How to resolve the algorithm Find Chess960 starting position identifier step by step in the Nim programming language
How to resolve the algorithm Find Chess960 starting position identifier step by step in the Nim programming language
Table of Contents
Problem Statement
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number ("SP-ID"), and generate the corresponding position. This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array QNRBBNKR (or ♕♘♖♗♗♘♔♖ or ♛♞♜♝♝♞♚♜), which we assume is given as seen from White's side of the board from left to right, your (sub)program should return 105; given the starting lineup of standard chess, it should return 518. You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional. The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example).
- Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=NN---, 1=N-N--, 2=N--N-, 3=N---N, 4=-NN--, etc; our pair is combination number 5. Call this number N. N=5
- Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, Q=2.
- Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (D=1), and the light bishop is on square 2 (L=2).
- Then the position number is given by 4(4(6N + Q)+D)+L, which reduces to 96N + 16Q + 4D + L. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518. Note that an earlier iteration of this page contained an incorrect description of the algorithm which would give the same SP-ID for both of the following two positions.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Find Chess960 starting position identifier step by step in the Nim programming language
Source code in the nim programming language
import sequtils, strformat, strutils, sugar, tables, unicode
type Piece {.pure.} = enum Rook = "R", Knight = "N", Bishop = "B", Queen = "Q", King = "K"
const
GlypthToPieces = {"♜": Rook, "♞": Knight, "♝": Bishop, "♛": Queen, "♚": King,
"♖": Rook, "♘": Knight, "♗": Bishop, "♕": Queen, "♔": King}.toTable
Names = [Rook: "rook", Knight: "knight", Bishop: "bishop", Queen: "queen", King: "king"]
NTable = {[0, 1]: 0, [0, 2]: 1, [0, 3]: 2, [0, 4]: 3, [1, 2]: 4,
[1, 3]: 5, [1, 4]: 6, [2, 3]: 7, [2, 4]: 8, [3, 4]: 9}.toTable
func toPieces(glyphs: string): seq[Piece] =
collect(newSeq, for glyph in glyphs.runes: GlypthToPieces[glyph.toUTF8])
func isEven(n: int): bool = (n and 1) == 0
func positions(pieces: seq[Piece]; piece: Piece): array[2, int] =
var idx = 0
for i, p in pieces:
if p == piece:
result[idx] = i
inc idx
func spid(glyphs: string): int =
let pieces = glyphs.toPieces()
# Check for errors.
if pieces.len != 8:
raise newException(ValueError, "there must be exactly 8 pieces.")
for piece in [King, Queen]:
if pieces.count(piece) != 1:
raise newException(ValueError, &"there must be one {Names[piece]}.")
for piece in [Rook, Knight, Bishop]:
if pieces.count(piece) != 2:
raise newException(ValueError, &"there must be two {Names[piece]}s.")
let r = pieces.positions(Rook)
let k = pieces.find(King)
if k < r[0] or k > r[1]:
raise newException(ValueError, "the king must be between the rooks.")
var b = pieces.positions(Bishop)
if isEven(b[1] - b[0]):
raise newException(ValueError, "the bishops must be on opposite color squares.")
# Compute SP_ID.
let piecesN = pieces.filterIt(it notin [Queen, Bishop])
let n = NTable[piecesN.positions(Knight)]
let piecesQ = pieces.filterIt(it != Bishop)
let q = piecesQ.find(Queen)
if b[1].isEven: swap b[0], b[1]
let d = [0, 2, 4, 6].find(b[0])
let l = [1, 3, 5, 7].find(b[1])
result = 96 * n + 16 * q + 4 * d + l
for glyphs in ["♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖", "♖♕♘♗♗♔♖♘", "♖♘♕♗♗♔♖♘"]:
echo &"{glyphs} or {glyphs.toPieces().join()} has SP-ID of {glyphs.spid()}"
You may also check:How to resolve the algorithm Runge-Kutta method step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Program termination step by step in the Haskell programming language
You may also check:How to resolve the algorithm Dragon curve step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Sort three variables step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Calendar step by step in the zkl programming language