Random Latin squares: Difference between revisions
m
syntax highlighting fixup automation
(Added related tasks) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 29:
{{trans|Python}}
<
assert(matrix.len == matrix[0].len)
V r = [[0] * matrix.len] * matrix.len
Line 74:
print(square.map(row -> row.join(‘ ’)).join("\n"))
_check(square)
print()</
{{out}}
Line 100:
=={{header|Action!}}==
<
DEFINE DIMENSION="5"
Line 223:
PutE()
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Random_Latin_squares.png Screenshot from Atari 8-bit computer]
Line 242:
=={{header|Arturo}}==
<
square: new []
variants: shuffle permutate 0..n-1
Line 265:
print row
print "---------"
]</
{{out}}
Line 283:
=={{header|C}}==
{{trans|C++}}
<
#include <stdio.h>
#include <stdlib.h>
Line 400:
return 0;
}</
{{out}}
<pre>[1, 4, 3, 0, 2]
Line 427:
=={{header|C++}}==
{{trans|Java}}
<
#include <chrono>
#include <iostream>
Line 520:
latinSquare(10);
return 0;
}</
{{out}}
<pre>[4, 3, 1, 2, 0]
Line 547:
=={{header|C sharp|C#}}==
{{trans|Kotlin}}
<
using System.Collections.Generic;
Line 651:
}
}
}</
{{out}}
<pre>[3, 0, 1, 4, 2]
Line 678:
=={{header|D}}==
{{trans|C#}}
<
import std.random;
import std.stdio;
Line 750:
latinSquare(10);
}</
{{out}}
<pre>[2, 4, 3, 1, 0]
Line 777:
=={{header|F_Sharp|F#}}==
This solution uses functions from [[Factorial_base_numbers_indexing_permutations_of_a_collection#F.23]] and [[Latin_Squares_in_reduced_form#F.23]]. This solution generates completely random uniformly distributed Latin Squares from all possible Latin Squares of order 5. It takes 5 thousandths of a second can that really be called hard?
<
// Generate 2 Random Latin Squares of order 5. Nigel Galloway: July 136th., 2019
let N=let N=System.Random() in (fun n->N.Next(n))
let rc()=let β=lN2p [|0;N 4;N 3;N 2|] [|0..4|] in Seq.item (N 56) (normLS 5) |> List.map(lN2p [|N 5;N 4;N 3;N 2|]) |> List.permute(fun n->β.[n]) |> List.iter(printfn "%A")
rc(); printfn ""; rc()
</syntaxhighlight>
{{out}}
<pre>
Line 824:
=={{header|Factor}}==
A brute force method for generating uniformly random Latin squares. Repeatedly select a random permutation of (0, 1,...n-1) and add it as the next row of the square. If at any point the rules for being a Latin square are violated, start the entire process over again from the beginning.
<
prettyprint random sequences sets ;
IN: rosetta-code.random-latin-squares
Line 834:
: random-latin-squares ( -- ) [ 5 ls simple-table. nl ] twice ;
MAIN: random-latin-squares</
{{out}}
<pre>
Line 853:
===Restarting Row method===
As the task is not asking for large squares to be generated and even n = 10 is virtually instant, we use a simple brute force approach here known as the 'Restarting Row' method (see Talk page). However, whilst easy to understand, this method does not produce uniformly random squares.
<
import (
Line 932:
latinSquare(5)
latinSquare(10) // for good measure
}</
{{out}}
Line 963:
===Latin Squares in Reduced Form method===
Unlike the "Restarting Row" method, this method does produce uniformly random Latin squares for n <= 6 (see Talk page) but is more involved and therefore slower. It reuses some (suitably adjusted) code from the [https://rosettacode.org/wiki/Latin_Squares_in_reduced_form#Go Latin Squares in Reduced Form] and [https://rosettacode.org/wiki/Permutations#non-recursive.2C_lexicographical_order Permutations] tasks.
<
import (
Line 1,215:
fmt.Println("\nA randomly generated latin square of order 6 is:\n")
generateLatinSquares(6, 1, 1)
}</
{{out}}
Line 1,259:
given first row and first column.
<
latinSquare :: Eq a => [a] -> [a] -> [[a]]
Line 1,286:
putStrLn $
unlines $
unwords . map show <$> tbl</
<pre>λ> printTable $ latinSquare [1,2,3,4,5] [1,3,2,5,4]
Line 1,298:
the deterministic algorithm.
<
randomLatinSquare set = do
r <- randomPermutation set
c <- randomPermutation (tail r)
return $ latinSquare r (head r:c)</
For examples a naive linear congruent method in a State monad is used.
<
type Random a = State Int a
Line 1,326:
randomSample :: [a] -> Random a
randomSample lst = (lst !!) <$> random (length lst)</
<pre>λ> printTable $ randomLatinSquare [0..4] `evalState` 42
Line 1,349:
=={{header|J}}==
<
s=. ?~ y NB. "deal" y unique integers from 0 to y
for_ijk. i.<:y do.
Line 1,360:
end.
)
</syntaxhighlight>
{{out}}
<pre> rls 5
Line 1,377:
=={{header|Java}}==
{{trans|Kotlin}}
<
import java.util.Collections;
import java.util.Iterator;
Line 1,462:
latinSquare(10);
}
}</
{{out}}
<pre>[1, 3, 4, 0, 2]
Line 1,488:
=={{header|Javascript}}==
<
class Latin {
constructor(size = 3) {
Line 1,541:
}
new Latin(5);
</syntaxhighlight>
{{out}}
<pre>
Line 1,559:
=={{header|Julia}}==
Using the Python algorithm as described in the discussion section.
<
shufflerows(mat) = mat[shuffle(1:end), :]
Line 1,590:
printlatinsquare(5), println("\n"), printlatinsquare(5)
</
<pre>
1 3 0 4 2
Line 1,608:
=={{header|Kotlin}}==
{{trans|Go}}
<
fun printSquare(latin: matrix) {
Line 1,665:
latinSquare(5)
latinSquare(10) // for good measure
}</
{{out}}
<pre>[4, 1, 2, 3, 0]
Line 1,698:
We use the stack of values, a linked list, for pushing to top (Push) or to bottom (Data), and we can pop from top using Number or by using Read A to read A from stack. Also we can shift from a chosen position to top using Shift, or using shiftback to move an item from top to chosen position. So we shuffle items by shifting them.
<syntaxhighlight lang="m2000 interpreter">
Module FastLatinSquare {
n=5
Line 1,749:
End Sub
}
FastLatinSquare</
===Hard Way===
Line 1,758:
for 20X20 need 22 min (as for 9.8 version)
<syntaxhighlight lang="m2000 interpreter">
Module LatinSquare (n, z=1, f$="latin.dat", NewFile As Boolean=False) {
If Not Exist(f$) Or NewFile Then
Line 1,833:
LatinSquare 16
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,868:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
RandomLatinSquare[n_] := Module[{out, ord},
out = Table[RotateLeft[Range[n], i], {i, n}];
Line 1,876:
out
]
RandomLatinSquare[5] // Grid</
{{out}}
<pre>5 2 4 1 3
Line 1,890:
Starting at n = 11, the execution time will be very variable as the program proceeds by trial and error. At least, the algorithm will be able to produce all the possible Latin squares but not in a uniform way.
<
type LatinSquare = seq[seq[char]]
Line 1,933:
echo latinSquare(5)
echo latinSquare(5)
echo latinSquare(10)</
{{out}}
Line 1,969:
Jacobson, M. T.; Matthews, P. (1996). "Generating uniformly distributed random latin squares". Journal of Combinatorial Designs. 4 (6): 405–437.
<
{$APPTYPE CONSOLE}
Line 2,110:
end.
</syntaxhighlight>
{{out}}
Line 2,172:
=={{header|Perl}}==
{{trans|Raku}}
<
use warnings;
use feature 'say';
Line 2,204:
}
say display random_ls($_) for 2..5, 5;</
{{out}}
<pre>B A
Line 2,232:
=={{header|Phix}}==
Brute force, begins to struggle above 42.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">aleph</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"</span>
Line 2,298:
<span style="color: #000000;">latin_square</span><span style="color: #0000FF;">(</span><span style="color: #000000;">42</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</
{{out}}
<pre>
Line 2,385:
Normally a non-random value strategy is preferred such as <code>up</code>, <code>split</code>, or <code>updown</code>, but the task requires random solutions.
<
_ = random2(), % random seed
N = 5,
Line 2,420:
nl
end,
nl.</
{{out}}
Line 2,502:
===Number of solutions===
The number of solutions for a Latin square of size N is the OEIS sequence [https://oeis.org/A002860 A002860: Number of Latin squares of order n; or labeled quasigroups]. Here we check N = 1..6 which took 18min54s.
<
foreach(N in 1..6)
Count = count_all(latin_square(N,_)),
println(N=Count)
end.</
{{out}}
Line 2,521:
=={{header|Python}}==
<
from copy import deepcopy
Line 2,581:
print(_to_text(square))
_check(square)
print()</
{{out}}
Line 2,622:
{{trans|Python}}
<syntaxhighlight lang="raku"
sub random ( @ls, :$size = 5 ) {
Line 2,656:
# Or, if you'd prefer:
display random latin-square, :size($_) for 12, 2, 1;</
{{out|Sample output}}
<pre> V Z M J U
Line 2,706:
The symbols could be any characters (except those that contain a blank), but the numbers from '''0''' ──► '''N-1''' are used.
<
parse arg N seed . /*obtain the optional argument from CL.*/
if N=='' | N=="," then N= 5 /*Not specified? Then use the default.*/
Line 2,721:
do j=1 for N /* [↓] display rows of random Latin sq*/
say translate(subword(zz, j, N), , '_') /*translate leading underbar to blank. */
end /*j*/ /*stick a fork in it, we're all done. */</
{{out|output|text= for 1<sup>st</sup> run when using the default inputs:}}
<pre>
Line 2,740:
=={{header|Ring}}==
<
load "stdlib.ring"
load "guilib.ring"
Line 3,086:
###====================================================================================
</syntaxhighlight>
[https://www.mediafire.com/file/6fruvfgydnbmtyj/RandomLatinSquares.jpg/file Random Latin Squares - image]
Line 3,092:
=={{header|Ruby}}==
This crude algorithm works fine up to a square size of 10; higher values take too much time and memory. It creates an array of all possible permutations, picks a random one as first row an weeds out all permutations which cannot appear in the remaining square. Repeat picking and weeding until there is a square.
<
def generate_square
Line 3,111:
2.times{print_square( generate_square)}
</syntaxhighlight>
{{out}}<pre>
3 4 2 1 5
Line 3,130:
{{trans|Go}}
===Restarting Row method===
<
var rand = Random.new()
Line 3,189:
latinSquare.call(5)
latinSquare.call(5)
latinSquare.call(10) // for good measure</
{{out}}
Line 3,222:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<
import "/sort" for Sort
import "/fmt" for Fmt
Line 3,437:
for (i in 0..3) System.print("%(testSquares[i]) : %(counts[i])")
System.print("\nA randomly generated latin square of order 6 is:\n")
generateLatinSquares.call(6, 1, 1)</
{{out}}
Line 3,476:
=={{header|zkl}}==
<
if(n<=0) return(T);
square,syms := List(), symbols.walker().walk(n);
Line 3,483:
T.zip(square.shuffle().xplode()).shuffle();
}
fcn rls2String(square){ square.apply("concat"," ").concat("\n") }</
<
randomLatinSquare(5, ["A".."Z"]) : rls2String(_).println("\n");
randomLatinSquare(10,"!@#$%^&*()") : rls2String(_).println("\n");</
{{out}}
<pre>
|