How to resolve the algorithm Knight's tour step by step in the Picat programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Knight's tour step by step in the Picat programming language

Table of Contents

Problem Statement

Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Knight's tour step by step in the Picat programming language

Source code in the picat programming language

import cp.

main =>
    N = 8,
    A = new_array(N,N),
    foreach (R in 1..N, C in 1..N)
        Connected = [(R+1, C+2),
                     (R+1, C-2),
                     (R-1, C+2),
                     (R-1, C-2),
                     (R+2, C+1),
                     (R+2, C-1),
                     (R-2, C+1),
                     (R-2, C-1)],
        A[R,C] :: [(R1-1)*N+C1 : (R1,C1) in Connected, R1 >= 1, R1 =< N, C1 >= 1, C1 =< N]
    end,
    V = vars(A),
    circuit(V),
    solve([ff],V),
    OutputM = new_array(N,N),
    fill_output_matrix(N,OutputM,V,1,1),
    foreach (R in 1..N)
        foreach (C in 1..N)
            printf("%3d ", OutputM[R,C])
        end,
        nl
    end.

fill_output_matrix(N,OutputM,V,I,Count) =>
    if Count =< N*N then
        R = (I-1) div N + 1,
        C = (I-1) mod N + 1,
        OutputM[R,C] = Count,
        fill_output_matrix(N,OutputM,V,V[I],Count+1)
    end.

  

You may also check:How to resolve the algorithm Greatest element of a list step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Thue-Morse step by step in the 8080 Assembly programming language
You may also check:How to resolve the algorithm Sequence of non-squares step by step in the Seed7 programming language
You may also check:How to resolve the algorithm RCRPG step by step in the Rust programming language
You may also check:How to resolve the algorithm Even or odd step by step in the Kotlin programming language