Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. ##
  2. ## INPUT
  3. ## 4
  4. ## OUTPUT
  5. ## [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
  6. ##
  7. def tsm(n)
  8. sqr = n * n
  9.  
  10. ## construct the matrix
  11. arr, b, c = [], [], []
  12. for i in 1..sqr
  13. c << i
  14. if i % n == 0
  15. arr << c
  16. c = []
  17. end
  18. end
  19.  
  20. ## Denotes indices to read the values at
  21. ## Also to determine if path exists
  22. i, j = 0, 0
  23.  
  24. ## Provides direction
  25. r, d, l, u = true, false, false, false
  26.  
  27. while true
  28. break if b.length == sqr - 1
  29. b << arr[i][j]
  30. arr[i][j] = nil ## mark as read
  31. case true
  32. when r
  33. ## right
  34. if j+1 < arr[i].length && arr[i][j+1] != nil
  35. j += 1
  36. else
  37. ## move down
  38. r, d, l, u = false, true, false, false
  39. i += 1
  40. end
  41. when d
  42. ## down
  43. if i+1 < arr.length && arr[i+1][j] != nil
  44. i += 1
  45. else
  46. ## move left
  47. r, d, l, u = false, false, true, false
  48. j -= 1
  49. end
  50. when l
  51. ## left
  52. if j > 0 && arr[i][j-1] != nil
  53. j -= 1
  54. else
  55. ## move up
  56. r, d, l, u = false, false, false, true
  57. i -= 1
  58. end
  59. when u
  60. if i > 0 && arr[i-1][j] != nil
  61. i -= 1
  62. else
  63. ## move right
  64. r, d, l, u = true, false, false, false
  65. j += 1
  66. end
  67. end
  68. end
  69. b << arr[i][j] unless arr[i][j].nil?
  70. b
  71. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement