Latin Squares in reduced form: Difference between revisions

m
 
(4 intermediate revisions by 4 users not shown)
Line 12:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F dList(n, =start)
start--
V a = Array(0 .< n)
Line 20:
V first = a[1]
[[Int]] r
F recurse(Int last) -> NVoid
I (last == @first)
L(v) @a[1..]
Line 55:
 
V count = 0
F recurse(Int i) -> NVoid
V rows = dList(@n, i)
 
Line 91:
V f = factorial(n - 1)
f *= f * n * size
print(‘Order #.: Size #<4 x #.! x #.! => Total #.’.format(n, size, n, n - 1, f))</langsyntaxhighlight>
 
{{out}}
Line 130:
=={{header|C sharp|C#}}==
{{trans|D}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 280:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>The four reduced latin squares of order 4 are:
Line 316:
=={{header|C++}}==
{{trans|C#}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <functional>
#include <iostream>
Line 464:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>The four reduced lating squares of order 4 are:
Line 499:
=={{header|D}}==
{{trans|Go}}
<langsyntaxhighlight lang="d">import std.algorithm;
import std.array;
import std.range;
Line 626:
writefln("Order %d: Size %-4d x %d! x %d! => Total %d", n, size, n, n - 1, f);
}
}</langsyntaxhighlight>
{{out}}
<pre>The four reduced latin squares of order 4 are:
Line 663:
===The Function===
This task uses [[Permutations/Derangements#F.23]]
<langsyntaxhighlight lang="fsharp">
// Generate Latin Squares in reduced form. Nigel Galloway: July 10th., 2019
let normLS α=
Line 670:
let rec normLS n g=seq{for i in fG n N.[g] do if g=α-2 then yield [|1..α|]::(List.rev (i::n)) else yield! normLS (i::n) (g+1)}
match α with 1->seq[[[|1|]]] |2-> seq[[[|1;2|];[|2;1|]]] |_->Seq.collect(fun n->normLS [n] 1) N.[0]
</syntaxhighlight>
</lang>
===The Task===
<langsyntaxhighlight lang="fsharp">
normLS 4 |> Seq.iter(fun n->List.iter(printfn "%A") n;printfn "");;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 697:
[|4; 3; 2; 1|]
</pre>
<langsyntaxhighlight lang="fsharp">
let rec fact n g=if n<2 then g else fact (n-1) n*g
[1..6] |> List.iter(fun n->let nLS=normLS n|>Seq.length in printfn "order=%d number of Reduced Latin Squares nLS=%d nLS*n!*(n-1)!=%d" n nLS (nLS*(fact n 1)*(fact (n-1) 1)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 713:
=={{header|Go}}==
This reuses the dList function from the [[Permutations/Derangements#Go]] task, suitably adjusted for the present one.
<langsyntaxhighlight lang="go">package main
 
import (
Line 849:
fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f)
}
}</langsyntaxhighlight>
 
{{out}}
Line 889:
The solution uses permutation generator given by '''Data.List''' package and List monad for generating all possible latin squares as a fold of permutation list.
 
<langsyntaxhighlight lang="haskell">import Data.List (permutations, (\\))
import Control.Monad (foldM, forM_)
 
Line 909:
printTable :: Show a => [[a]] -> IO ()
printTable tbl = putStrLn $ unlines $ unwords . map show <$> tbl
</syntaxhighlight>
</lang>
 
It is slightly optimized by grouping permutations by the first element according to a set order. Partitioning reduces the filtering procedure by factor of an initial set size.
Line 949:
 
'''Tasks'''
<langsyntaxhighlight lang="haskell">task1 = do
putStrLn "Latin squares of order 4:"
mapM_ printTable $ latinSquares [1..4]
Line 959:
total = fact n * fact (n-1) * size
fact i = product [1..i]
in printf "Order %v: %v*%v!*%v!=%v\n" n size n (n-1) total</langsyntaxhighlight>
 
<pre>λ> task1 >> task2
Line 990:
Order 5: 56*5!*4!=161280
Order 6: 9408*6!*5!=812851200</pre>
 
=={{header|J}}==
Implementation:
<syntaxhighlight lang="j">
redlat=: {{
perms=: (A.&i.~ !)~ y
sqs=. i.1 1,y
for_j.}.i.y do.
p=. (j={."1 perms)#perms
sel=.-.+./"1 p +./@:="1/"2 sqs
sqs=.(#~ 1-0*/ .="1{:"2),/sqs,"2 1 sel#"2 p
end.
}}
</syntaxhighlight>
 
Task examples:
 
<syntaxhighlight lang="j"> redlat 4
0 1 2 3
1 0 3 2
2 3 0 1
3 2 1 0
 
0 1 2 3
1 0 3 2
2 3 1 0
3 2 0 1
 
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
 
0 1 2 3
1 3 0 2
2 0 3 1
3 2 1 0
#@redlat every 1 2 3 4 5 6
1 1 1 4 56 9408
(#@redlat every 1 2 3 4 5 6)*(!1 2 3 4 5 6x)*(!0 1 2 3 4 5x)
1 2 12 576 161280 812851200
</syntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
import java.math.BigInteger;
import java.util.ArrayList;
Line 1,199 ⟶ 1,241:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,239 ⟶ 1,281:
 
''' Preliminaries'''
<langsyntaxhighlight lang="jq">def count(s): reduce s as $x (0; .+1);
 
def factorial: reduce range(2;.+1) as $i (1; . * $i);
Line 1,249 ⟶ 1,291:
| [.[$i]] + (del(.[$i])|permutations)
end ;
</syntaxhighlight>
</lang>
'''Latin Squares'''
<langsyntaxhighlight lang="jq">def clash($row2; $row1):
any(range(0;$row2|length); $row1[.] == $row2[.]);
 
Line 1,288 ⟶ 1,330:
[[range(1;$n+1)]]
| complete_latin_square ;
</syntaxhighlight>
</lang>
'''The Task'''
<langsyntaxhighlight lang="jq">def task:
"The reduced latin squares of order 4 are:",
(4 | latin_squares),
Line 1,301 ⟶ 1,343:
) ;
 
task</langsyntaxhighlight>
{{out}}
Invocation: jq -nrc -f latin-squares.jq
Line 1,321 ⟶ 1,363:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Combinatorics
 
clash(row2, row1::Vector{Int}) = any(i -> row1[i] == row2[i], 1:length(row2))
Line 1,362 ⟶ 1,404:
testlatinsquares()
</langsyntaxhighlight>{{out}}
<pre>
The four reduced latin squares of order 4 are:
Line 1,395 ⟶ 1,437:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">typealias Matrix = MutableList<MutableList<Int>>
 
fun dList(n: Int, sp: Int): Matrix {
Line 1,515 ⟶ 1,557:
println("Order $n: Size %-4d x $n! x ${n - 1}! => Total $f".format(size))
}
}</langsyntaxhighlight>
{{out}}
<pre>The four reduced latin squares of order 4 are:
Line 1,551 ⟶ 1,593:
=={{header|MiniZinc}}==
===The Model (lsRF.mnz)===
<syntaxhighlight lang="minizinc">
<lang MiniZinc>
%Latin Squares in Reduced Form. Nigel Galloway, September 5th., 2019
include "alldifferent.mzn";
Line 1,557 ⟶ 1,599:
array[1..N,1..N] of var 1..N: p; constraint forall(n in 1..N)(p[1,n]=n /\ p[n,1]=n);
constraint forall(n in 1..N)(alldifferent([p[n,g]|g in 1..N])/\alldifferent([p[g,n]|g in 1..N]));
</syntaxhighlight>
</lang>
===The Tasks===
;displaying the four reduced Latin Squares of order 4
<syntaxhighlight lang="minizinc">
<lang MiniZinc>
include "lsRF.mzn";
output [show_int(1,p[i,j])++
Line 1,568 ⟶ 1,610:
else "" endif
| i,j in 1..4 ] ++ ["\n"];
</syntaxhighlight>
</lang>
When the above is run using minizinc --all-solutions -DN=4 the following is produced:
{{out}}
Line 1,649 ⟶ 1,691:
We use the Go algorithm but have chosen to create two types, Row and Matrix, to simulate sequences starting at index 1. So, the indexes and tests are somewhat different.
 
<langsyntaxhighlight Nimlang="nim">import algorithm, math, sequtils, strformat
 
type
Line 1,756 ⟶ 1,798:
let size = reducedLatinSquares(n, false)
let f = fac(n - 1)^2 * n * size
echo &"Order {n}: Size {size:<4} x {n}! x {n - 1}! => Total {f}"</langsyntaxhighlight>
 
{{out}}
Line 1,791 ⟶ 1,833:
=={{header|Perl}}==
It takes a little under 2 minutes to find order 7.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Latin_Squares_in_reduced_form
Line 1,823 ⟶ 1,865:
length $s <= 1 ? $s :
map { my $f = $_; map "$f$_", perm( $s =~ s/$_//r ) } split //, $s;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,864 ⟶ 1,906:
A Simple backtracking search.<br>
aside: in phix here is no difference between res[r][c] and res[r,c]. I mixed them here, using whichever felt the more natural to me.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">string</span> <span style="color: #000000;">aleph</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"</span>
Line 1,955 ⟶ 1,997:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Order %d: Size %-4d x %d! x %d! =&gt; Total %d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">size</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,991 ⟶ 2,033:
"2 minutes and 23s"
</pre>
 
=={{header|Picat}}==
Using Constraint modelling.
====The four solutions for N=4====
<syntaxhighlight lang="picat">import cp.
 
main =>
N = 4,
latin_square_reduced_form(N, X),
foreach(Row in X)
println(Row.to_list)
end,
nl,
fail.
 
latin_square_reduced_form(N, X) =>
X = new_array(N,N),
X :: 1..N,
foreach(I in 1..N)
all_different([X[I,J] : J in 1..N]),
all_different([X[J,I] : J in 1..N]),
X[1,I] #= I,
X[I,1] #= I
end,
solve(X).</syntaxhighlight>
 
{{out}}
<pre>[1,2,3,4]
[2,1,4,3]
[3,4,1,2]
[4,3,2,1]
 
[1,2,3,4]
[2,1,4,3]
[3,4,2,1]
[4,3,1,2]
 
[1,2,3,4]
[2,3,4,1]
[3,4,1,2]
[4,1,2,3]
 
[1,2,3,4]
[2,4,1,3]
[3,1,4,2]
[4,3,2,1]</pre>
 
====Number of solutions====
<syntaxhighlight lang="picat">import cp.
 
main =>
foreach(N in 1..7)
Count = count_all(latin_square_reduced_form(N, _X)),
printf("%2d %10d x %d! x %d! %16w\n",N,Count,N,N-1, Count*factorial(N)*factorial(N-1))
end,
nl.</syntaxhighlight>
 
{{out}}
<pre> 1 1 x 1! x 0! 1
2 1 x 2! x 1! 2
3 1 x 3! x 2! 12
4 4 x 4! x 3! 576
5 56 x 5! x 4! 161280
6 9408 x 6! x 5! 812851200
7 16942080 x 7! x 6! 61479419904000</pre>
 
For N=1..6 this model takes 23ms. For N=1..7 it takes 28.1s.
 
=={{header|Python}}==
{{trans|D}}
<langsyntaxhighlight lang="python">def dList(n, start):
start -= 1 # use 0 basing
a = range(n)
Line 2,090 ⟶ 2,199:
f = factorial(n - 1)
f *= f * n * size
print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)</langsyntaxhighlight>
{{out}}
<pre>The four reduced latin squares of order 4 are:
Line 2,126 ⟶ 2,235:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line># utilities: factorial, sub-factorial, derangements
sub postfix:<!>($n) { (constant f = 1, |[\×] 1..*)[$n] }
sub prefix:<!>($n) { (1, 0, 1, -> $a, $b { ($++ + 2) × ($b + $a) } ... *)[$n] }
Line 2,156 ⟶ 2,265:
for 1..6 -> $n {
printf "Order $n: Size %-4d x $n! x {$n-1}! => Total %d\n", $_, $_ * $n! * ($n-1)! given LS-reduced($n).elems
}</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4
Line 2,187 ⟶ 2,296:
=={{header|Ruby}}==
{{trans|D}}
<langsyntaxhighlight lang="ruby">def printSquare(a)
for row in a
print row, "\n"
Line 2,308 ⟶ 2,417:
f = f * f * n * size
print "Order %d Size %-4d x %d! x %d! => Total %d\n" % [n, size, n, n - 1, f]
end</langsyntaxhighlight>
{{out}}
<pre>The four reduced latin squares of order 4 are:
Line 2,342 ⟶ 2,451:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Option Strict On
 
Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))
Line 2,500 ⟶ 2,609:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>The four reduced latin squares of order 4 are:
Line 2,539 ⟶ 2,648:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./sort" for Sort
import "./math" for Int
import "./fmt" for Fmt
 
// generate derangements of first n numbers, with 'start' in first place.
Line 2,653 ⟶ 2,762:
f = f * f * n * size
Fmt.print("Order $d: Size $-4d x $d! x $d! => Total $d", n, size, n, n-1, f)
}</langsyntaxhighlight>
 
{{out}}
Line 2,693 ⟶ 2,802:
{{trans|Go}}
This reuses the dList function from the [[Permutations/Derangements#zkl]] task, suitably adjusted for the present one.
<langsyntaxhighlight lang="zkl">fcn reducedLatinSquare(n,write=False){
if(n<=1) return(n);
rlatin:=n.pump(List(), List.createLong(n,0).copy); // matrix of zeros
Line 2,732 ⟶ 2,841:
println();
}
fcn fact(n){ ([1..n]).reduce('*,1) }</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">println("The four reduced latin squares of order 4 are:");
reducedLatinSquare(4,True);
 
Line 2,741 ⟶ 2,850:
size,f,f := reducedLatinSquare(n), fact(n - 1), f*f*n*size;;
println("Order %d: Size %-4d x %d! x %d! -> Total %,d".fmt(n,size,n,n-1,f));
}</langsyntaxhighlight>
{{out}}
<pre>
1,480

edits