ex2.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. N = 8 -- board size
  2. -- check whether position (n,c) is free from attacks
  3. local function isplaceok(a, n, c)
  4. for i = 1, n - 1 do -- for each queen already placed
  5. if (a[i] == c) or -- same column?
  6. (a[i] - i == c - n) or -- same diagonal?
  7. (a[i] + i == c + n) then -- same diagonal?
  8. return false -- place can be attacked
  9. end
  10. end
  11. return true -- no attacks; place is OK
  12. end
  13. -- print a board
  14. local function printsolution(a)
  15. for i = 1, N do -- for each row
  16. for j = 1, N do -- and for each column
  17. -- write "X" or "-" plus a space
  18. io.write(a[i] == j and "X" or "-", " ")
  19. end
  20. io.write("\n")
  21. end
  22. io.write("\n")
  23. end
  24. local function reverse(a, s, e)
  25. for i = s, e / 2 do
  26. local counter_i = e - (i - 1)
  27. local tmp = a[i]
  28. a[i] = a[counter_i]
  29. a[counter_i] = tmp
  30. end
  31. end
  32. local function generatePermutations()
  33. local p1 = { 1, 2, 3, 4, 5, 6, 7, 8}
  34. local ps = {p1}
  35. while true do
  36. local newP = {}
  37. local last_p = ps[#ps]
  38. for i = 1, #last_p do
  39. newP[i] = last_p[i]
  40. end
  41. local k = nil
  42. for i = #newP, 1, -1 do
  43. if newP[i + 1] == nil then
  44. goto continue
  45. end
  46. if newP[i] < newP[i + 1] then
  47. k = i
  48. break
  49. end
  50. ::continue::
  51. end
  52. if k == nil then
  53. break
  54. end
  55. local l = nil
  56. for i = #newP, 1, -1 do
  57. if newP[k] < newP[i] then
  58. l = i
  59. break
  60. end
  61. end
  62. if l == nil then
  63. print("ERROR: l was nil")
  64. os.exit(1)
  65. end
  66. local tmp = newP[k]
  67. newP[k] = newP[l]
  68. newP[l] = tmp
  69. reverse(newP, k + 1, #newP)
  70. print(k, l)
  71. table.insert(ps, newP)
  72. end
  73. return ps
  74. end
  75. local perms = generatePermutations()
  76. for i = 1, #perms do
  77. print(table.unpack(perms[i]))
  78. end
  79. print(#perms)