Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/bench/tests/shootout/queen.lua
2727 views
1
--[[
2
MIT License
3
4
Copyright (c) 2017 Gabriel de Quadros Ligneul
5
6
Permission is hereby granted, free of charge, to any person obtaining a copy
7
of this software and associated documentation files (the "Software"), to deal
8
in the Software without restriction, including without limitation the rights
9
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
copies of the Software, and to permit persons to whom the Software is
11
furnished to do so, subject to the following conditions:
12
13
The above copyright notice and this permission notice shall be included in all
14
copies or substantial portions of the Software.
15
16
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
SOFTWARE.
23
]]
24
local function prequire(name) local success, result = pcall(require, name); return success and result end
25
local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support")
26
27
function test()
28
29
local N = tonumber((arg and arg[1]) or 8) -- board size
30
31
32
-- check whether position (n,c) is free from attacks
33
local function isplaceok (a, n, c)
34
for i = 1, n - 1 do -- for each queen already placed
35
if (a[i] == c) or -- same column?
36
(a[i] - i == c - n) or -- same diagonal?
37
(a[i] + i == c + n) then -- same diagonal?
38
return false -- place can be attacked
39
end
40
end
41
return true -- no attacks; place is OK
42
end
43
44
45
-- print a board
46
local function printsolution (a)
47
for i = 1, N do
48
for j = 1, N do
49
--print(a[i] == j and "X" or "-", " ")
50
end
51
--print("\n")
52
end
53
--print("\n")
54
end
55
56
57
-- add to board 'a' all queens from 'n' to 'N'
58
local function addqueen (a, n)
59
if n > N then -- all queens have been placed?
60
printsolution(a)
61
else -- try to place n-th queen
62
for c = 1, N do
63
if isplaceok(a, n, c) then
64
a[n] = c -- place n-th queen at column 'c'
65
addqueen(a, n + 1)
66
end
67
end
68
end
69
end
70
71
72
-- run the program
73
addqueen({}, 1)
74
75
end
76
77
bench.runCode(test, "queen")
78
79