Generate Chess960 starting position: Difference between revisions
Generate Chess960 starting position (view source)
Revision as of 12:16, 17 March 2024
, 2 months ago→{{header|EasyLang}}
m (→{{header|Phix}}: added syntax colouring, marked p2js compatible) |
|||
(18 intermediate revisions by 14 users not shown) | |||
Line 13:
;Task:
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed
<br><br>
Line 19:
{{trans|Python: Correct by construction}}
<
V start = [‘R’, ‘K’, ‘R’]
Line 30:
R start
print(random960())</
{{out}}
Line 38:
=={{header|Action!}}==
<
DEFINE MAX_LEN="20"
DEFINE MAX_FACTORS="5"
Line 130:
PutE()
PrintResult(max,n,factors,texts)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Generate_Chess960_starting_position_.png Screenshot from Atari 8-bit computer]
Line 145:
RNQBKRBN
</pre>
=={{header|APL}}==
This function accepts a SP-ID and generates the corresponding position; to generate a random one, just pass in roll 960 (<tt>?960</tt>). (It's written for index origin 1, but reduces the passed-in SP-ID modulo 960 so that works without having to subtract 1 from the roll result.)
{{works with|Dyalog APL}}
{{works with|GNU APL}}
<syntaxhighlight lang="apl">⍝ Utility functions
divmod ← {(⌊⍺÷⍵),⍵|⍺}
indices ← {(⍺∊⍵)/⍳⍴⍺}
∇result ← place placement; array; index; piece; result
(array piece index) ← placement
array[(array indices '-')[index]] ← piece
result ← array
∇
∇result ← chess960 spid; array; n; b1; b2; n1; n2; q
spid ← 960 | spid
array ← 8/'-'
(n b1) ← spid divmod 4
array[2+2×b1] ← 'B'
(n b2) ← n divmod 4
array[1+2×b2] ← 'B'
(n q) ← n divmod 6
array ← place array 'Q' (1+q)
n1 ← 1⍳⍨n<4 7 9 10
array ← place array 'N' n1
n2 ← (1 2 3 4 2 3 4 3 4 4)[n+1]
array ← place array 'N' n2
array ← place array 'R' 1
array ← place array 'K' 1
array ← place array 'R' 1
result ← spid, array
∇</syntaxhighlight>
{{Out}}
<pre> chess960 518
518 RNBQKBNR
chess960 ?960
377 NRKBBRNQ
chess960 ?960
487 QRBNKNRB</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">; Using Edward Collins' single-die method
; http://www.edcollins.com/chess/fischer-random.htm
chess960: function [][
result: array.of: 8 ø
vacant: @0..7 ; open squares available to put pieces
result\[remove 'vacant <= 2 * random 0 3]: 'bishop ; place on random black square
result\[remove 'vacant <= 1 + 2 * random 0 3]: 'bishop ; place on random white square
loop ['queen 'knight 'knight] 'piece [
result\[remove 'vacant <= sample vacant]: piece ; place on random open square
]
result\[vacant\0]: 'rook ; place king between rooks on remaining open squares
result\[vacant\1]: 'king
result\[vacant\2]: 'rook
result
]
do.times:5 -> print chess960</syntaxhighlight>
{{out}}
<pre>bishop knight rook queen king knight rook bishop
knight rook queen bishop bishop king knight rook
rook bishop bishop knight knight king rook queen
bishop knight rook queen king knight rook bishop
rook king knight knight bishop queen rook bishop</pre>
=={{header|AutoHotkey}}==
{{works with|AutoHotkey 1.1}}
<
Out .= Chess960() "`n"
MsgBox, % RTrim(Out, "`n")
Line 180 ⟶ 249:
Random, n, Min, Max
return n
}</
{{Output}}
<big><big><pre>♕♘♖♗♗♘♔♖
Line 191 ⟶ 260:
==={{header|BASIC256}}===
{{trans|Yabasic}}
<
inicio$ = "RKR"
pieza$ = "QNN"
Line 205 ⟶ 274:
print inicio$
next i
end</
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> VDU 23, 22, 240; 360; 8, 16, 16, 136
*FONT Arial, 20
FOR I% = 1 TO 10
Rank1$ = "202"
FOR Piece = 1 TO 3
P% = RND(LENRank1$ + 1)
Rank1$ = LEFT$(Rank1$, P% - 1) + MID$("144", Piece, 1) + MID$(Rank1$, P%)
NEXT
P% = RND(7)
Rank1$ = LEFT$(Rank1$, P% - 1) + "3" + MID$(Rank1$, P%)
IF P% > 5 P% += 1 ELSE P% += RND(4 - (P% >> 1)) * 2 - 1
Rank1$ = LEFT$(Rank1$, P% - 1) + "3" + MID$(Rank1$, P%)
FOR Piece = 1 TO 8
VDU &E2, &99, &94 + VALMID$(Rank1$, Piece, 1)
NEXT
PRINT
NEXT</syntaxhighlight>
{{out}}
<pre>♘ ♖ ♗ ♔ ♖ ♘ ♕ ♗
♘ ♖ ♔ ♘ ♕ ♖ ♗ ♗
♕ ♗ ♖ ♔ ♗ ♘ ♖ ♘
♖ ♘ ♔ ♗ ♖ ♕ ♗ ♘
♖ ♗ ♗ ♘ ♔ ♖ ♘ ♕
♘ ♖ ♗ ♗ ♕ ♔ ♘ ♖
♖ ♔ ♕ ♘ ♗ ♘ ♖ ♗
♘ ♘ ♖ ♔ ♖ ♗ ♗ ♕
♖ ♕ ♔ ♘ ♗ ♗ ♖ ♘
♖ ♕ ♔ ♘ ♘ ♗ ♗ ♖</pre>
==={{header|Commodore BASIC}}===
{{works with|Commodore BASIC|3.5,7.0}}
Besides the admittedly-trivial use of <tt>DO</tt>/<tt>LOOP</tt>, this implementation also exploits the BASIC 3.5+ ability to use <tt>MID$</tt> as an lvalue.
<
110 PRINT "SPID (-1 FOR RANDOM):";
120 OPEN 1,0:INPUT#1, SP$:CLOSE 1
Line 250 ⟶ 350:
510 NEXT I
520 RETURN
</syntaxhighlight>
Here's a version that doesn't use the advanced features:
{{works with|Commodore BASIC|2.0}}
<
110 PRINT "SPID (-1 FOR RANDOM):";
120 OPEN 1,0:INPUT#1, SP$:CLOSE 1
Line 294 ⟶ 394:
480 : N=N-1
510 NEXT I
520 RETURN</
{{Out}}
Line 313 ⟶ 413:
==={{header|FreeBASIC}}===
{{trans|Yabasic}}
<
Randomize Timer
For i As Byte = 1 To 10
Line 331 ⟶ 431:
Print inicio
Next i
</syntaxhighlight>
==={{header|QBasic}}===
{{trans|Yabasic}}
<
FOR i = 1 TO 10
Line 352 ⟶ 452:
PRINT inicio$
NEXT i
END</
==={{header|Yabasic}}===
{{trans|Seed7}}
<
piece$ = "QNN"
Line 368 ⟶ 468:
start$ = left$(start$, pos-1) + "B" + right$(start$, len(start$) - pos + 1)
print start$
</syntaxhighlight>
=={{header|Befunge}}==
Similar to the [[Generate_Chess960_starting_position#Ruby:_Generate_from_SP-ID|Ruby SP-ID solution]], this generates the start position for a random number in the [[wp:Chess960 numbering scheme|Chess960 numbering scheme]].
<
v,":".:%*8"x"$<^!:\*2<+<
>48*,:4%2*1#v+#02#\3#g<<
Line 382 ⟶ 482:
>"RKRNN"11g:!#v_\$\$\$\v
v _v#!`*86:g0:<^!:-1$\$<
>$\>,1+ :7`#@_^> v960v <</
{{out}}
<pre>856 : RBKNBRNQ</pre>
Line 388 ⟶ 488:
=={{header|C}}==
As noted in the C implementation for the [[Sparkline in unicode]] task, unicode output is reliable only on Linux/Unix systems. This implementation thus has compiler directives to check whether the underlying system is Windows or Linux, if Windows, only letters are printed, otherwise Unicode output is displayed. 9 rows are displayed.
<
#include<locale.h>
#include<wchar.h>
Line 490 ⟶ 590:
return 0;
}
</syntaxhighlight>
Output on Linux :
<pre>♗♗♖♕♘♘♔♖
Line 511 ⟶ 611:
RNKBNRBQ
QNRBBNKR</pre>
=={{header|C#}}==
{{trans|Go}}
<syntaxhighlight lang="C#">
using System;
class Program
{
struct Symbols
{
public char K, Q, R, B, N;
public Symbols(char k, char q, char r, char b, char n)
{
K = k; Q = q; R = r; B = b; N = n;
}
}
private static Symbols A = new Symbols('K', 'Q', 'R', 'B', 'N');
private static Symbols W = new Symbols('♔', '♕', '♖', '♗', '♘');
private static Symbols B = new Symbols('♚', '♛', '♜', '♝', '♞');
private static string[] krn = new string[]
{
"nnrkr", "nrnkr", "nrknr", "nrkrn",
"rnnkr", "rnknr", "rnkrn",
"rknnr", "rknrn",
"rkrnn"
};
private static string Chess960(Symbols sym, int id)
{
char[] pos = new char[8];
int q = id / 4, r = id % 4;
pos[r * 2 + 1] = sym.B;
r = q % 4; q /= 4;
pos[r * 2] = sym.B;
r = q % 6; q /= 6;
int placementIndex = 0; // Adjusted variable name to prevent conflict
for (int i = 0; ; i++)
{
if (pos[i] != '\0') continue;
if (r == 0)
{
pos[i] = sym.Q;
break;
}
r--;
}
while (pos[placementIndex] != '\0') placementIndex++; // Adjusted loop to prevent conflict
foreach (char f in krn[q])
{
while (pos[placementIndex] != '\0') placementIndex++;
switch (f)
{
case 'k':
pos[placementIndex] = sym.K;
break;
case 'r':
pos[placementIndex] = sym.R;
break;
case 'n':
pos[placementIndex] = sym.N;
break;
}
}
return new string(pos);
}
static void Main(string[] args)
{
Console.WriteLine(" ID Start position");
foreach (int id in new int[] { 0, 518, 959 })
{
Console.WriteLine($"{id,3} {Chess960(A, id)}");
}
Console.WriteLine("\nRandom");
Random rand = new Random();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(Chess960(W, rand.Next(960)));
}
}
}
</syntaxhighlight>
{{out}}
<pre>
ID Start position
0 BBQNNRKR
518 RNBQKBNR
959 RKRNNQBB
Random
♘♕♖♔♗♖♘♗
♗♗♖♘♔♖♕♘
♖♕♘♔♖♗♗♘
♘♖♗♔♘♗♖♕
♖♘♕♗♔♘♗♖
</pre>
=={{header|C++}}==
<
#include <string>
#include <time.h>
Line 570 ⟶ 771:
return system( "pause" );
}
</syntaxhighlight>
{{out}}
<pre>NQBRNBKR
Line 584 ⟶ 785:
=={{header|Clojure}}==
<
(:gen-class)
(:require [clojure.string :as s]))
Line 621 ⟶ 822:
;; => "♖, ♕, ♘, ♔, ♗, ♗, ♘, ♖"
(c960 4)
;; => ("♘, ♖, ♔, ♘, ♗, ♗, ♖, ♕" "♗, ♖, ♔, ♘, ♘, ♕, ♖, ♗" "♘, ♕, ♗, ♖, ♔, ♗, ♘, ♖" "♖, ♔, ♘, ♘, ♕, ♖, ♗, ♗")</
=={{header|Common Lisp}}==
Line 627 ⟶ 828:
===Common Lisp: generate from SP-ID===
{{trans|Raku}}
<
(&optional (sp-id (random 360 (make-random-state t))))
(labels
Line 679 ⟶ 880:
(format t "~a~%" (chess960-from-sp-id 518))
(format t "~a~%" (chess960-from-sp-id))</
{{Out}}<pre>(518 #(♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜))
Line 688 ⟶ 889:
===D: Indexing===
<
import std.stdio, std.range, std.algorithm, std.string, permutations2;
Line 700 ⟶ 901:
.map!toUpper.array.sort().uniq;
writeln(starts.walkLength, "\n", starts.front);
}</
{{out}}
<pre>960
Line 706 ⟶ 907:
===D: Regexp===
<
import std.stdio, std.regex, std.range, std.algorithm, permutations2;
Line 716 ⟶ 917:
.array.sort().uniq;
writeln(starts3.walkLength, "\n", starts3.front);
}</
The output is the same.
===D: Correct by construction===
<
import std.stdio, std.random, std.array, std.range;
Line 732 ⟶ 933:
start.insertInPlace(iota(bishpos % 2, start.length, 2)[uniform(0,$)], 'B');
start.writeln;
}</
{{out}}
<pre>QBNNBRKR</pre>
=={{header|EasyLang}}==
{{trans|Lua}}
<syntaxhighlight>
len t$[] 8
proc randins c$ l r . pos .
repeat
pos = randint (r - l + 1) + l - 1
until t$[pos] = ""
.
t$[pos] = c$
.
randins "K" 2 7 king
randins "R" 1 (king - 1) h
randins "R" (king + 1) 8 h
randins "B" 1 8 b1
repeat
randins "B" 1 8 b2
until (b2 - b1) mod 2 <> 0
t$[b2] = ""
.
randins "Q" 1 8 b1
randins "N" 1 8 b1
randins "N" 1 8 b1
print strjoin t$[]
</syntaxhighlight>
{{out}}
<pre>
RBBNQNKR
</pre>
=={{header|EchoLisp}}==
<
(define *pos* (list R N B Q K B N R)) ;; standard starter
Line 752 ⟶ 983:
(if (legal-pos *pos*)
(map unicode-piece *pos*) (c960)))
</syntaxhighlight>
{{out}}
<pre>(define (unicode-piece i) (unicode->string (+ 0x2654 i)))
Line 769 ⟶ 1,000:
{{works with|Elixir|1.1}}
===Elixir: shuffle pieces until all regexes match===
<
@pieces ~w(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖) # ~w(K Q N N B B R R)
@regexes [~r/♗(..)*♗/, ~r/♖.*♔.*♖/] # [~r/B(..)*B/, ~r/R.*K.*R/]
Line 779 ⟶ 1,010:
end
Enum.each(1..5, fn _ -> IO.puts Chess960.shuffle end)</
{{out}}
<pre>♘♗♘♖♗♔♕♖
Line 788 ⟶ 1,019:
===Elixir: Construct===
<
def construct do
row = Enum.reduce(~w[♕ ♘ ♘], ~w[♖ ♔ ♖], fn piece,acc ->
Line 800 ⟶ 1,031:
end
Enum.each(1..5, fn _ -> IO.puts Chess960.construct end)</
{{out}}
<pre>♖♔♗♘♖♕♘♗
Line 809 ⟶ 1,040:
===Elixir: Generate from SP-ID===
<
@krn ~w(NNRKR NRNKR NRKNR NRKRN RNNKR RNKNR RNKRN RKNNR RKNRN RKRNN)
Line 839 ⟶ 1,070:
end)
IO.puts "\nGenerate random Start Position"
Enum.each(1..5, fn _ -> IO.puts Chess960.start_position end)</
{{out}}
<pre>Generate Start Position from ID number
Line 856 ⟶ 1,087:
===Single die method===
Using the single die method: https://en.wikipedia.org/wiki/Chess960_starting_position#Single_die_method
<
IN: rosetta-code.chess960
Line 883 ⟶ 1,114:
: chess960-demo ( -- ) 5 [ chess960 print ] times ;
MAIN: chess960-demo</
{{out}}
<pre>
Line 895 ⟶ 1,126:
===Built-in===
Factor comes with a chess960 position generator:
<
chess960-position .</
{{out}}
<pre>
Line 905 ⟶ 1,136:
=={{header|Forth}}==
<
\ 0 1 2 3 4 5 6 7 8 9
Line 924 ⟶ 1,155:
959 chess960 \ RKRNNQBB ok
960 choose chess960 \ random position</
=={{header|Fortran}}==
This implementation simply iterates through all 960 positions.
<
implicit none
Line 985 ⟶ 1,216:
end program chess960
</syntaxhighlight>
{{out}}
The first ten positions:
Line 1,001 ⟶ 1,232:
=={{header|Go}}==
{{trans|Ruby}}
<
import (
Line 1,063 ⟶ 1,294:
fmt.Println(W.chess960(rand.Intn(960)))
}
}</
{{out}}
<pre> ID Start position
Line 1,078 ⟶ 1,309:
=={{header|Haskell}}==
<
import qualified Data.Set as Set
Line 1,092 ⟶ 1,323:
main :: IO ()
main = mapM_ (putStrLn . concatMap show) . Set.toList . Set.fromList
. filter isChess960 $ permutations [R,N,B,Q,K,B,N,R]</
{{out}}
<pre>QRKRBBNN
Line 1,102 ⟶ 1,333:
=={{header|J}}==
<
king=: u:9812
rook=: u:9814
Line 1,114 ⟶ 1,345:
perm=: A.&i.~ !
valid=: (#~ ok"1) ~.row0{"1~perm 8
gen=: valid {~ ? bind 960</
Example use:
<
♘♗♖♔♗♕♖♘
gen''
Line 1,125 ⟶ 1,356:
♖♗♔♘♘♕♗♖
gen''
♖♔♕♗♗♘♖♘</
=={{header|Java}}==
{{works with|Java|1.5+}}
Regex inspired by (original) [[#Python: Regexp|Python Regexp]], prints ten examples.
<
import java.util.Collections;
import java.util.List;
Line 1,156 ⟶ 1,387:
}
}
}</
{{out}}
<pre>[R, N, K, N, R, B, B, Q]
Line 1,171 ⟶ 1,402:
=={{header|JavaScript}}==
This conforms to Altendörfer's single die method[https://en.wikipedia.org/wiki/Chess960_starting_position#Single_die_method], though the die will give no "needless" numbers.
<
var rank = new Array(8),
// randomizer (our die)
Line 1,196 ⟶ 1,427:
// testing (10 times)
for (var x = 1; x <= 10; x++) console.log(ch960startPos().join(" | "));</
{{out}}
<p>The test-output (exemplary each):</p>
Line 1,209 ⟶ 1,440:
♗ | ♘ | ♖ | ♘ | ♕ | ♗ | ♔ | ♖<br/>
♘ | ♗ | ♖ | ♔ | ♗ | ♘ | ♖ | ♕<br/>
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
'''Also works with fq, a Go implementation of a large subset of jq'''
<syntaxhighlight lang=jq>
### Utilities
# The glyphs in .
def chars: explode[] | [.] | implode;
# input: an array
# $keys : an array of strings
def objectify($keys):
with_entries(.key = $keys[.key]) ;
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
def Symbols: ["k", "q", "r", "b", "n"];
def A: ["K", "Q", "R", "B", "N"] | objectify(Symbols);
def W: ["♔", "♕", "♖", "♗", "♘"] | objectify(Symbols);
def B: ["♚", "♛", "♜", "♝", "♞"] | objectify(Symbols);
def krn: [
"nnrkr", "nrnkr", "nrknr", "nrkrn",
"rnnkr", "rnknr", "rnkrn",
"rknnr", "rknrn",
"rkrnn"
];
# $sym specifies the Symbols
# $id specifies the position
def chess960($sym):
. as $id
| { q: (($id/4)|floor),
r: ($id % 4)
}
| .pos[.r*2+1] = $sym.b
| .t = .q
| .q |= ((./4)|floor)
| .r = (.t % 4)
| .pos[.r*2] = $sym.b
| .t = .q
| .q |= ((./6)|floor)
| .r = .t % 6
| .i = 0
| .break = false
| until( .break;
if .pos[.i] == null
then if .r == 0
then .pos[.i] = $sym.q
| .break = true
else .r += -1
end
else .
end
| .i += 1 )
| .i = 0
| reduce (krn[.q]|chars) as $f (.;
# find next insertion point
until(.pos[.i] == null; .i += 1)
| if $f | IN("k", "r", "n")
then .pos[.i] = $sym[$f]
else .
end )
| .pos
| join(" ") ;
def display960($sym):
"\(lpad(3)) \(chess960($sym))";
" ID Start position",
( 0, 518, 959 | display960(A) ),
"\nPseudo-random starting positions:",
(699, 889, 757, 645, 754 | display960(W))
</syntaxhighlight>
{{output}}
<pre>
ID Start position
0 B B Q N N R K R
518 R N B Q K B N R
959 R K R N N Q B B
Pseudo-random starting positions:
699 ♖ ♕ ♔ ♘ ♗ ♘ ♖ ♗
889 ♖ ♕ ♔ ♗ ♗ ♖ ♘ ♘
757 ♖ ♔ ♗ ♗ ♘ ♘ ♖ ♕
645 ♖ ♘ ♗ ♗ ♔ ♖ ♕ ♘
754 ♗ ♖ ♔ ♘ ♘ ♗ ♖ ♕
</pre>
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
# Placeholder knights
rank = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘']
Line 1,241 ⟶ 1,567:
end
@show generateposition()</
{{out}}
<pre>generateposition() = ['♘', '♗', '♗', '♖', '♕', '♔', '♘', '♖']</pre>
=={{header|Kotlin}}==
<
override fun iterator() = patterns.iterator()
Line 1,275 ⟶ 1,601:
fun main(args: Array<String>) {
Chess960.forEachIndexed { i, s -> println("$i: $s") }
}</
{{Out}}
<pre>0: BBNNQRKR
Line 1,286 ⟶ 1,612:
=={{header|Lua}}==
<
function randomInsert (t, str, left, right)
local pos
Line 1,314 ⟶ 1,640:
-- Main procedure
math.randomseed(os.time())
print(table.concat(chess960()))</
{{out}}
<pre>NNRQBBKR</pre>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Chess960 {
function OneFrom960$ {
def q$="♕", h$="♘", t$="♖", b$="♗", k$="♔"
def integer b1, b2, t1, t2, k, q
buffer p as integer *8
return p, 0:=string$(h$, 8)
k=random(1, 6)
t1=random(0,k-1)
t2=random(k+1, 7)
used=list:=k, t1, t2
do : b1=random(0,7): until not exist(used, b1)
append used, b1
n=b1 mod 2
do : b2=random(0,7): until not exist(used, b2) and b2 mod 2 <> n
append used, b2
do : q=random(0,7): until not exist(used, q)
// place pawns to positions
return p, k:=k$, t1:=t$, t2:=t$, b1:=b$, b2:=b$, q:=q$
=Eval$(p)+{
} // append new line to every solution
}
document doc$
For i=0 to 7:doc$+=OneFrom960$(): next
clipboard doc$
report doc$
}
Chess960
</syntaxhighlight>
{{out}}
<pre>
♘♗♗♘♖♕♔♖
♗♕♖♘♘♔♖♗
♗♗♕♖♔♘♖♘
♘♖♕♗♗♔♖♘
♖♔♘♗♖♕♗♘
♖♔♖♗♘♘♗♕
♘♘♗♕♖♗♔♖
♖♔♕♘♘♗♗♖
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
{{Output?}}
Generates all possible initial conditions, filters for validity, and chooses a random element.
<
RandomChoice[
Select[Union[
Line 1,329 ⟶ 1,698:
MatchQ[#, {___, "\[WhiteRook]", ___, "\[WhiteKing]", ___,
"\[WhiteRook]", ___}] &&
OddQ[Subtract @@ Flatten[Position[#, "\[WhiteBishop]"]]] &]]]];</
=={{header|MiniScript}}==
This version uses the Unicode piece characters. If running in [[Mini Micro]] — which supports Unicode but does not have these characters in its font — just replace the the piece characters with letters.
<
rank = ["♘"] * 8
Line 1,365 ⟶ 1,734:
rank[randFree(0, 7)] = "♕"
print join(rank, " ")</
{{out}}
<pre>♘ ♖ ♕ ♔ ♖ ♘ ♗ ♗</pre>
=={{header|Nim}}==
<
type
Line 1,438 ⟶ 1,807:
for piece in Pieces:
row[pos[piece]] = $piece
echo row.join(" ")</
{{out}}
Line 1,454 ⟶ 1,823:
=={{header|Objeck}}==
{{trans|C++}}
<
function : Main(args : String[]) ~ Nil {
Generate(10);
Line 1,523 ⟶ 1,892:
return (Float->Random() * 1000)->As(Int) % 8;
}
}</
Output:
Line 1,538 ⟶ 1,907:
=={{header|PARI/GP}}==
<
{
my (C = vector(8), i, j, r);
Line 1,546 ⟶ 1,915:
for (i = 1, 8, if (!C[i], C[i] = Vec("RKR")[j++]));
C
}</
Output:<pre>gp > for(i=1, 10, print(chess960()));
Line 1,576 ⟶ 1,945:
=={{header|Perl}}==
Directly generates a configuration by inserting pieces at random appropriate places. Each config has an equal chance of being produced.
<
sub empties { grep !$_[0][$_], 0 .. 7 }
Line 1,592 ⟶ 1,961:
@s
}
print "@{[chess960]}\n" for 0 .. 10;</
{{out}}
<pre>R N B K R N Q B
Line 1,611 ⟶ 1,980:
For something faster, and truer to the task description, just use the commented out permute(rand(factorial(8) line,
and quit as soon as you find a valid one (but I wanted to check that I had found exactly 960).
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">solutions</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 1,638 ⟶ 2,007:
<span style="color: #0000FF;">?</span><span style="color: #000000;">solutions</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">solutions</span><span style="color: #0000FF;">))]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>Found 960 solutions
Line 1,649 ⟶ 2,018:
=={{header|PicoLisp}}==
{{Output?}}
<
(seed (in "/dev/urandom" (rd 8)))
Line 1,664 ⟶ 2,033:
(prinl) )
(bye)</
=={{header|PowerShell}}==
{{works with|powershell|2}}
<
{
$Starts = @()
Line 1,697 ⟶ 2,066:
Get-RandomChess960Start
Get-RandomChess960Start
</syntaxhighlight>
{{out}}
<pre>♘♕♖♔♖♘♗♗
Line 1,703 ⟶ 2,072:
♖♗♔♕♗♖♘♘
♘♖♔♖♕♗♗♘</pre>
=={{header|Prolog}}==
Uses <code lang="prolog">random_permutation/2</code> defined in SWI-Prolog.
<syntaxhighlight lang="prolog">
check(Row) :-
nth1(King, Row, ♔),
nth1(Rook1, Row, ♖),
nth1(Rook2, Row, ♖),
nth1(Bishop1, Row, ♗),
nth1(Bishop2, Row, ♗),
Rook1 < King, King < Rook2,
(Bishop1 + Bishop2) mod 2 =:= 1.
generate(Row) :-
random_permutation([♖,♘,♗,♕,♔,♗,♘,♖], Row),
check(Row) ; generate(Row).
</syntaxhighlight>
Example run:
<syntaxhighlight lang="prolog">
?- generate(X).
X = [♘, ♗, ♖, ♕, ♘, ♔, ♗, ♖] ;
X = [♘, ♗, ♖, ♕, ♘, ♔, ♗, ♖] ;
X = [♘, ♖, ♘, ♕, ♔, ♖, ♗, ♗] ;
X = [♘, ♖, ♘, ♕, ♔, ♖, ♗, ♗]
</syntaxhighlight>
=={{header|Python}}==
Line 1,708 ⟶ 2,104:
This uses indexing rather than regexps. Rooks and bishops are in upper and lower case to start with so they can be individually indexed to apply the constraints. This would lead to some duplication of start positions if not for the use of a set comprehension to uniquify the, (upper-cased), start positions.
<
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
Line 1,718 ⟶ 2,114:
>>> starts.pop()
'QNBRNKRB'
>>></
===Python: Regexp===
This uses regexps to filter permutations of the start position pieces rather than indexing.
<
>>> pieces = 'KQRRBBNN'
>>> bish = re.compile(r'B(|..|....|......)B').search
Line 1,732 ⟶ 2,128:
>>> starts3.pop()
'QRNKBNRB'
>>></
===Python: Correct by construction===
Follows Perl algorithm of constructing one start position randomly, according to the rules.
(See talk page for tests).
<
def random960():
Line 1,751 ⟶ 2,147:
return ''.join(start).upper()
print(random960())</
{{out}}
<pre>['N', 'R', 'K', 'N', 'B', 'Q', 'R', 'B']</pre>
===Python: Generate all positions then choose one randomly===
<
def generate960():
Line 1,786 ⟶ 2,182:
gen = generate960()
print(''.join(choice(gen)))</
{{out}}
<pre>NRBQNKRB</pre>
=={{header|R}}==
<
pieces <- c("R","B","N","Q","K","N","B","R")
Line 1,817 ⟶ 2,213:
cat(convert_to_unicode(generateFirstRank()), "\n")
</syntaxhighlight>
{{out}}
<pre>
Line 1,827 ⟶ 2,223:
Constructive:
<
(define white (match-lambda ['P #\♙] ['R #\♖] ['B #\♗] ['N #\♘] ['Q #\♕] ['K #\♔]))
(define black (match-lambda ['P #\♟] ['R #\♜] ['B #\♝] ['N #\♞] ['Q #\♛] ['K #\♚]))
Line 1,858 ⟶ 2,254:
(list->string (vector->list v)))
(chess960-start-position)</
{{out}}
<pre>"♖♘♗♕♔♗♘♖"</pre>
Line 1,869 ⟶ 2,265:
(formerly Perl 6)
First, using a list with three rooks and no king, we keep generating a random piece order until the two bishops are on opposite colors. Then we sneakily promote the second of the three rooks to a king.
<syntaxhighlight lang="raku"
s:2nd['♖'] = '♔';
say .comb;</
{{out}}
<big><big><big><big><pre>♕ ♗ ♖ ♘ ♔ ♖ ♗ ♘</pre></big></big></big></big>
Here's a more "functional" solution that avoids side effects
<syntaxhighlight lang="raku"
.subst(:nth(2), /'♜'/, '♚') given
first rx/ '♝' [..]* '♝' /,
Line 1,881 ⟶ 2,277:
}
say chess960;</
{{out}}
<big><big><big><big><pre>♛♝♜♚♝♞♞♜</pre></big></big></big></big>
Line 1,889 ⟶ 2,285:
but written in the form of a list comprehension rather than nested map and grep. (The list comprehension is actually faster currently.) Note that the constant is calculated at compile time, because, well, it's a constant. Just a big fancy one.
<syntaxhighlight lang="raku"
< ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.permutations».join.unique.grep( / '♝' [..]* '♝' / )».subst(:nth(2), /'♜'/, '♚');
.say for chess960;</
Here's a much faster way (about 30x) to generate all 960 variants by construction. No need to filter for uniqueness, since it produces exactly 960 entries.
<syntaxhighlight lang="raku"
(my @q = <♜ ♚ ♜>).splice($q, 0, '♛');
for 0 .. @q -> $n1 {
Line 1,913 ⟶ 2,309:
CHECK { note "done compiling" }
note +chess960;
say chess960.pick;</
{{out}}
<pre>done compiling
Line 1,924 ⟶ 2,320:
There is a [https://en.wikipedia.org/wiki/Fischer_random_chess_numbering_scheme standard numbering scheme] for Chess960 positions, assigning each an index in the range 0..959. This function will generate the corresponding position from a given index number (or fall back to a random one if no index is specified, making it yet another solution to the general problem).
<syntaxhighlight lang="raku"
sub chess960(Pos960 $position = (^960).pick) {
Line 1,980 ⟶ 2,376:
# demo code
say chess960(518); #standard optning position
say chess960; # (it happened to pick #300)</
{{Out}}
Line 1,989 ⟶ 2,385:
Random starting position is correct by construction (both REXX entries).
===generates one random position===
<
parse arg seed . /*allow for (RANDOM BIF) repeatability.*/
if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/
Line 2,014 ⟶ 2,410:
_= /*only the queen is left to be placed. */
do i=1 for 8; _=_ || @.i; end /*construct the output: first rank only*/
say translate(translate(_, 'q', .)) /*stick a fork in it, we're all done. */</
'''output'''
<pre>NRQKBRNB</pre>
===generates all 960 positions randomly===
<
parse arg seed . /*allow for (RANDOM BIF) repeatability.*/
if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/
Line 2,056 ⟶ 2,452:
say # 'unique starting positions found after ' t "generations."
/*stick a fork in it, we're all done. */ /**/</
'''output'''
<pre> 1000 random generations: 515 unique starting positions.
Line 2,074 ⟶ 2,470:
960 unique starting positions found after 14639 generations.</pre>
===version 3 COMPUTE all possibilities===
<
* Compute the 960 possible solutions
* There must be at least one field between the rooks
Line 2,134 ⟶ 2,530:
If cnt.1=4 Then
Say ' ...'
Return</
{{out}}
<pre> 1 45678 1 2 3 RKRQBBNN
Line 2,144 ⟶ 2,540:
960 12345 6 7 8 NNBBQRKR
960 solutions</pre>
=={{header|RPL}}==
We use here the single die method, starting with a list of rooks that are gradually replaced by other pieces.
{{works with|HP|48G}}
≪ SWAP 1 ≪ 'R' SAME ≫ DOLIST 0 SWAP
1 OVER SIZE '''FOR''' j
DUP j GET ROT + SWAP
j 3 PICK PUT
'''NEXT'''
SWAP DROP SWAP POS
≫ '<span style="color:blue">ROOKPOS</span>' STO
≪ { } 1 8 '''START''' 'R' + '''NEXT'''
RAND 4 * FLOOR 2 * 1 + 'B' PUT
RAND 4 * CEIL 2 * 'B' PUT
DUP RAND 6 * CEIL <span style="color:blue">ROOKPOS</span> 'Q' PUT
DUP RAND 5 * CEIL <span style="color:blue">ROOKPOS</span> 'N' PUT
DUP RAND 4 * CEIL <span style="color:blue">ROOKPOS</span> 'N' PUT
DUP 2 <span style="color:blue">ROOKPOS</span> 'K' PUT
≫ '<span style="color:blue">→CH360</span>' STO
{{out}}
<pre>
3: { N Q R K B B R N }
2: { R K B B R Q N N }
1: { Q N R B K N B R }
</pre>
=={{header|Ruby}}==
===Ruby: shuffle pieces until all regexes match===
Translation of Tcl.
<
regexes = [/♗(..)*♗/, /♖.*♔.*♖/]
row = pieces.shuffle.join until regexes.all?{|re| re.match(row)}
puts row</
{{output}}
<big><big><big><big><pre>♕♖♗♘♔♖♘♗</pre></big></big></big></big>
Line 2,157 ⟶ 2,579:
===Ruby: Construct===
Uses the Perl idea of starting with [R,K,R] and inserting the rest:
<
[:♕, :♘, :♘].each{|piece| row.insert(rand(row.size+1), piece)}
[[0, 2, 4, 6].sample, [1, 3, 5, 7].sample].sort.each{|pos| row.insert(pos, :♗)}
puts row</
{{output}}
<big><big><big><big><pre>♗♘♕♘♖♗♔♖</pre></big></big></big></big>
Line 2,167 ⟶ 2,589:
===Ruby: Generate from SP-ID===
'''[[wp:Chess960 numbering scheme|Chess960 numbering scheme]]'''
<
def chess960(id=rand(960))
Line 2,188 ⟶ 2,610:
puts "\nGenerate random Start Position"
5.times {puts chess960}</
{{out}}
<pre>Generate Start Position from id number
Line 2,205 ⟶ 2,627:
{{Output?}}
{{trans|Kotlin}}
<
struct Chess960 ( BTreeSet<String> );
Line 2,239 ⟶ 2,661:
println!("{}: {}", i, p);
}
}</
===Rust 1.57 nightly===
<syntaxhighlight lang="rust">
// Chess960: regex and unicode version, create 5 valid random positions.
Line 2,284 ⟶ 2,706:
println!("{:?}", create_rnd_candidate());
}
}</
{{out}}
<pre>["♕", "♘", "♗", "♗", "♖", "♘", "♔", "♖"]
Line 2,294 ⟶ 2,716:
=={{header|Scala}}==
===Functional Programming, tail recursive, Unicode, RegEx===
<
object Chess960 extends App {
Line 2,318 ⟶ 2,740:
if (n <= 0) () else loop(n - 1)
}
}</
{{Out}}See it running in your browser by [https://scalafiddle.io/sf/AkvVAlG/0 ScalaFiddle (JavaScript, non JVM)] or by [https://scastie.scala-lang.org/qpKdhOc4SkuAbze8kgU6zQ Scastie (JVM)].
===Imperative Programming===
{{trans|Kotlin}}
<
private def apply(b: String, e: String) {
if (e.length <= 1) {
Line 2,342 ⟶ 2,764:
apply("", "KQRRNNBB")
for ((s, i) <- patterns.zipWithIndex) println(s"$i: $s")
}</
=={{header|Scheme}}==
{{libheader|Scheme/SRFIs}}
<
(srfi 1) ; list library
(srfi 27)) ; random numbers
Line 2,403 ⟶ 2,825:
(display "First rank: ") (display (random-piece-positions)) (newline)
</syntaxhighlight>
{{out}}
Ten sample runs:
Line 2,418 ⟶ 2,840:
=={{header|Seed7}}==
<
const proc: main is func
Line 2,435 ⟶ 2,857:
start := start[.. pred(pos)] & "B" & start[pos ..];
writeln(start);
end func;</
{{out}}
<pre>NQBNRBKR</pre>
=={{header|Sidef}}==
<
var king = backrank.index('♚')
var (rook1, rook2) = backrank.indices_of('♜')...
Line 2,454 ⟶ 2,876:
}
say random_960_position().join(' ')</
{{out}}
<pre>
Line 2,462 ⟶ 2,884:
=={{header|Swift}}==
<
var rooksPlaced = 0
var bishopColor = -1
Line 2,552 ⟶ 2,974:
}
print(positions.count, positions.randomElement()!)</
{{out}}
Line 2,561 ⟶ 2,983:
Using regular expressions to filter a random permutation.
{{tcllib|struct::list}}
<
proc chess960 {} {
Line 2,578 ⟶ 3,000:
# Output multiple times just to show scope of positions
foreach - {1 2 3 4 5} {puts [chessRender [chess960]]}</
{{out}}
<pre>♕♖♘♔♗♗♘♖
Line 2,585 ⟶ 3,007:
♘♕♗♖♔♖♘♗
♘♘♖♔♗♗♕♖</pre>
=={{header|UNIX Shell}}==
{{trans|raku}}
{{works with|bash}}
<syntaxhighlight lang=bash>declare -a pieces=(♖ ♖ ♖ ♕ ♗ ♗ ♘ ♘)
declare -i i pick index
declare -ai picking_history
declare attempt
until [[ "$attempt" =~ ♗(..)*♗ ]]
do
attempt=''
picking_history=()
for _ in {1..8}
do
while ((picking_history[pick=RANDOM%8]++))
do :
done
attempt+="${pieces[pick]}"
done
done
for i in {0..7}
do
if [[ "${attempt:i:1}" = ♖ ]] && ((index++))
then echo "${attempt:0:i}♔${attempt:i+1}"; break;
fi
done</syntaxhighlight>
=={{header|Wren}}==
Line 2,590 ⟶ 3,039:
{{libheader|Wren-dynamic}}
{{libheader|Wren-fmt}}
<
import "./dynamic" for Tuple
import "./fmt" for Fmt
var Symbols = Tuple.create("Symbols", ["k", "q", "r", "b", "n"])
Line 2,646 ⟶ 3,095:
System.print("\nRandom")
var rand = Random.new()
for (i in 0..4) System.print(chess960.call(W, rand.int(960)))</
{{out}}
Line 2,661 ⟶ 3,110:
♖ ♔ ♗ ♕ ♘ ♗ ♘ ♖
♖ ♔ ♘ ♗ ♕ ♘ ♗ ♖
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">char Col;
func ColNum(Start, Piece); \Return column number of Piece
int Start, Piece, I;
[for I:= Start to 7 do
if Col(I) = Piece then return I;
return -1;
];
proc Shuffle; \Randomly rearrange pieces in columns
int I, J, T;
[for I:= 8-1 downto 1 do
[J:= Ran(I); \range [0..I-1] (Sattolo cycle)
T:= Col(I); Col(I):= Col(J); Col(J):= T;
];
];
int N, B1, B2, BOK, R1, R2, K, KOK;
[for N:= 1 to 5 do
[Col:= "RNBQKBNR ";
repeat Shuffle;
B1:= ColNum(0, ^B);
B2:= ColNum(B1+1, ^B);
BOK:= ((B1 xor B2) and 1) # 0;
R1:= ColNum(0, ^R);
R2:= ColNum(R1+1, ^R);
K:= ColNum(0, ^K);
KOK:= R1<K and K<R2;
until BOK and KOK;
Text(0, Col); CrLf(0);
];
]</syntaxhighlight>
{{out}}
<pre>
BNRBQKRN
RBKNNQBR
BQRBNKNR
NRBBQKNR
RNKNBQRB
</pre>
=={{header|zkl}}==
{{trans|D}}
<
starts:=pieces:Utils.Helpers.permuteW(_).filter(fcn(p){
I:=p.index;
Line 2,672 ⟶ 3,164:
((I("r") < I("K") and I("K") < I("R")) or
(I("R") < I("K") and I("K") < I("r")))
}).pump(List,"concat","toUpper"):Utils.Helpers.listUnique(_);</
<
glyphs:=Dictionary("K","\u2654", "Q","\u2655", "R","\u2656", "B","\u2657", "N","\u2658");
// pick some random starts and transform BBNRKQRN to glyphs
do(10){ starts[(0).random(N)].apply(glyphs.find).println() }</
{{out}}
<pre>960
|