How to resolve the algorithm N-queens problem step by step in the Seed7 programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm N-queens problem step by step in the Seed7 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 Seed7 programming language

Source code in the seed7 programming language

$ include "seed7_05.s7i";

var array integer: board is 8 times 0;
var integer: solutionNum is 0;

const func boolean: safe (in integer: y) is func
  result
    var boolean: safe is TRUE;
  local
    var integer: i is 1;
  begin
    while i < y and safe do
      safe := board[y - i] <> board[y] and
              board[y - i] <> board[y] - i and
              board[y - i] <> board[y] + i;
      incr(i);
    end while;
  end func;

const proc: putBoard is func
  local
    var integer: y is 0;
  begin
    incr(solutionNum);
    writeln;
    writeln("Solution " <& solutionNum);
    for y range 1 to 8 do
      writeln("|_" mult pred(board[y]) <& "|Q" <& "|_" mult (8 - board[y]) <& "|");
    end for;
  end func;

const proc: main is func
  local
    var integer: y is 1;
  begin
    while y >= 1 do
      repeat
        incr(board[y]);
      until board[y] > 8 or safe(y);
      if board[y] <= 8 then
        if y < 8 then
          incr(y);
          board[y] := 0;
        else
          putBoard;
        end if;
      else
        decr(y);
      end if;
    end while;
  end func;

  

You may also check:How to resolve the algorithm Wireworld step by step in the Ursala programming language
You may also check:How to resolve the algorithm Call an object method step by step in the SuperCollider programming language
You may also check:How to resolve the algorithm Long primes step by step in the Prolog programming language
You may also check:How to resolve the algorithm Sorting algorithms/Quicksort step by step in the jq programming language
You may also check:How to resolve the algorithm Case-sensitivity of identifiers step by step in the J programming language