fork download
  1. open System
  2. open System.IO
  3.  
  4. type Direction = UP | DOWN | LEFT | RIGHT
  5.  
  6. let rec fillSpiral (spiral:int[,]) num square goal curX curY direction =
  7. match num with
  8. | x when num=goal+1 -> spiral
  9. | _ ->
  10. spiral.[curX,curY] <- num
  11. let newDirection = match direction with
  12. | UP -> match curY with
  13. | a when curY=0 -> RIGHT
  14. | b when spiral.[curX,(curY-1)] <> -1 -> RIGHT
  15. | _ -> UP
  16. | DOWN -> match curY with
  17. | a when curY=square-1 -> LEFT
  18. | b when spiral.[curX,(curY+1)] <> -1 -> LEFT
  19. | _ -> DOWN
  20. | LEFT -> match curX with
  21. | a when curX=0 -> UP
  22. | b when spiral.[curX-1,curY] <> -1 -> UP
  23. | _ -> LEFT
  24. | RIGHT -> match curX with
  25. | a when curX=square-1 -> DOWN
  26. | b when spiral.[curX+1,curY] <> -1 -> DOWN
  27. | _ -> RIGHT
  28. let nextX = match newDirection with
  29. | LEFT -> curX-1
  30. | RIGHT -> curX+1
  31. | _ -> curX
  32. let nextY = match newDirection with
  33. | UP -> curY-1
  34. | DOWN -> curY+1
  35. | _ -> curY
  36. fillSpiral spiral (num+1) square goal nextX nextY newDirection
  37.  
  38. let makeSpiral num =
  39. let square = num*num
  40. let matrix = Array2D.init num num (fun x y -> -1)
  41. let spiral = fillSpiral matrix 1 num square 0 0 RIGHT
  42. let alignment = ((log (square |> double))) |> int
  43. for y in [0..num-1] do
  44. for x in [0..num-1] do
  45. printf "%*d " alignment spiral.[x,y]
  46. printfn ""
  47. ()
  48.  
  49. [<EntryPoint>]
  50. let main argv =
  51. makeSpiral 4
  52. printfn ""
  53. makeSpiral 5
  54. 0
Success #stdin #stdout 0.02s 132800KB
stdin
Standard input is empty
stdout
 1  2  3  4 
12 13 14  5 
11 16 15  6 
10  9  8  7 

  1   2   3   4   5 
 16  17  18  19   6 
 15  24  25  20   7 
 14  23  22  21   8 
 13  12  11  10   9