How to resolve the algorithm N-queens problem step by step in the Nim programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm N-queens problem step by step in the Nim programming language
Table of Contents
Problem Statement
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN. For the number of solutions for small values of N, see OEIS: A000170.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm N-queens problem step by step in the Nim programming language
Source code in the nim programming language
const BoardSize = 8
proc underAttack(col: int; queens: seq[int]): bool =
if col in queens: return true
for i, x in queens:
if abs(col - x) == queens.len - i:
return true
return false
proc solve(n: int): seq[seq[int]] =
result = newSeq[seq[int]]()
result.add(@[])
var newSolutions = newSeq[seq[int]]()
for row in 1..n:
for solution in result:
for i in 1..BoardSize:
if not underAttack(i, solution):
newSolutions.add(solution & i)
swap result, newSolutions
newSolutions.setLen(0)
echo "Solutions for a chessboard of size ", BoardSize, 'x', BoardSize
echo ""
for i, answer in solve(BoardSize):
for row, col in answer:
if row > 0: stdout.write ' '
stdout.write chr(ord('a') + row), col
stdout.write if i mod 4 == 3: "\n" else: " "
You may also check:How to resolve the algorithm Ulam spiral (for primes) step by step in the Delphi programming language
You may also check:How to resolve the algorithm Pascal's triangle step by step in the jq programming language
You may also check:How to resolve the algorithm Arithmetic evaluation step by step in the Java programming language
You may also check:How to resolve the algorithm Morse code step by step in the Ring programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Miranda programming language