Generate Chess960 starting position: Difference between revisions
Content added Content deleted
(→{{header|APL}}: Add implementation.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 19: | Line 19: | ||
{{trans|Python: Correct by construction}} |
{{trans|Python: Correct by construction}} |
||
< |
<syntaxhighlight lang="11l">F random960() |
||
V start = [‘R’, ‘K’, ‘R’] |
V start = [‘R’, ‘K’, ‘R’] |
||
Line 30: | Line 30: | ||
R start |
R start |
||
print(random960())</ |
print(random960())</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 38: | Line 38: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">DEFINE MAX_NUMBERS="200" |
||
DEFINE MAX_LEN="20" |
DEFINE MAX_LEN="20" |
||
DEFINE MAX_FACTORS="5" |
DEFINE MAX_FACTORS="5" |
||
Line 130: | Line 130: | ||
PutE() |
PutE() |
||
PrintResult(max,n,factors,texts) |
PrintResult(max,n,factors,texts) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Generate_Chess960_starting_position_.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Generate_Chess960_starting_position_.png Screenshot from Atari 8-bit computer] |
||
Line 151: | Line 151: | ||
{{works with|GNU APL}} |
{{works with|GNU APL}} |
||
< |
<syntaxhighlight lang="apl">⍝ Utility functions |
||
divmod ← {(⌊⍺÷⍵),⍵|⍺} |
divmod ← {(⌊⍺÷⍵),⍵|⍺} |
||
indices ← {(⍺∊⍵)/⍳⍴⍺} |
indices ← {(⍺∊⍵)/⍳⍴⍺} |
||
Line 176: | Line 176: | ||
array ← place array 'R' 1 |
array ← place array 'R' 1 |
||
result ← spid, array |
result ← spid, array |
||
∇</ |
∇</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 188: | Line 188: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
{{works with|AutoHotkey 1.1}} |
{{works with|AutoHotkey 1.1}} |
||
< |
<syntaxhighlight lang="autohotkey">Loop, 5 |
||
Out .= Chess960() "`n" |
Out .= Chess960() "`n" |
||
MsgBox, % RTrim(Out, "`n") |
MsgBox, % RTrim(Out, "`n") |
||
Line 220: | Line 220: | ||
Random, n, Min, Max |
Random, n, Min, Max |
||
return n |
return n |
||
}</ |
}</syntaxhighlight> |
||
{{Output}} |
{{Output}} |
||
<big><big><pre>♕♘♖♗♗♘♔♖ |
<big><big><pre>♕♘♖♗♗♘♔♖ |
||
Line 231: | Line 231: | ||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
{{trans|Yabasic}} |
{{trans|Yabasic}} |
||
< |
<syntaxhighlight lang="basic256">for i = 1 to 10 |
||
inicio$ = "RKR" |
inicio$ = "RKR" |
||
pieza$ = "QNN" |
pieza$ = "QNN" |
||
Line 245: | Line 245: | ||
print inicio$ |
print inicio$ |
||
next i |
next i |
||
end</ |
end</syntaxhighlight> |
||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
{{works with|Commodore BASIC|3.5,7.0}} |
{{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. |
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. |
||
< |
<syntaxhighlight lang="basic">100 REM CHESS 960 |
||
110 PRINT "SPID (-1 FOR RANDOM):"; |
110 PRINT "SPID (-1 FOR RANDOM):"; |
||
120 OPEN 1,0:INPUT#1, SP$:CLOSE 1 |
120 OPEN 1,0:INPUT#1, SP$:CLOSE 1 |
||
Line 290: | Line 290: | ||
510 NEXT I |
510 NEXT I |
||
520 RETURN |
520 RETURN |
||
</syntaxhighlight> |
|||
</lang> |
|||
Here's a version that doesn't use the advanced features: |
Here's a version that doesn't use the advanced features: |
||
{{works with|Commodore BASIC|2.0}} |
{{works with|Commodore BASIC|2.0}} |
||
< |
<syntaxhighlight lang="basic">100 REM CHESS 960 |
||
110 PRINT "SPID (-1 FOR RANDOM):"; |
110 PRINT "SPID (-1 FOR RANDOM):"; |
||
120 OPEN 1,0:INPUT#1, SP$:CLOSE 1 |
120 OPEN 1,0:INPUT#1, SP$:CLOSE 1 |
||
Line 334: | Line 334: | ||
480 : N=N-1 |
480 : N=N-1 |
||
510 NEXT I |
510 NEXT I |
||
520 RETURN</ |
520 RETURN</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 353: | Line 353: | ||
==={{header|FreeBASIC}}=== |
==={{header|FreeBASIC}}=== |
||
{{trans|Yabasic}} |
{{trans|Yabasic}} |
||
< |
<syntaxhighlight lang="freebasic"> |
||
Randomize Timer |
Randomize Timer |
||
For i As Byte = 1 To 10 |
For i As Byte = 1 To 10 |
||
Line 371: | Line 371: | ||
Print inicio |
Print inicio |
||
Next i |
Next i |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|QBasic}}=== |
==={{header|QBasic}}=== |
||
{{trans|Yabasic}} |
{{trans|Yabasic}} |
||
< |
<syntaxhighlight lang="qbasic">RANDOMIZE TIMER |
||
FOR i = 1 TO 10 |
FOR i = 1 TO 10 |
||
Line 392: | Line 392: | ||
PRINT inicio$ |
PRINT inicio$ |
||
NEXT i |
NEXT i |
||
END</ |
END</syntaxhighlight> |
||
==={{header|Yabasic}}=== |
==={{header|Yabasic}}=== |
||
{{trans|Seed7}} |
{{trans|Seed7}} |
||
< |
<syntaxhighlight lang="yabasic">start$ = "RKR" |
||
piece$ = "QNN" |
piece$ = "QNN" |
||
Line 408: | Line 408: | ||
start$ = left$(start$, pos-1) + "B" + right$(start$, len(start$) - pos + 1) |
start$ = left$(start$, pos-1) + "B" + right$(start$, len(start$) - pos + 1) |
||
print start$ |
print start$ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Befunge}}== |
=={{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]]. |
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]]. |
||
< |
<syntaxhighlight lang="befunge">#.#.#.#.065*0#v_1-\>>?1v |
||
v,":".:%*8"x"$<^!:\*2<+< |
v,":".:%*8"x"$<^!:\*2<+< |
||
>48*,:4%2*1#v+#02#\3#g<< |
>48*,:4%2*1#v+#02#\3#g<< |
||
Line 422: | Line 422: | ||
>"RKRNN"11g:!#v_\$\$\$\v |
>"RKRNN"11g:!#v_\$\$\$\v |
||
v _v#!`*86:g0:<^!:-1$\$< |
v _v#!`*86:g0:<^!:-1$\$< |
||
>$\>,1+ :7`#@_^> v960v <</ |
>$\>,1+ :7`#@_^> v960v <</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>856 : RBKNBRNQ</pre> |
<pre>856 : RBKNBRNQ</pre> |
||
Line 428: | Line 428: | ||
=={{header|C}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="c">#include<stdlib.h> |
||
#include<locale.h> |
#include<locale.h> |
||
#include<wchar.h> |
#include<wchar.h> |
||
Line 530: | Line 530: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output on Linux : |
Output on Linux : |
||
<pre>♗♗♖♕♘♘♔♖ |
<pre>♗♗♖♕♘♘♔♖ |
||
Line 553: | Line 553: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <string> |
#include <string> |
||
#include <time.h> |
#include <time.h> |
||
Line 610: | Line 610: | ||
return system( "pause" ); |
return system( "pause" ); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>NQBRNBKR |
<pre>NQBRNBKR |
||
Line 624: | Line 624: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(ns c960.core |
||
(:gen-class) |
(:gen-class) |
||
(:require [clojure.string :as s])) |
(:require [clojure.string :as s])) |
||
Line 661: | Line 661: | ||
;; => "♖, ♕, ♘, ♔, ♗, ♗, ♘, ♖" |
;; => "♖, ♕, ♘, ♔, ♗, ♗, ♘, ♖" |
||
(c960 4) |
(c960 4) |
||
;; => ("♘, ♖, ♔, ♘, ♗, ♗, ♖, ♕" "♗, ♖, ♔, ♘, ♘, ♕, ♖, ♗" "♘, ♕, ♗, ♖, ♔, ♗, ♘, ♖" "♖, ♔, ♘, ♘, ♕, ♖, ♗, ♗")</ |
;; => ("♘, ♖, ♔, ♘, ♗, ♗, ♖, ♕" "♗, ♖, ♔, ♘, ♘, ♕, ♖, ♗" "♘, ♕, ♗, ♖, ♔, ♗, ♘, ♖" "♖, ♔, ♘, ♘, ♕, ♖, ♗, ♗")</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 667: | Line 667: | ||
===Common Lisp: generate from SP-ID=== |
===Common Lisp: generate from SP-ID=== |
||
{{trans|Raku}} |
{{trans|Raku}} |
||
< |
<syntaxhighlight lang="lisp">(defun chess960-from-sp-id |
||
(&optional (sp-id (random 360 (make-random-state t)))) |
(&optional (sp-id (random 360 (make-random-state t)))) |
||
(labels |
(labels |
||
Line 719: | Line 719: | ||
(format t "~a~%" (chess960-from-sp-id 518)) |
(format t "~a~%" (chess960-from-sp-id 518)) |
||
(format t "~a~%" (chess960-from-sp-id))</ |
(format t "~a~%" (chess960-from-sp-id))</syntaxhighlight> |
||
{{Out}}<pre>(518 #(♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜)) |
{{Out}}<pre>(518 #(♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜)) |
||
Line 728: | Line 728: | ||
===D: Indexing=== |
===D: Indexing=== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.range, std.algorithm, std.string, permutations2; |
import std.stdio, std.range, std.algorithm, std.string, permutations2; |
||
Line 740: | Line 740: | ||
.map!toUpper.array.sort().uniq; |
.map!toUpper.array.sort().uniq; |
||
writeln(starts.walkLength, "\n", starts.front); |
writeln(starts.walkLength, "\n", starts.front); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>960 |
<pre>960 |
||
Line 746: | Line 746: | ||
===D: Regexp=== |
===D: Regexp=== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.regex, std.range, std.algorithm, permutations2; |
import std.stdio, std.regex, std.range, std.algorithm, permutations2; |
||
Line 756: | Line 756: | ||
.array.sort().uniq; |
.array.sort().uniq; |
||
writeln(starts3.walkLength, "\n", starts3.front); |
writeln(starts3.walkLength, "\n", starts3.front); |
||
}</ |
}</syntaxhighlight> |
||
The output is the same. |
The output is the same. |
||
===D: Correct by construction=== |
===D: Correct by construction=== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.random, std.array, std.range; |
import std.stdio, std.random, std.array, std.range; |
||
Line 772: | Line 772: | ||
start.insertInPlace(iota(bishpos % 2, start.length, 2)[uniform(0,$)], 'B'); |
start.insertInPlace(iota(bishpos % 2, start.length, 2)[uniform(0,$)], 'B'); |
||
start.writeln; |
start.writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>QBNNBRKR</pre> |
<pre>QBNNBRKR</pre> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp">(define-values (K Q R B N) (iota 5)) |
||
(define *pos* (list R N B Q K B N R)) ;; standard starter |
(define *pos* (list R N B Q K B N R)) ;; standard starter |
||
Line 792: | Line 792: | ||
(if (legal-pos *pos*) |
(if (legal-pos *pos*) |
||
(map unicode-piece *pos*) (c960))) |
(map unicode-piece *pos*) (c960))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>(define (unicode-piece i) (unicode->string (+ 0x2654 i))) |
<pre>(define (unicode-piece i) (unicode->string (+ 0x2654 i))) |
||
Line 809: | Line 809: | ||
{{works with|Elixir|1.1}} |
{{works with|Elixir|1.1}} |
||
===Elixir: shuffle pieces until all regexes match=== |
===Elixir: shuffle pieces until all regexes match=== |
||
< |
<syntaxhighlight lang="elixir">defmodule Chess960 do |
||
@pieces ~w(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖) # ~w(K Q N N B B R R) |
@pieces ~w(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖) # ~w(K Q N N B B R R) |
||
@regexes [~r/♗(..)*♗/, ~r/♖.*♔.*♖/] # [~r/B(..)*B/, ~r/R.*K.*R/] |
@regexes [~r/♗(..)*♗/, ~r/♖.*♔.*♖/] # [~r/B(..)*B/, ~r/R.*K.*R/] |
||
Line 819: | Line 819: | ||
end |
end |
||
Enum.each(1..5, fn _ -> IO.puts Chess960.shuffle end)</ |
Enum.each(1..5, fn _ -> IO.puts Chess960.shuffle end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>♘♗♘♖♗♔♕♖ |
<pre>♘♗♘♖♗♔♕♖ |
||
Line 828: | Line 828: | ||
===Elixir: Construct=== |
===Elixir: Construct=== |
||
< |
<syntaxhighlight lang="elixir">defmodule Chess960 do |
||
def construct do |
def construct do |
||
row = Enum.reduce(~w[♕ ♘ ♘], ~w[♖ ♔ ♖], fn piece,acc -> |
row = Enum.reduce(~w[♕ ♘ ♘], ~w[♖ ♔ ♖], fn piece,acc -> |
||
Line 840: | Line 840: | ||
end |
end |
||
Enum.each(1..5, fn _ -> IO.puts Chess960.construct end)</ |
Enum.each(1..5, fn _ -> IO.puts Chess960.construct end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>♖♔♗♘♖♕♘♗ |
<pre>♖♔♗♘♖♕♘♗ |
||
Line 849: | Line 849: | ||
===Elixir: Generate from SP-ID=== |
===Elixir: Generate from SP-ID=== |
||
< |
<syntaxhighlight lang="elixir">defmodule Chess960 do |
||
@krn ~w(NNRKR NRNKR NRKNR NRKRN RNNKR RNKNR RNKRN RKNNR RKNRN RKRNN) |
@krn ~w(NNRKR NRNKR NRKNR NRKRN RNNKR RNKNR RNKRN RKNNR RKNRN RKRNN) |
||
Line 879: | Line 879: | ||
end) |
end) |
||
IO.puts "\nGenerate random Start Position" |
IO.puts "\nGenerate random Start Position" |
||
Enum.each(1..5, fn _ -> IO.puts Chess960.start_position end)</ |
Enum.each(1..5, fn _ -> IO.puts Chess960.start_position end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Generate Start Position from ID number |
<pre>Generate Start Position from ID number |
||
Line 896: | Line 896: | ||
===Single die method=== |
===Single die method=== |
||
Using the single die method: https://en.wikipedia.org/wiki/Chess960_starting_position#Single_die_method |
Using the single die method: https://en.wikipedia.org/wiki/Chess960_starting_position#Single_die_method |
||
< |
<syntaxhighlight lang="factor">USING: io kernel math random sequences ; |
||
IN: rosetta-code.chess960 |
IN: rosetta-code.chess960 |
||
Line 923: | Line 923: | ||
: chess960-demo ( -- ) 5 [ chess960 print ] times ; |
: chess960-demo ( -- ) 5 [ chess960 print ] times ; |
||
MAIN: chess960-demo</ |
MAIN: chess960-demo</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 935: | Line 935: | ||
===Built-in=== |
===Built-in=== |
||
Factor comes with a chess960 position generator: |
Factor comes with a chess960 position generator: |
||
< |
<syntaxhighlight lang="factor">USING: chess960 prettyprint ; |
||
chess960-position .</ |
chess960-position .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 945: | Line 945: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">\ make starting position for Chess960, constructive |
||
\ 0 1 2 3 4 5 6 7 8 9 |
\ 0 1 2 3 4 5 6 7 8 9 |
||
Line 964: | Line 964: | ||
959 chess960 \ RKRNNQBB ok |
959 chess960 \ RKRNNQBB ok |
||
960 choose chess960 \ random position</ |
960 choose chess960 \ random position</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
This implementation simply iterates through all 960 positions. |
This implementation simply iterates through all 960 positions. |
||
< |
<syntaxhighlight lang="fortran">program chess960 |
||
implicit none |
implicit none |
||
Line 1,025: | Line 1,025: | ||
end program chess960 |
end program chess960 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
The first ten positions: |
The first ten positions: |
||
Line 1,041: | Line 1,041: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,103: | Line 1,103: | ||
fmt.Println(W.chess960(rand.Intn(960))) |
fmt.Println(W.chess960(rand.Intn(960))) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> ID Start position |
<pre> ID Start position |
||
Line 1,118: | Line 1,118: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Data.List |
||
import qualified Data.Set as Set |
import qualified Data.Set as Set |
||
Line 1,132: | Line 1,132: | ||
main :: IO () |
main :: IO () |
||
main = mapM_ (putStrLn . concatMap show) . Set.toList . Set.fromList |
main = mapM_ (putStrLn . concatMap show) . Set.toList . Set.fromList |
||
. filter isChess960 $ permutations [R,N,B,Q,K,B,N,R]</ |
. filter isChess960 $ permutations [R,N,B,Q,K,B,N,R]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>QRKRBBNN |
<pre>QRKRBBNN |
||
Line 1,144: | Line 1,144: | ||
Build a table of the starting positions then pick one at random. There are 40320 distinct permutations of 8 items and 5040 distinct permutations of these chess pieces and (as the task name points out) only 960 permutations which also satisfy the constraints on bishop and rook position, so little memory is needed to generate the table. Also, since the table is built at "compile time", execution is fast (though "compilation" is reasonably fast also). |
Build a table of the starting positions then pick one at random. There are 40320 distinct permutations of 8 items and 5040 distinct permutations of these chess pieces and (as the task name points out) only 960 permutations which also satisfy the constraints on bishop and rook position, so little memory is needed to generate the table. Also, since the table is built at "compile time", execution is fast (though "compilation" is reasonably fast also). |
||
< |
<syntaxhighlight lang="j">row0=: u: 9812+2}.5|i.10 |
||
king=: u:9812 |
king=: u:9812 |
||
rook=: u:9814 |
rook=: u:9814 |
||
Line 1,154: | Line 1,154: | ||
perm=: A.&i.~ ! |
perm=: A.&i.~ ! |
||
valid=: (#~ ok"1) ~.row0{"1~perm 8 |
valid=: (#~ ok"1) ~.row0{"1~perm 8 |
||
gen=: valid {~ ? bind 960</ |
gen=: valid {~ ? bind 960</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="j"> gen'' |
||
♘♗♖♔♗♕♖♘ |
♘♗♖♔♗♕♖♘ |
||
gen'' |
gen'' |
||
Line 1,165: | Line 1,165: | ||
♖♗♔♘♘♕♗♖ |
♖♗♔♘♘♕♗♖ |
||
gen'' |
gen'' |
||
♖♔♕♗♗♘♖♘</ |
♖♔♕♗♗♘♖♘</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
Regex inspired by (original) [[#Python: Regexp|Python Regexp]], prints ten examples. |
Regex inspired by (original) [[#Python: Regexp|Python Regexp]], prints ten examples. |
||
< |
<syntaxhighlight lang="java5">import java.util.Arrays; |
||
import java.util.Collections; |
import java.util.Collections; |
||
import java.util.List; |
import java.util.List; |
||
Line 1,196: | Line 1,196: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[R, N, K, N, R, B, B, Q] |
<pre>[R, N, K, N, R, B, B, Q] |
||
Line 1,211: | Line 1,211: | ||
=={{header|JavaScript}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="javascript">function ch960startPos() { |
||
var rank = new Array(8), |
var rank = new Array(8), |
||
// randomizer (our die) |
// randomizer (our die) |
||
Line 1,236: | Line 1,236: | ||
// testing (10 times) |
// testing (10 times) |
||
for (var x = 1; x <= 10; x++) console.log(ch960startPos().join(" | "));</ |
for (var x = 1; x <= 10; x++) console.log(ch960startPos().join(" | "));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<p>The test-output (exemplary each):</p> |
<p>The test-output (exemplary each):</p> |
||
Line 1,252: | Line 1,252: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
< |
<syntaxhighlight lang="julia">function generateposition() |
||
# Placeholder knights |
# Placeholder knights |
||
rank = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘'] |
rank = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘'] |
||
Line 1,281: | Line 1,281: | ||
end |
end |
||
@show generateposition()</ |
@show generateposition()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>generateposition() = ['♘', '♗', '♗', '♖', '♕', '♔', '♘', '♖']</pre> |
<pre>generateposition() = ['♘', '♗', '♗', '♖', '♕', '♔', '♘', '♖']</pre> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">object Chess960 : Iterable<String> { |
||
override fun iterator() = patterns.iterator() |
override fun iterator() = patterns.iterator() |
||
Line 1,315: | Line 1,315: | ||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Chess960.forEachIndexed { i, s -> println("$i: $s") } |
Chess960.forEachIndexed { i, s -> println("$i: $s") } |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>0: BBNNQRKR |
<pre>0: BBNNQRKR |
||
Line 1,326: | Line 1,326: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">-- Insert 'str' into 't' at a random position from 'left' to 'right' |
||
function randomInsert (t, str, left, right) |
function randomInsert (t, str, left, right) |
||
local pos |
local pos |
||
Line 1,354: | Line 1,354: | ||
-- Main procedure |
-- Main procedure |
||
math.randomseed(os.time()) |
math.randomseed(os.time()) |
||
print(table.concat(chess960()))</ |
print(table.concat(chess960()))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>NNRQBBKR</pre> |
<pre>NNRQBBKR</pre> |
||
Line 1,361: | Line 1,361: | ||
{{Output?}} |
{{Output?}} |
||
Generates all possible initial conditions, filters for validity, and chooses a random element. |
Generates all possible initial conditions, filters for validity, and chooses a random element. |
||
< |
<syntaxhighlight lang="mathematica">Print[StringJoin[ |
||
RandomChoice[ |
RandomChoice[ |
||
Select[Union[ |
Select[Union[ |
||
Line 1,369: | Line 1,369: | ||
MatchQ[#, {___, "\[WhiteRook]", ___, "\[WhiteKing]", ___, |
MatchQ[#, {___, "\[WhiteRook]", ___, "\[WhiteKing]", ___, |
||
"\[WhiteRook]", ___}] && |
"\[WhiteRook]", ___}] && |
||
OddQ[Subtract @@ Flatten[Position[#, "\[WhiteBishop]"]]] &]]]];</ |
OddQ[Subtract @@ Flatten[Position[#, "\[WhiteBishop]"]]] &]]]];</syntaxhighlight> |
||
=={{header|MiniScript}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="miniscript">// placeholder knights |
||
rank = ["♘"] * 8 |
rank = ["♘"] * 8 |
||
Line 1,405: | Line 1,405: | ||
rank[randFree(0, 7)] = "♕" |
rank[randFree(0, 7)] = "♕" |
||
print join(rank, " ")</ |
print join(rank, " ")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>♘ ♖ ♕ ♔ ♖ ♘ ♗ ♗</pre> |
<pre>♘ ♖ ♕ ♔ ♖ ♘ ♗ ♗</pre> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import random, strutils |
||
type |
type |
||
Line 1,478: | Line 1,478: | ||
for piece in Pieces: |
for piece in Pieces: |
||
row[pos[piece]] = $piece |
row[pos[piece]] = $piece |
||
echo row.join(" ")</ |
echo row.join(" ")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,494: | Line 1,494: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
{{trans|C++}} |
{{trans|C++}} |
||
< |
<syntaxhighlight lang="objeck">class Chess960 { |
||
function : Main(args : String[]) ~ Nil { |
function : Main(args : String[]) ~ Nil { |
||
Generate(10); |
Generate(10); |
||
Line 1,563: | Line 1,563: | ||
return (Float->Random() * 1000)->As(Int) % 8; |
return (Float->Random() * 1000)->As(Int) % 8; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,578: | Line 1,578: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">chess960() = |
||
{ |
{ |
||
my (C = vector(8), i, j, r); |
my (C = vector(8), i, j, r); |
||
Line 1,586: | Line 1,586: | ||
for (i = 1, 8, if (!C[i], C[i] = Vec("RKR")[j++])); |
for (i = 1, 8, if (!C[i], C[i] = Vec("RKR")[j++])); |
||
C |
C |
||
}</ |
}</syntaxhighlight> |
||
Output:<pre>gp > for(i=1, 10, print(chess960())); |
Output:<pre>gp > for(i=1, 10, print(chess960())); |
||
Line 1,616: | Line 1,616: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Directly generates a configuration by inserting pieces at random appropriate places. Each config has an equal chance of being produced. |
Directly generates a configuration by inserting pieces at random appropriate places. Each config has an equal chance of being produced. |
||
< |
<syntaxhighlight lang="perl">sub rnd($) { int(rand(shift)) } |
||
sub empties { grep !$_[0][$_], 0 .. 7 } |
sub empties { grep !$_[0][$_], 0 .. 7 } |
||
Line 1,632: | Line 1,632: | ||
@s |
@s |
||
} |
} |
||
print "@{[chess960]}\n" for 0 .. 10;</ |
print "@{[chess960]}\n" for 0 .. 10;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>R N B K R N Q B |
<pre>R N B K R N Q B |
||
Line 1,651: | Line 1,651: | ||
For something faster, and truer to the task description, just use the commented out permute(rand(factorial(8) line, |
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). |
and quit as soon as you find a valid one (but I wanted to check that I had found exactly 960). |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<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> |
<span style="color: #004080;">sequence</span> <span style="color: #000000;">solutions</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> |
||
Line 1,678: | Line 1,678: | ||
<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: #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> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre>Found 960 solutions |
<pre>Found 960 solutions |
||
Line 1,689: | Line 1,689: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
{{Output?}} |
{{Output?}} |
||
< |
<syntaxhighlight lang="picolisp">(load "@lib/simul.l") |
||
(seed (in "/dev/urandom" (rd 8))) |
(seed (in "/dev/urandom" (rd 8))) |
||
Line 1,704: | Line 1,704: | ||
(prinl) ) |
(prinl) ) |
||
(bye)</ |
(bye)</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
{{works with|powershell|2}} |
{{works with|powershell|2}} |
||
< |
<syntaxhighlight lang="powershell">function Get-RandomChess960Start |
||
{ |
{ |
||
$Starts = @() |
$Starts = @() |
||
Line 1,737: | Line 1,737: | ||
Get-RandomChess960Start |
Get-RandomChess960Start |
||
Get-RandomChess960Start |
Get-RandomChess960Start |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>♘♕♖♔♖♘♗♗ |
<pre>♘♕♖♔♖♘♗♗ |
||
Line 1,748: | Line 1,748: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="python">>>> from itertools import permutations |
||
>>> pieces = 'KQRrBbNN' |
>>> pieces = 'KQRrBbNN' |
||
>>> starts = {''.join(p).upper() for p in permutations(pieces) |
>>> starts = {''.join(p).upper() for p in permutations(pieces) |
||
Line 1,758: | Line 1,758: | ||
>>> starts.pop() |
>>> starts.pop() |
||
'QNBRNKRB' |
'QNBRNKRB' |
||
>>></ |
>>></syntaxhighlight> |
||
===Python: Regexp=== |
===Python: Regexp=== |
||
This uses regexps to filter permutations of the start position pieces rather than indexing. |
This uses regexps to filter permutations of the start position pieces rather than indexing. |
||
< |
<syntaxhighlight lang="python">>>> import re |
||
>>> pieces = 'KQRRBBNN' |
>>> pieces = 'KQRRBBNN' |
||
>>> bish = re.compile(r'B(|..|....|......)B').search |
>>> bish = re.compile(r'B(|..|....|......)B').search |
||
Line 1,772: | Line 1,772: | ||
>>> starts3.pop() |
>>> starts3.pop() |
||
'QRNKBNRB' |
'QRNKBNRB' |
||
>>></ |
>>></syntaxhighlight> |
||
===Python: Correct by construction=== |
===Python: Correct by construction=== |
||
Follows Perl algorithm of constructing one start position randomly, according to the rules. |
Follows Perl algorithm of constructing one start position randomly, according to the rules. |
||
(See talk page for tests). |
(See talk page for tests). |
||
< |
<syntaxhighlight lang="python">from random import choice |
||
def random960(): |
def random960(): |
||
Line 1,791: | Line 1,791: | ||
return ''.join(start).upper() |
return ''.join(start).upper() |
||
print(random960())</ |
print(random960())</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>['N', 'R', 'K', 'N', 'B', 'Q', 'R', 'B']</pre> |
<pre>['N', 'R', 'K', 'N', 'B', 'Q', 'R', 'B']</pre> |
||
===Python: Generate all positions then choose one randomly=== |
===Python: Generate all positions then choose one randomly=== |
||
< |
<syntaxhighlight lang="python">from random import choice |
||
def generate960(): |
def generate960(): |
||
Line 1,826: | Line 1,826: | ||
gen = generate960() |
gen = generate960() |
||
print(''.join(choice(gen)))</ |
print(''.join(choice(gen)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>NRBQNKRB</pre> |
<pre>NRBQNKRB</pre> |
||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="rsplus"> |
||
pieces <- c("R","B","N","Q","K","N","B","R") |
pieces <- c("R","B","N","Q","K","N","B","R") |
||
Line 1,857: | Line 1,857: | ||
cat(convert_to_unicode(generateFirstRank()), "\n") |
cat(convert_to_unicode(generateFirstRank()), "\n") |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,867: | Line 1,867: | ||
Constructive: |
Constructive: |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define white (match-lambda ['P #\♙] ['R #\♖] ['B #\♗] ['N #\♘] ['Q #\♕] ['K #\♔])) |
(define white (match-lambda ['P #\♙] ['R #\♖] ['B #\♗] ['N #\♘] ['Q #\♕] ['K #\♔])) |
||
(define black (match-lambda ['P #\♟] ['R #\♜] ['B #\♝] ['N #\♞] ['Q #\♛] ['K #\♚])) |
(define black (match-lambda ['P #\♟] ['R #\♜] ['B #\♝] ['N #\♞] ['Q #\♛] ['K #\♚])) |
||
Line 1,898: | Line 1,898: | ||
(list->string (vector->list v))) |
(list->string (vector->list v))) |
||
(chess960-start-position)</ |
(chess960-start-position)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>"♖♘♗♕♔♗♘♖"</pre> |
<pre>"♖♘♗♕♔♗♘♖"</pre> |
||
Line 1,909: | Line 1,909: | ||
(formerly Perl 6) |
(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. |
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. |
||
<lang |
<syntaxhighlight lang="raku" line>repeat until m/ '♗' [..]* '♗' / { $_ = < ♖ ♖ ♖ ♕ ♗ ♗ ♘ ♘ >.pick(*).join } |
||
s:2nd['♖'] = '♔'; |
s:2nd['♖'] = '♔'; |
||
say .comb;</ |
say .comb;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<big><big><big><big><pre>♕ ♗ ♖ ♘ ♔ ♖ ♗ ♘</pre></big></big></big></big> |
<big><big><big><big><pre>♕ ♗ ♖ ♘ ♔ ♖ ♗ ♘</pre></big></big></big></big> |
||
Here's a more "functional" solution that avoids side effects |
Here's a more "functional" solution that avoids side effects |
||
<lang |
<syntaxhighlight lang="raku" line>sub chess960 { |
||
.subst(:nth(2), /'♜'/, '♚') given |
.subst(:nth(2), /'♜'/, '♚') given |
||
first rx/ '♝' [..]* '♝' /, |
first rx/ '♝' [..]* '♝' /, |
||
Line 1,921: | Line 1,921: | ||
} |
} |
||
say chess960;</ |
say chess960;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<big><big><big><big><pre>♛♝♜♚♝♞♞♜</pre></big></big></big></big> |
<big><big><big><big><pre>♛♝♜♚♝♞♞♜</pre></big></big></big></big> |
||
Line 1,929: | Line 1,929: | ||
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. |
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. |
||
<lang |
<syntaxhighlight lang="raku" line>constant chess960 = |
||
< ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.permutations».join.unique.grep( / '♝' [..]* '♝' / )».subst(:nth(2), /'♜'/, '♚'); |
< ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.permutations».join.unique.grep( / '♝' [..]* '♝' / )».subst(:nth(2), /'♜'/, '♚'); |
||
.say for chess960;</ |
.say for chess960;</syntaxhighlight> |
||
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. |
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. |
||
<lang |
<syntaxhighlight lang="raku" line>constant chess960 = gather for 0..3 -> $q { |
||
(my @q = <♜ ♚ ♜>).splice($q, 0, '♛'); |
(my @q = <♜ ♚ ♜>).splice($q, 0, '♛'); |
||
for 0 .. @q -> $n1 { |
for 0 .. @q -> $n1 { |
||
Line 1,953: | Line 1,953: | ||
CHECK { note "done compiling" } |
CHECK { note "done compiling" } |
||
note +chess960; |
note +chess960; |
||
say chess960.pick;</ |
say chess960.pick;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>done compiling |
<pre>done compiling |
||
Line 1,964: | Line 1,964: | ||
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). |
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). |
||
<lang |
<syntaxhighlight lang="raku" line>subset Pos960 of Int where { $_ ~~ ^960 }; |
||
sub chess960(Pos960 $position = (^960).pick) { |
sub chess960(Pos960 $position = (^960).pick) { |
||
Line 2,020: | Line 2,020: | ||
# demo code |
# demo code |
||
say chess960(518); #standard optning position |
say chess960(518); #standard optning position |
||
say chess960; # (it happened to pick #300)</ |
say chess960; # (it happened to pick #300)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,029: | Line 2,029: | ||
Random starting position is correct by construction (both REXX entries). |
Random starting position is correct by construction (both REXX entries). |
||
===generates one random position=== |
===generates one random position=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program generates a random starting position for the Chess960 game. */ |
||
parse arg seed . /*allow for (RANDOM BIF) repeatability.*/ |
parse arg seed . /*allow for (RANDOM BIF) repeatability.*/ |
||
if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/ |
if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/ |
||
Line 2,054: | Line 2,054: | ||
_= /*only the queen is left to be placed. */ |
_= /*only the queen is left to be placed. */ |
||
do i=1 for 8; _=_ || @.i; end /*construct the output: first rank only*/ |
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. */</ |
say translate(translate(_, 'q', .)) /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' |
'''output''' |
||
<pre>NRQKBRNB</pre> |
<pre>NRQKBRNB</pre> |
||
===generates all 960 positions randomly=== |
===generates all 960 positions randomly=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program generates all random starting positions for the Chess960 game. */ |
||
parse arg seed . /*allow for (RANDOM BIF) repeatability.*/ |
parse arg seed . /*allow for (RANDOM BIF) repeatability.*/ |
||
if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/ |
if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/ |
||
Line 2,096: | Line 2,096: | ||
say # 'unique starting positions found after ' t "generations." |
say # 'unique starting positions found after ' t "generations." |
||
/*stick a fork in it, we're all done. */ /**/</ |
/*stick a fork in it, we're all done. */ /**/</syntaxhighlight> |
||
'''output''' |
'''output''' |
||
<pre> 1000 random generations: 515 unique starting positions. |
<pre> 1000 random generations: 515 unique starting positions. |
||
Line 2,114: | Line 2,114: | ||
960 unique starting positions found after 14639 generations.</pre> |
960 unique starting positions found after 14639 generations.</pre> |
||
===version 3 COMPUTE all possibilities=== |
===version 3 COMPUTE all possibilities=== |
||
< |
<syntaxhighlight lang="rexx">/*--------------------------------------------------------------- |
||
* Compute the 960 possible solutions |
* Compute the 960 possible solutions |
||
* There must be at least one field between the rooks |
* There must be at least one field between the rooks |
||
Line 2,174: | Line 2,174: | ||
If cnt.1=4 Then |
If cnt.1=4 Then |
||
Say ' ...' |
Say ' ...' |
||
Return</ |
Return</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1 45678 1 2 3 RKRQBBNN |
<pre> 1 45678 1 2 3 RKRQBBNN |
||
Line 2,188: | Line 2,188: | ||
===Ruby: shuffle pieces until all regexes match=== |
===Ruby: shuffle pieces until all regexes match=== |
||
Translation of Tcl. |
Translation of Tcl. |
||
< |
<syntaxhighlight lang="ruby">pieces = %i(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖) |
||
regexes = [/♗(..)*♗/, /♖.*♔.*♖/] |
regexes = [/♗(..)*♗/, /♖.*♔.*♖/] |
||
row = pieces.shuffle.join until regexes.all?{|re| re.match(row)} |
row = pieces.shuffle.join until regexes.all?{|re| re.match(row)} |
||
puts row</ |
puts row</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
<big><big><big><big><pre>♕♖♗♘♔♖♘♗</pre></big></big></big></big> |
<big><big><big><big><pre>♕♖♗♘♔♖♘♗</pre></big></big></big></big> |
||
Line 2,197: | Line 2,197: | ||
===Ruby: Construct=== |
===Ruby: Construct=== |
||
Uses the Perl idea of starting with [R,K,R] and inserting the rest: |
Uses the Perl idea of starting with [R,K,R] and inserting the rest: |
||
< |
<syntaxhighlight lang="ruby">row = [:♖, :♔, :♖] |
||
[:♕, :♘, :♘].each{|piece| row.insert(rand(row.size+1), piece)} |
[:♕, :♘, :♘].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, :♗)} |
[[0, 2, 4, 6].sample, [1, 3, 5, 7].sample].sort.each{|pos| row.insert(pos, :♗)} |
||
puts row</ |
puts row</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
<big><big><big><big><pre>♗♘♕♘♖♗♔♖</pre></big></big></big></big> |
<big><big><big><big><pre>♗♘♕♘♖♗♔♖</pre></big></big></big></big> |
||
Line 2,207: | Line 2,207: | ||
===Ruby: Generate from SP-ID=== |
===Ruby: Generate from SP-ID=== |
||
'''[[wp:Chess960 numbering scheme|Chess960 numbering scheme]]''' |
'''[[wp:Chess960 numbering scheme|Chess960 numbering scheme]]''' |
||
< |
<syntaxhighlight lang="ruby">KRN = %w(NNRKR NRNKR NRKNR NRKRN RNNKR RNKNR RNKRN RKNNR RKNRN RKRNN) |
||
def chess960(id=rand(960)) |
def chess960(id=rand(960)) |
||
Line 2,228: | Line 2,228: | ||
puts "\nGenerate random Start Position" |
puts "\nGenerate random Start Position" |
||
5.times {puts chess960}</ |
5.times {puts chess960}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Generate Start Position from id number |
<pre>Generate Start Position from id number |
||
Line 2,245: | Line 2,245: | ||
{{Output?}} |
{{Output?}} |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<syntaxhighlight lang="rust">use std::collections::BTreeSet; |
||
struct Chess960 ( BTreeSet<String> ); |
struct Chess960 ( BTreeSet<String> ); |
||
Line 2,279: | Line 2,279: | ||
println!("{}: {}", i, p); |
println!("{}: {}", i, p); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Rust 1.57 nightly=== |
===Rust 1.57 nightly=== |
||
<syntaxhighlight lang="rust"> |
|||
<lang Rust> |
|||
// Chess960: regex and unicode version, create 5 valid random positions. |
// Chess960: regex and unicode version, create 5 valid random positions. |
||
Line 2,324: | Line 2,324: | ||
println!("{:?}", create_rnd_candidate()); |
println!("{:?}", create_rnd_candidate()); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>["♕", "♘", "♗", "♗", "♖", "♘", "♔", "♖"] |
<pre>["♕", "♘", "♗", "♗", "♖", "♘", "♔", "♖"] |
||
Line 2,334: | Line 2,334: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
===Functional Programming, tail recursive, Unicode, RegEx=== |
===Functional Programming, tail recursive, Unicode, RegEx=== |
||
< |
<syntaxhighlight lang="scala">import scala.annotation.tailrec |
||
object Chess960 extends App { |
object Chess960 extends App { |
||
Line 2,358: | Line 2,358: | ||
if (n <= 0) () else loop(n - 1) |
if (n <= 0) () else loop(n - 1) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{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)]. |
{{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=== |
===Imperative Programming=== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<syntaxhighlight lang="scala">object Chess960 extends App { |
||
private def apply(b: String, e: String) { |
private def apply(b: String, e: String) { |
||
if (e.length <= 1) { |
if (e.length <= 1) { |
||
Line 2,382: | Line 2,382: | ||
apply("", "KQRRNNBB") |
apply("", "KQRRNNBB") |
||
for ((s, i) <- patterns.zipWithIndex) println(s"$i: $s") |
for ((s, i) <- patterns.zipWithIndex) println(s"$i: $s") |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
{{libheader|Scheme/SRFIs}} |
{{libheader|Scheme/SRFIs}} |
||
< |
<syntaxhighlight lang="scheme">(import (scheme base) (scheme write) |
||
(srfi 1) ; list library |
(srfi 1) ; list library |
||
(srfi 27)) ; random numbers |
(srfi 27)) ; random numbers |
||
Line 2,443: | Line 2,443: | ||
(display "First rank: ") (display (random-piece-positions)) (newline) |
(display "First rank: ") (display (random-piece-positions)) (newline) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Ten sample runs: |
Ten sample runs: |
||
Line 2,458: | Line 2,458: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 2,475: | Line 2,475: | ||
start := start[.. pred(pos)] & "B" & start[pos ..]; |
start := start[.. pred(pos)] & "B" & start[pos ..]; |
||
writeln(start); |
writeln(start); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>NQBNRBKR</pre> |
<pre>NQBNRBKR</pre> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func is_valid_960 (backrank) { |
||
var king = backrank.index('♚') |
var king = backrank.index('♚') |
||
var (rook1, rook2) = backrank.indices_of('♜')... |
var (rook1, rook2) = backrank.indices_of('♜')... |
||
Line 2,494: | Line 2,494: | ||
} |
} |
||
say random_960_position().join(' ')</ |
say random_960_position().join(' ')</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,502: | Line 2,502: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func isValid960Position(_ firstRank: String) -> Bool { |
||
var rooksPlaced = 0 |
var rooksPlaced = 0 |
||
var bishopColor = -1 |
var bishopColor = -1 |
||
Line 2,592: | Line 2,592: | ||
} |
} |
||
print(positions.count, positions.randomElement()!)</ |
print(positions.count, positions.randomElement()!)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,601: | Line 2,601: | ||
Using regular expressions to filter a random permutation. |
Using regular expressions to filter a random permutation. |
||
{{tcllib|struct::list}} |
{{tcllib|struct::list}} |
||
< |
<syntaxhighlight lang="tcl">package require struct::list |
||
proc chess960 {} { |
proc chess960 {} { |
||
Line 2,618: | Line 2,618: | ||
# Output multiple times just to show scope of positions |
# Output multiple times just to show scope of positions |
||
foreach - {1 2 3 4 5} {puts [chessRender [chess960]]}</ |
foreach - {1 2 3 4 5} {puts [chessRender [chess960]]}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>♕♖♘♔♗♗♘♖ |
<pre>♕♖♘♔♗♗♘♖ |
||
Line 2,630: | Line 2,630: | ||
{{libheader|Wren-dynamic}} |
{{libheader|Wren-dynamic}} |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
< |
<syntaxhighlight lang="ecmascript">import "random" for Random |
||
import "/dynamic" for Tuple |
import "/dynamic" for Tuple |
||
import "/fmt" for Fmt |
import "/fmt" for Fmt |
||
Line 2,686: | Line 2,686: | ||
System.print("\nRandom") |
System.print("\nRandom") |
||
var rand = Random.new() |
var rand = Random.new() |
||
for (i in 0..4) System.print(chess960.call(W, rand.int(960)))</ |
for (i in 0..4) System.print(chess960.call(W, rand.int(960)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,704: | Line 2,704: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">char Col; |
||
func ColNum(Start, Piece); \Return column number of Piece |
func ColNum(Start, Piece); \Return column number of Piece |
||
Line 2,735: | Line 2,735: | ||
Text(0, Col); CrLf(0); |
Text(0, Col); CrLf(0); |
||
]; |
]; |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,748: | Line 2,748: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|D}} |
{{trans|D}} |
||
< |
<syntaxhighlight lang="zkl">const pieces="KQRrBbNN"; |
||
starts:=pieces:Utils.Helpers.permuteW(_).filter(fcn(p){ |
starts:=pieces:Utils.Helpers.permuteW(_).filter(fcn(p){ |
||
I:=p.index; |
I:=p.index; |
||
Line 2,755: | Line 2,755: | ||
((I("r") < I("K") and I("K") < I("R")) or |
((I("r") < I("K") and I("K") < I("R")) or |
||
(I("R") < I("K") and I("K") < I("r"))) |
(I("R") < I("K") and I("K") < I("r"))) |
||
}).pump(List,"concat","toUpper"):Utils.Helpers.listUnique(_);</ |
}).pump(List,"concat","toUpper"):Utils.Helpers.listUnique(_);</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">N:=starts.len(); println(N); |
||
glyphs:=Dictionary("K","\u2654", "Q","\u2655", "R","\u2656", "B","\u2657", "N","\u2658"); |
glyphs:=Dictionary("K","\u2654", "Q","\u2655", "R","\u2656", "B","\u2657", "N","\u2658"); |
||
// pick some random starts and transform BBNRKQRN to glyphs |
// pick some random starts and transform BBNRKQRN to glyphs |
||
do(10){ starts[(0).random(N)].apply(glyphs.find).println() }</ |
do(10){ starts[(0).random(N)].apply(glyphs.find).println() }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>960 |
<pre>960 |