خوب من هم برای مثال یک الگوریتم یکسان رو در پایتون و go میارم (با C++ هم نوشته بودم ولی پیداش نمیکنم و حال دوباره نویسی ندارم، ولی زمان اجراش با go زیاد فرقی نداره). الگوریتم تعداد جوابهای مسالهٔ n وزیر رو پیدا میکنه.
در PYTHON
#!/usr/bin/python3
import sys
import time
COUNT = 0
BOARD_SIZE = int(sys.argv[1])
ALL = (1<<BOARD_SIZE) - 1
def main():
start = time.clock()
putQueens(0, 0, 0)
elapsed = (time.clock() - start)
print(COUNT, "solutions to ", BOARD_SIZE,"queens in", elapsed, "seconds")
def putQueens(ld, cols, rd):
if cols == ALL:
global COUNT
COUNT += 1
return
pos = ~(ld | cols | rd) & ALL
while pos != 0:
bit = pos & -pos
pos -= bit
putQueens((ld|bit)<<1, cols|bit, (rd|bit)>>1)
if __name__ == "__main__":
main()
و در GO
package main
import (
"fmt"
"os"
"strconv"
"time"
)
var (
all int
count int
)
func main() {
var size int
size, _ = strconv.Atoi(os.Args[1])
all = 1<<uint(size) - 1
now := time.Now()
try(0, 0, 0)
then := time.Now()
fmt.Printf("%d solutions to %d-queens in %f seconds", count, size, then.Sub(now).Seconds())
}
func try(ld int, cols int, rd int) {
if cols == all {
count++
return
}
pos := ^(ld | cols | rd) & all
for pos != 0 {
bit := pos & -pos
pos -= bit
try((ld|bit)<<1, cols|bit, (rd|bit)>>1)
}
}
و این هم زمانهای اجرا برای هر دو
در python
92 solutions to 8 queens in 0.0033359999999999987 seconds
352 solutions to 9 queens in 0.013877000000000007 seconds
724 solutions to 10 queens in 0.064723 seconds
2680 solutions to 11 queens in 0.292063 seconds
14200 solutions to 12 queens in 1.542927 seconds
73712 solutions to 13 queens in 7.767173 seconds
365596 solutions to 14 queens in 43.817662000000006 seconds
2279184 solutions to 15 queens in 272.59477599999997 seconds
در go
92 solutions to 8-queens in 0.000087 seconds
352 solutions to 9-queens in 0.000325 seconds
724 solutions to 10-queens in 0.001371 seconds
2680 solutions to 11-queens in 0.003151 seconds
14200 solutions to 12-queens in 0.012581 seconds
73712 solutions to 13-queens in 0.064506 seconds
365596 solutions to 14-queens in 0.358315 seconds
2279184 solutions to 15-queens in 2.234746 seconds
14772512 solutions to 16-queens in 14.877159 seconds