Advertisement
Icytroll

Day 3.1

Dec 22nd, 2017
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.11 KB | None | 0 0
  1. % First star
  2. % I think I found a pretty little solution for the first star where I
  3. % avoid doing a lot of matrix manuevering.
  4. % Because the squares of numbers follow two separate diagonal lines
  5. % throughout the grid, I can deduce where my input number is located.
  6. % Afterwards a little addition/subtraction is needed to calculate the
  7. % manhatten distance to the center of the grid.
  8.  
  9. input = 347991;
  10.  
  11. % Square number counter
  12. x = 0;
  13. while x^2 < input
  14.     x = x + 1;
  15. end
  16.  
  17. x = x - 1;
  18.  
  19. if mod(x,2) == 1
  20.     if (x+1)^2 - input == input - (x^2+1)
  21.         steps = x + 1;
  22.     elseif (x+1)^2 - input < input - (x^2+1)
  23.         row = abs(((x+1)^2 - (x-1)/2) - input);
  24.         steps = (x+1)/2 + row;
  25.     else
  26.         col = abs((x^2+1 + (x-1)/2) - input);
  27.         steps = (x+1)/2 + col;
  28.     end
  29. else
  30.     if (x+1)^2 - input == input - (x^2+1)
  31.         steps = x;
  32.     elseif (x+1)^2 - input < input - (x^2+1)
  33.         row = abs(((x+1)^2 - x/2) - input);
  34.         steps = x/2 + row;
  35.     else
  36.         col = abs((x^2+1 + x/2) - input);
  37.         steps = x/2 + col;
  38.     end
  39. end
  40.  
  41. fprintf('Number of steps: %d\n',steps)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement