Random Latin squares: Difference between revisions

m
syntax highlighting fixup automation
(Added related tasks)
m (syntax highlighting fixup automation)
Line 29:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F _transpose(matrix)
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()</langsyntaxhighlight>
 
{{out}}
Line 100:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE PTR="CARD"
DEFINE DIMENSION="5"
 
Line 223:
PutE()
OD
RETURN</langsyntaxhighlight>
{{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}}==
 
<langsyntaxhighlight lang="rebol">latinSquare: function [n][
square: new []
variants: shuffle permutate 0..n-1
Line 265:
print row
print "---------"
]</langsyntaxhighlight>
 
{{out}}
Line 283:
=={{header|C}}==
{{trans|C++}}
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
Line 400:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 4, 3, 0, 2]
Line 427:
=={{header|C++}}==
{{trans|Java}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <chrono>
#include <iostream>
Line 520:
latinSquare(10);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>[4, 3, 1, 2, 0]
Line 547:
=={{header|C sharp|C#}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 651:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>[3, 0, 1, 4, 2]
Line 678:
=={{header|D}}==
{{trans|C#}}
<langsyntaxhighlight lang="d">import std.array;
import std.random;
import std.stdio;
Line 750:
 
latinSquare(10);
}</langsyntaxhighlight>
{{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?
<langsyntaxhighlight lang="fsharp">
// 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>
</lang>
{{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.
<langsyntaxhighlight lang="factor">USING: arrays combinators.extras fry io kernel math.matrices
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</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 932:
latinSquare(5)
latinSquare(10) // for good measure
}</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,215:
fmt.Println("\nA randomly generated latin square of order 6 is:\n")
generateLatinSquares(6, 1, 1)
}</langsyntaxhighlight>
 
{{out}}
Line 1,259:
given first row and first column.
 
<langsyntaxhighlight lang="haskell">import Data.List (permutations, (\\))
 
latinSquare :: Eq a => [a] -> [a] -> [[a]]
Line 1,286:
putStrLn $
unlines $
unwords . map show <$> tbl</langsyntaxhighlight>
 
<pre>λ> printTable $ latinSquare [1,2,3,4,5] [1,3,2,5,4]
Line 1,298:
the deterministic algorithm.
 
<langsyntaxhighlight lang="haskell">randomLatinSquare :: Eq a => [a] -> Random [[a]]
randomLatinSquare set = do
r <- randomPermutation set
c <- randomPermutation (tail r)
return $ latinSquare r (head r:c)</langsyntaxhighlight>
 
For examples a naive linear congruent method in a State monad is used.
 
<langsyntaxhighlight lang="haskell">import Control.Monad.State
 
type Random a = State Int a
Line 1,326:
 
randomSample :: [a] -> Random a
randomSample lst = (lst !!) <$> random (length lst)</langsyntaxhighlight>
 
<pre>λ> printTable $ randomLatinSquare [0..4] `evalState` 42
Line 1,349:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">rls=: 3 : 0
s=. ?~ y NB. "deal" y unique integers from 0 to y
for_ijk. i.<:y do.
Line 1,360:
end.
)
</syntaxhighlight>
</lang>
{{out}}
<pre> rls 5
Line 1,377:
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="java">import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
Line 1,462:
latinSquare(10);
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 3, 4, 0, 2]
Line 1,488:
 
=={{header|Javascript}}==
<langsyntaxhighlight lang="javascript">
class Latin {
constructor(size = 3) {
Line 1,541:
}
new Latin(5);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,559:
=={{header|Julia}}==
Using the Python algorithm as described in the discussion section.
<langsyntaxhighlight lang="julia">using Random
 
shufflerows(mat) = mat[shuffle(1:end), :]
Line 1,590:
 
printlatinsquare(5), println("\n"), printlatinsquare(5)
</langsyntaxhighlight>{{out}}
<pre>
1 3 0 4 2
Line 1,608:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">typealias matrix = MutableList<MutableList<Int>>
 
fun printSquare(latin: matrix) {
Line 1,665:
latinSquare(5)
latinSquare(10) // for good measure
}</langsyntaxhighlight>
{{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">
<lang M2000 Interpreter>
Module FastLatinSquare {
n=5
Line 1,749:
End Sub
}
FastLatinSquare</langsyntaxhighlight>
 
===Hard Way===
Line 1,758:
for 20X20 need 22 min (as for 9.8 version)
 
<syntaxhighlight lang="m2000 interpreter">
<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>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,868:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Clear[RandomLatinSquare]
RandomLatinSquare[n_] := Module[{out, ord},
out = Table[RotateLeft[Range[n], i], {i, n}];
Line 1,876:
out
]
RandomLatinSquare[5] // Grid</langsyntaxhighlight>
{{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.
 
<langsyntaxhighlight Nimlang="nim">import random, sequtils, strutils
 
type LatinSquare = seq[seq[char]]
Line 1,933:
echo latinSquare(5)
echo latinSquare(5)
echo latinSquare(10)</langsyntaxhighlight>
 
{{out}}
Line 1,969:
Jacobson, M. T.; Matthews, P. (1996). "Generating uniformly distributed random latin squares". Journal of Combinatorial Designs. 4 (6): 405–437.
 
<langsyntaxhighlight lang="pascal">
 
{$APPTYPE CONSOLE}
Line 2,110:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,172:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 2,204:
}
 
say display random_ls($_) for 2..5, 5;</langsyntaxhighlight>
{{out}}
<pre>B A
Line 2,232:
=={{header|Phix}}==
Brute force, begins to struggle above 42.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{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.
 
<langsyntaxhighlight Picatlang="picat">main =>
_ = random2(), % random seed
N = 5,
Line 2,420:
nl
end,
nl.</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight Picatlang="picat">main =>
foreach(N in 1..6)
Count = count_all(latin_square(N,_)),
println(N=Count)
end.</langsyntaxhighlight>
 
{{out}}
Line 2,521:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from random import choice, shuffle
from copy import deepcopy
 
Line 2,581:
print(_to_text(square))
_check(square)
print()</langsyntaxhighlight>
 
{{out}}
Line 2,622:
{{trans|Python}}
 
<syntaxhighlight lang="raku" perl6line>sub latin-square { [[0],] };
 
sub random ( @ls, :$size = 5 ) {
Line 2,656:
 
# Or, if you'd prefer:
display random latin-square, :size($_) for 12, 2, 1;</langsyntaxhighlight>
{{out|Sample output}}
<pre> V Z M J U
Line 2,706:
 
The symbols could be any characters (except those that contain a blank), &nbsp; but the numbers from &nbsp; '''0''' ──► '''N-1''' &nbsp; are used.
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays a randomized Latin square. */
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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; for 1<sup>st</sup> run when using the default inputs:}}
<pre>
Line 2,740:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
load "guilib.ring"
Line 3,086:
###====================================================================================
 
</syntaxhighlight>
</lang>
 
[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.
<langsyntaxhighlight lang="ruby">N = 5
 
def generate_square
Line 3,111:
 
2.times{print_square( generate_square)}
</syntaxhighlight>
</lang>
{{out}}<pre>
3 4 2 1 5
Line 3,130:
{{trans|Go}}
===Restarting Row method===
<langsyntaxhighlight lang="ecmascript">import "random" for Random
 
var rand = Random.new()
Line 3,189:
latinSquare.call(5)
latinSquare.call(5)
latinSquare.call(10) // for good measure</langsyntaxhighlight>
 
{{out}}
Line 3,222:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<langsyntaxhighlight lang="ecmascript">import "random" for Random
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)</langsyntaxhighlight>
 
{{out}}
Line 3,476:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn randomLatinSquare(n,symbols=[1..]){ //--> list of lists
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") }</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach n in (T(1,2,5)){ randomLatinSquare(n) : rls2String(_).println("\n") }
randomLatinSquare(5, ["A".."Z"]) : rls2String(_).println("\n");
randomLatinSquare(10,"!@#$%^&*()") : rls2String(_).println("\n");</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits