fork(4) download
  1. def output_spiral(n)
  2. #For formatting, determine the length of the largest number
  3. max_number_length = n.to_s.length
  4.  
  5. #Determine matrix size
  6. max_x = Math.sqrt(n).floor
  7. max_y = Math.sqrt(n).floor
  8. if max_x * max_y < n
  9. max_x += 1
  10. if max_x * max_y < n
  11. max_y += 1
  12. end
  13. end
  14.  
  15. #The a matrix of the required size.
  16. #Note that for simplicity in printing spiral is an array of row arrays.
  17. spiral = Array.new
  18. row = Array.new(max_x){ |i| ' ' }
  19. max_y.times{ spiral << row.clone }
  20.  
  21. #Determine the starting point index (ie where to insert 1)
  22. x = ((max_x-1)/2).floor
  23. y = ((max_y-1)/2).floor
  24.  
  25. #Input the start point value, formatted to the right size
  26. spiral[y][x] = "%0#{max_number_length}d" % 1
  27.  
  28. #Setup counters required to iterate through the spiral
  29. steps_in_direction = 1 #This defines how many steps to take in a direction
  30. steps_count = 0 #This defines how many steps have been taken in the direction
  31. direction = 'right' #This defines the direction currently travelling
  32. steps_in_direction_count = 0 #This define how many times we have used the same steps_in_direction value
  33.  
  34. #Iterate through all the numbers up to n
  35. 2.upto(n) do |i|
  36. #Change index based on the direction we are travelling
  37. case direction
  38. when 'right' then x += 1
  39. when 'down' then y += 1
  40. when 'left' then x -= 1
  41. when 'up' then y -= 1
  42. end
  43.  
  44. #Input the value, formatted to the right size
  45. spiral[y][x] = "%0#{max_number_length}d" % i
  46.  
  47. #Increment counters
  48. steps_count += 1
  49. if steps_count == steps_in_direction
  50. steps_count = 0
  51. steps_in_direction_count += 1
  52.  
  53. if steps_in_direction_count == 2
  54. steps_in_direction += 1
  55. steps_in_direction_count = 0
  56. end
  57.  
  58. case direction
  59. when 'right' then direction = 'down'
  60. when 'down' then direction = 'left'
  61. when 'left' then direction = 'up'
  62. when 'up' then direction = 'right'
  63. end
  64. end
  65.  
  66. end
  67.  
  68. #Output spiral
  69. spiral.each do |x|
  70. puts x.join(' ')
  71. end
  72. end
  73.  
  74. output_spiral(95)
Success #stdin #stdout 0.01s 4760KB
stdin
Standard input is empty
stdout
73 74 75 76 77 78 79 80 81 82
72 43 44 45 46 47 48 49 50 83
71 42 21 22 23 24 25 26 51 84
70 41 20 07 08 09 10 27 52 85
69 40 19 06 01 02 11 28 53 86
68 39 18 05 04 03 12 29 54 87
67 38 17 16 15 14 13 30 55 88
66 37 36 35 34 33 32 31 56 89
65 64 63 62 61 60 59 58 57 90
               95 94 93 92 91