Perfect shuffle: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 89: Line 89:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F flatten(lst)
<syntaxhighlight lang="11l">F flatten(lst)
[Int] r
[Int] r
L(sublst) lst
L(sublst) lst
Line 112: Line 112:
V deck = Array(0 .< length)
V deck = Array(0 .< length)
V shuffles_needed = after_how_many_is_equal(deck, deck)
V shuffles_needed = after_how_many_is_equal(deck, deck)
print(‘#<5 | #.’.format(length, shuffles_needed))</lang>
print(‘#<5 | #.’.format(length, shuffles_needed))</syntaxhighlight>


{{out}}
{{out}}
Line 128: Line 128:
=={{header|Action!}}==
=={{header|Action!}}==
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
<lang Action!>DEFINE MAXDECK="5000"
<syntaxhighlight lang="action!">DEFINE MAXDECK="5000"


PROC Order(INT ARRAY deck INT count)
PROC Order(INT ARRAY deck INT count)
Line 188: Line 188:
Test(deck,deck2,counts(i))
Test(deck,deck2,counts(i))
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Perfect_shuffle.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Perfect_shuffle.png Screenshot from Atari 8-bit computer]
Line 202: Line 202:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with ada.text_io;use ada.text_io;
<syntaxhighlight lang="ada">with ada.text_io;use ada.text_io;


procedure perfect_shuffle is
procedure perfect_shuffle is
Line 229: Line 229:
put_line ("For" & size'img & " cards, there are "& count_shuffle (size / 2)'img & " shuffles needed.");
put_line ("For" & size'img & " cards, there are "& count_shuffle (size / 2)'img & " shuffles needed.");
end loop;
end loop;
end perfect_shuffle;</lang>
end perfect_shuffle;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 242: Line 242:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68># returns an array of the specified length, initialised to an ascending sequence of integers #
<syntaxhighlight lang="algol68"># returns an array of the specified length, initialised to an ascending sequence of integers #
OP DECK = ( INT length )[]INT:
OP DECK = ( INT length )[]INT:
BEGIN
BEGIN
Line 299: Line 299:
FOR l FROM LWB lengths TO UPB lengths DO
FOR l FROM LWB lengths TO UPB lengths DO
print( ( whole( lengths[ l ], -8 ) + ": " + whole( count shuffles( lengths[ l ] ), -6 ), newline ) )
print( ( whole( lengths[ l ], -8 ) + ": " + whole( count shuffles( lengths[ l ] ), -6 ), newline ) )
OD</lang>
OD</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 313: Line 313:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang apl>faro ← ∊∘⍉(2,2÷⍨≢)⍴⊢
<syntaxhighlight lang="apl">faro ← ∊∘⍉(2,2÷⍨≢)⍴⊢
count ← {⍺←⍵ ⋄ ⍺≡r←⍺⍺ ⍵:1 ⋄ 1+⍺∇r}
count ← {⍺←⍵ ⋄ ⍺≡r←⍺⍺ ⍵:1 ⋄ 1+⍺∇r}
(⊢,[1.5] (faro count ⍳)¨) 8 24 52 100 1020 1024 10000</lang>
(⊢,[1.5] (faro count ⍳)¨) 8 24 52 100 1020 1024 10000</syntaxhighlight>
{{out}}
{{out}}
<pre> 8 3
<pre> 8 3
Line 327: Line 327:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>perfectShuffle: function [deckSize][
<syntaxhighlight lang="rebol">perfectShuffle: function [deckSize][
deck: 1..deckSize
deck: 1..deckSize
original: new deck
original: new deck
Line 344: Line 344:
pad.right join @["Perfect shuffles required for deck size " to :string s ":"] 48
pad.right join @["Perfect shuffles required for deck size " to :string s ":"] 48
perfectShuffle s
perfectShuffle s
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 357: Line 357:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Shuffle(cards){
<syntaxhighlight lang="autohotkey">Shuffle(cards){
n := cards.MaxIndex()/2, res := []
n := cards.MaxIndex()/2, res := []
loop % n
loop % n
res.push(cards[A_Index]), res.push(cards[round(A_Index + n)])
res.push(cards[A_Index]), res.push(cards[round(A_Index + n)])
return res
return res
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>test := [8, 24, 52, 100, 1020, 1024, 10000]
Examples:<syntaxhighlight lang="autohotkey">test := [8, 24, 52, 100, 1020, 1024, 10000]
for each, val in test
for each, val in test
{
{
Line 379: Line 379:
}
}
MsgBox % result
MsgBox % result
return</lang>
return</syntaxhighlight>
Outputs:<pre>8 3
Outputs:<pre>8 3
24 11
24 11
Line 390: Line 390:
=={{header|C}}==
=={{header|C}}==


<lang c>/* ===> INCLUDES <============================================================*/
<syntaxhighlight lang="c">/* ===> INCLUDES <============================================================*/
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
Line 500: Line 500:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 518: Line 518:
=={{header|C sharp}}==
=={{header|C sharp}}==
{{works with|C sharp|6}}
{{works with|C sharp|6}}
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 550: Line 550:
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 563: Line 563:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <algorithm>
#include <algorithm>
Line 602: Line 602:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 615: Line 615:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn perfect-shuffle [deck]
<syntaxhighlight lang="clojure">(defn perfect-shuffle [deck]
(let [half (split-at (/ (count deck) 2) deck)]
(let [half (split-at (/ (count deck) 2) deck)]
(interleave (first half) (last half))))
(interleave (first half) (last half))))
Line 626: Line 626:
(inc (some identity (map-indexed (fn [i x] (when (predicate x) i)) trials)))))))
(inc (some identity (map-indexed (fn [i x] (when (predicate x) i)) trials)))))))


(map solve [8 24 52 100 1020 1024 10000])</lang>
(map solve [8 24 52 100 1020 1024 10000])</syntaxhighlight>


{{out}}
{{out}}
Line 640: Line 640:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun perfect-shuffle (deck)
<syntaxhighlight lang="lisp">(defun perfect-shuffle (deck)
(let* ((half (floor (length deck) 2))
(let* ((half (floor (length deck) 2))
(left (subseq deck 0 half))
(left (subseq deck 0 half))
Line 660: Line 660:
(solve 1020)
(solve 1020)
(solve 1024)
(solve 1024)
(solve 10000)</lang>
(solve 10000)</syntaxhighlight>
{{out}}
{{out}}
<pre> 8: 3
<pre> 8: 3
Line 672: Line 672:
=={{header|D}}==
=={{header|D}}==
{{trans|Java}}
{{trans|Java}}
<lang D>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
Line 702: Line 702:


assert(false, "How did this get here?");
assert(false, "How did this get here?");
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 715: Line 715:
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{Trans|Go}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Perfect_shuffle;
program Perfect_shuffle;


Line 815: Line 815:
end;
end;
readln;
readln;
end.</lang>
end.</syntaxhighlight>


=={{header|Dyalect}}==
=={{header|Dyalect}}==
Line 821: Line 821:
{{trans|C#}}
{{trans|C#}}


<lang dyalect>func shuffle(arr) {
<syntaxhighlight lang="dyalect">func shuffle(arr) {
if arr.Length() % 2 != 0 {
if arr.Length() % 2 != 0 {
throw @InvalidValue(arr.Length())
throw @InvalidValue(arr.Length())
Line 866: Line 866:
var numbers = [1..input]
var numbers = [1..input]
print("\(input) cards: \(shuffleThrough(numbers).Length())")
print("\(input) cards: \(shuffleThrough(numbers).Length())")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 879: Line 879:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
;; shuffler : a permutation vector which interleaves both halves of deck
;; shuffler : a permutation vector which interleaves both halves of deck
(define (make-shuffler n)
(define (make-shuffler n)
Line 899: Line 899:
#:break (eqv? deck dock) ;; compare to first
#:break (eqv? deck dock) ;; compare to first
1)))))
1)))))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
<lang lisp>
<syntaxhighlight lang="lisp">
map magic-shuffle '(8 24 52 100 1020 1024 10000))
map magic-shuffle '(8 24 52 100 1020 1024 10000))
→ ((8 . 3) (24 . 11) (52 . 8) (100 . 30) (1020 . 1018) (1024 . 10) (10000 . 300))
→ ((8 . 3) (24 . 11) (52 . 8) (100 . 30) (1020 . 1018) (1024 . 10) (10000 . 300))
Line 915: Line 915:
(oeis '(1 2 4 3 6 10 12 4))
(oeis '(1 2 4 3 6 10 12 4))
→ Sequence A002326 found
→ Sequence A002326 found
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang elixir>defmodule Perfect do
<syntaxhighlight lang="elixir">defmodule Perfect do
def shuffle(n) do
def shuffle(n) do
start = Enum.to_list(1..n)
start = Enum.to_list(1..n)
Line 942: Line 942:
step = Perfect.shuffle(n)
step = Perfect.shuffle(n)
IO.puts "#{n} : #{step}"
IO.puts "#{n} : #{step}"
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 956: Line 956:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
let perfectShuffle xs =
let perfectShuffle xs =
let h = (List.length xs) / 2
let h = (List.length xs) / 2
Line 972: Line 972:


[ 8; 24; 52; 100; 1020; 1024; 10000 ] |> List.iter (fun n->n |> orderCount |> printfn "%d %d" n)
[ 8; 24; 52; 100; 1020; 1024; 10000 ] |> List.iter (fun n->n |> orderCount |> printfn "%d %d" n)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 986: Line 986:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: arrays formatting kernel math prettyprint sequences
<syntaxhighlight lang="factor">USING: arrays formatting kernel math prettyprint sequences
sequences.merged ;
sequences.merged ;
IN: rosetta-code.perfect-shuffle
IN: rosetta-code.perfect-shuffle
Line 999: Line 999:


"Deck size" "Number of shuffles required" "%-11s %-11s\n" printf
"Deck size" "Number of shuffles required" "%-11s %-11s\n" printf
test-cases [ dup shuffle-count "%-11d %-11d\n" printf ] each</lang>
test-cases [ dup shuffle-count "%-11d %-11d\n" printf ] each</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,013: Line 1,013:


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran>MODULE PERFECT_SHUFFLE
<syntaxhighlight lang="fortran">MODULE PERFECT_SHUFFLE
IMPLICIT NONE
IMPLICIT NONE


Line 1,095: Line 1,095:
WRITE(*,'(I17, A, I35)') DECK_SIZES(I), " | ", COUNTER
WRITE(*,'(I17, A, I35)') DECK_SIZES(I), " | ", COUNTER
END DO
END DO
END PROGRAM DEMO_PERFECT_SHUFFLE</lang>
END PROGRAM DEMO_PERFECT_SHUFFLE</syntaxhighlight>
<pre>
<pre>
input (deck size) | output (number of shuffles required)
input (deck size) | output (number of shuffles required)
Line 1,109: Line 1,109:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>function is_in_order( d() as uinteger ) as boolean
<syntaxhighlight lang="freebasic">function is_in_order( d() as uinteger ) as boolean
'tests if a deck is in order
'tests if a deck is in order
for i as uinteger = lbound(d) to ubound(d)-1
for i as uinteger = lbound(d) to ubound(d)-1
Line 1,152: Line 1,152:
for i = 1 to 7
for i = 1 to 7
print tests(i);" cards require "; shufs_needed(tests(i)); " shuffles."
print tests(i);" cards require "; shufs_needed(tests(i)); " shuffles."
next i</lang>
next i</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
8 cards require 3 shuffles.
8 cards require 3 shuffles.
Line 1,164: Line 1,164:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,222: Line 1,222:
}
}
return
return
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Cards count: 8, shuffles required: 3
<pre>Cards count: 8, shuffles required: 3
Line 1,233: Line 1,233:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>shuffle :: [a] -> [a]
<syntaxhighlight lang="haskell">shuffle :: [a] -> [a]
shuffle lst = let (a,b) = splitAt (length lst `div` 2) lst
shuffle lst = let (a,b) = splitAt (length lst `div` 2) lst
in foldMap (\(x,y) -> [x,y]) $ zip a b
in foldMap (\(x,y) -> [x,y]) $ zip a b
Line 1,244: Line 1,244:
report n = putStrLn ("deck of " ++ show n ++ " cards: "
report n = putStrLn ("deck of " ++ show n ++ " cards: "
++ show (countSuffles n) ++ " shuffles!")
++ show (countSuffles n) ++ " shuffles!")
countSuffles n = 1 + length (findCycle shuffle [1..n])</lang>
countSuffles n = 1 + length (findCycle shuffle [1..n])</syntaxhighlight>


{{out}}
{{out}}
Line 1,260: Line 1,260:
The shuffle routine:
The shuffle routine:


<lang J> shuf=: /: $ /:@$ 0 1"_</lang>
<syntaxhighlight lang="j"> shuf=: /: $ /:@$ 0 1"_</syntaxhighlight>


Here, the phrase ($ $ 0 1"_) would generate a sequence of 0s and 1s the same length as the argument sequence:
Here, the phrase ($ $ 0 1"_) would generate a sequence of 0s and 1s the same length as the argument sequence:


<lang J> ($ $ 0 1"_) 'abcdef'
<syntaxhighlight lang="j"> ($ $ 0 1"_) 'abcdef'
0 1 0 1 0 1</lang>
0 1 0 1 0 1</syntaxhighlight>


And we can use ''grade up'' <code>(/:)</code> to find the indices which would sort the argument sequence so that the values in the positions corresponding to our generated zeros would come before the values in the positions corresponding to our ones.
And we can use ''grade up'' <code>(/:)</code> to find the indices which would sort the argument sequence so that the values in the positions corresponding to our generated zeros would come before the values in the positions corresponding to our ones.


<lang J> /: ($ $ 0 1"_) 'abcdef'
<syntaxhighlight lang="j"> /: ($ $ 0 1"_) 'abcdef'
0 2 4 1 3 5</lang>
0 2 4 1 3 5</syntaxhighlight>


But we can use ''grade up'' again to find what would have been the original permutation (''grade up'' is a self inverting function for this domain).
But we can use ''grade up'' again to find what would have been the original permutation (''grade up'' is a self inverting function for this domain).


<lang J> /:/: ($ $ 0 1"_) 'abcdef'
<syntaxhighlight lang="j"> /:/: ($ $ 0 1"_) 'abcdef'
0 3 1 4 2 5</lang>
0 3 1 4 2 5</syntaxhighlight>


And, that means it can also sort the original sequence into that order:
And, that means it can also sort the original sequence into that order:


<lang J> shuf 'abcdef'
<syntaxhighlight lang="j"> shuf 'abcdef'
adbecf
adbecf
shuf 'abcdefgh'
shuf 'abcdefgh'
aebfcgdh</lang>
aebfcgdh</syntaxhighlight>


And this will work for sequences of arbitrary length.
And this will work for sequences of arbitrary length.
Line 1,290: Line 1,290:
Meanwhile, the cycle length routine could look like this:
Meanwhile, the cycle length routine could look like this:


<lang J> shuflen=: [: *./ #@>@C.@shuf@i.</lang>
<syntaxhighlight lang="j"> shuflen=: [: *./ #@>@C.@shuf@i.</syntaxhighlight>


Here, we first generate a list of integers of the required length in their natural order. We then reorder them using our <code>shuf</code> function, find the [[j:Vocabulary/ccapdot|cycles]] which result, find the lengths of each of these cycles then find the least common multiple of those lengths.
Here, we first generate a list of integers of the required length in their natural order. We then reorder them using our <code>shuf</code> function, find the [[j:Vocabulary/ccapdot|cycles]] which result, find the lengths of each of these cycles then find the least common multiple of those lengths.
Line 1,296: Line 1,296:
So here is the task example (with most of the middle trimmed out to avoid crashing the rosettacode wiki implementation):
So here is the task example (with most of the middle trimmed out to avoid crashing the rosettacode wiki implementation):


<lang J> shuflen"0 }.2*i.5000
<syntaxhighlight lang="j"> shuflen"0 }.2*i.5000
1 2 4 3 6 10 12 4 8 18 6 11 20 18 28 5 10 12 36 12 20 14 12 23 21 8 52 20 18 ... 4278 816 222 1332 384</lang>
1 2 4 3 6 10 12 4 8 18 6 11 20 18 28 5 10 12 36 12 20 14 12 23 21 8 52 20 18 ... 4278 816 222 1332 384</syntaxhighlight>


Task example:
Task example:


<lang J> ('deck size';'required shuffles'),(; shuflen)&> 8 24 52 100 1020 1024 10000
<syntaxhighlight lang="j"> ('deck size';'required shuffles'),(; shuflen)&> 8 24 52 100 1020 1024 10000
┌─────────┬─────────────────┐
┌─────────┬─────────────────┐
│deck size│required shuffles│
│deck size│required shuffles│
Line 1,318: Line 1,318:
├─────────┼─────────────────┤
├─────────┼─────────────────┤
│10000 │300 │
│10000 │300 │
└─────────┴─────────────────┘</lang>
└─────────┴─────────────────┘</syntaxhighlight>


Note that the implementation of <code>shuf</code> defines a behavior for odd length "decks". Experimentation shows that cycle length for an odd length deck is often the same as the cycle length for an even length deck which is one "card" longer.
Note that the implementation of <code>shuf</code> defines a behavior for odd length "decks". Experimentation shows that cycle length for an odd length deck is often the same as the cycle length for an even length deck which is one "card" longer.
Line 1,324: Line 1,324:
=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|8}}
{{works with|Java|8}}
<lang java>import java.util.Arrays;
<syntaxhighlight lang="java">import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.IntStream;


Line 1,356: Line 1,356:
}
}
}
}
}</lang>
}</syntaxhighlight>


<pre> 8 : 3
<pre> 8 : 3
Line 1,368: Line 1,368:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES6===
===ES6===
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,489: Line 1,489:
.map(row => row.join(''))
.map(row => row.join(''))
.join('\n');
.join('\n');
})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,505: Line 1,505:


A small point of interest in the following is the `recurrence` function as it is generic.
A small point of interest in the following is the `recurrence` function as it is generic.
<lang jq>def perfect_shuffle:
<syntaxhighlight lang="jq">def perfect_shuffle:
. as $a
. as $a
| if (length % 2) == 1 then "cannot perform perfect shuffle on odd-length array" | error
| if (length % 2) == 1 then "cannot perform perfect shuffle on odd-length array" | error
Line 1,528: Line 1,528:


(8, 24, 52, 100, 1020, 1024, 10000, 100000)
(8, 24, 52, 100, 1020, 1024, 10000, 100000)
| [., count_perfect_shuffles]</lang>
| [., count_perfect_shuffles]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,543: Line 1,543:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>using Printf
<syntaxhighlight lang="julia">using Printf


function perfect_shuffle(a::Array)::Array
function perfect_shuffle(a::Array)::Array
Line 1,570: Line 1,570:
count = count_perfect_shuffles(i)
count = count_perfect_shuffles(i)
@printf("%7i%7i\n", i, count)
@printf("%7i%7i\n", i, count)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,584: Line 1,584:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun areSame(a: IntArray, b: IntArray): Boolean {
fun areSame(a: IntArray, b: IntArray): Boolean {
Line 1,624: Line 1,624:
println("${"%-9d".format(size)} $count")
println("${"%-9d".format(size)} $count")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,640: Line 1,640:


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>-- Perform weave shuffle
<syntaxhighlight lang="lua">-- Perform weave shuffle
function shuffle (cards)
function shuffle (cards)
local pile1, pile2 = {}, {}
local pile1, pile2 = {}, {}
Line 1,675: Line 1,675:
local testCases = {8, 24, 52, 100, 1020, 1024, 10000}
local testCases = {8, 24, 52, 100, 1020, 1024, 10000}
print("Input", "Output")
print("Input", "Output")
for _, case in pairs(testCases) do print(case, countShuffles(case)) end</lang>
for _, case in pairs(testCases) do print(case, countShuffles(case)) end</syntaxhighlight>
{{out}}
{{out}}
<pre>Input Output
<pre>Input Output
Line 1,687: Line 1,687:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>shuffle[deck_] := Apply[Riffle, TakeDrop[deck, Length[deck]/2]];
<syntaxhighlight lang="mathematica">shuffle[deck_] := Apply[Riffle, TakeDrop[deck, Length[deck]/2]];
shuffleCount[n_] := Block[{count=0}, NestWhile[shuffle, shuffle[Range[n]], (count++; OrderedQ[#] )&];count];
shuffleCount[n_] := Block[{count=0}, NestWhile[shuffle, shuffle[Range[n]], (count++; OrderedQ[#] )&];count];
Map[shuffleCount, {8, 24, 52, 100, 1020, 1024, 10000}]</lang>
Map[shuffleCount, {8, 24, 52, 100, 1020, 1024, 10000}]</syntaxhighlight>
{{out}}
{{out}}
<pre>{3, 11, 8, 30, 1018, 10, 300}</pre>
<pre>{3, 11, 8, 30, 1018, 10, 300}</pre>
Line 1,695: Line 1,695:
=={{header|MATLAB}}==
=={{header|MATLAB}}==
PerfectShuffle.m:
PerfectShuffle.m:
<lang matlab>function [New]=PerfectShuffle(Nitems, Nturns)
<syntaxhighlight lang="matlab">function [New]=PerfectShuffle(Nitems, Nturns)
if mod(Nitems,2)==0 %only if even number
if mod(Nitems,2)==0 %only if even number
X=1:Nitems; %define deck
X=1:Nitems; %define deck
Line 1,703: Line 1,703:
end
end
New=X; %result of multiple shufflings
New=X; %result of multiple shufflings
end</lang>
end</syntaxhighlight>


Main:
Main:
<lang matlab>Result=[]; %vector to store results
<syntaxhighlight lang="matlab">Result=[]; %vector to store results
Q=[8, 24, 52, 100, 1020, 1024, 10000]; %queries
Q=[8, 24, 52, 100, 1020, 1024, 10000]; %queries
for n=Q %for each query
for n=Q %for each query
Line 1,718: Line 1,718:
Result=[Result;T]; %collect results
Result=[Result;T]; %collect results
end
end
disp([Q', Result])</lang>
disp([Q', Result])</syntaxhighlight>
{{out}}
{{out}}
<pre> 8 3
<pre> 8 3
Line 1,730: Line 1,730:
=={{header|Modula-2}}==
=={{header|Modula-2}}==
{{trans|C}}
{{trans|C}}
<lang modula2>MODULE PerfectShuffle;
<syntaxhighlight lang="modula2">MODULE PerfectShuffle;
FROM FormatString IMPORT FormatString;
FROM FormatString IMPORT FormatString;
FROM Storage IMPORT ALLOCATE,DEALLOCATE;
FROM Storage IMPORT ALLOCATE,DEALLOCATE;
Line 1,820: Line 1,820:


ReadChar
ReadChar
END PerfectShuffle.</lang>
END PerfectShuffle.</syntaxhighlight>
{{out}}
{{out}}
<pre>8: 3
<pre>8: 3
Line 1,831: Line 1,831:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import sequtils, strutils
<syntaxhighlight lang="nim">import sequtils, strutils


proc newValList(size: Positive): seq[int] =
proc newValList(size: Positive): seq[int] =
Line 1,856: Line 1,856:
if valList == initList:
if valList == initList:
break
break
echo ($size).align(5), ": ", ($count).align(4)</lang>
echo ($size).align(5), ": ", ($count).align(4)</syntaxhighlight>




Line 1,870: Line 1,870:
=={{header|Oforth}}==
=={{header|Oforth}}==


<lang oforth>: shuffle(l) l size 2 / dup l left swap l right zip expand ;
<syntaxhighlight lang="oforth">: shuffle(l) l size 2 / dup l left swap l right zip expand ;
: nbShuffles(l) 1 l while( shuffle dup l <> ) [ 1 under+ ] drop ;</lang>
: nbShuffles(l) 1 l while( shuffle dup l <> ) [ 1 under+ ] drop ;</syntaxhighlight>


{{out}}
{{out}}
Line 1,882: Line 1,882:
{{improve|PARI/GP|The task description was updated; please update this solution accordingly and then remove this template.}}
{{improve|PARI/GP|The task description was updated; please update this solution accordingly and then remove this template.}}


<lang parigp>magic(v)=vector(#v,i,v[if(i%2,1,#v/2)+i\2]);
<syntaxhighlight lang="parigp">magic(v)=vector(#v,i,v[if(i%2,1,#v/2)+i\2]);
shuffles_slow(n)=my(v=[1..n],o=v,s=1);while((v=magic(v))!=o,s++);s;
shuffles_slow(n)=my(v=[1..n],o=v,s=1);while((v=magic(v))!=o,s++);s;
shuffles(n)=znorder(Mod(2,n-1));
shuffles(n)=znorder(Mod(2,n-1));
vector(5000,n,shuffles_slow(2*n))</lang>
vector(5000,n,shuffles_slow(2*n))</syntaxhighlight>
{{out}}
{{out}}
<pre>%1 = [1, 2, 4, 3, 6, 10, 12, 4, 8, 18, 6, 11, 20, 18, 28, 5, 10, 12, 36, 12,
<pre>%1 = [1, 2, 4, 3, 6, 10, 12, 4, 8, 18, 6, 11, 20, 18, 28, 5, 10, 12, 36, 12,
Line 1,917: Line 1,917:
=={{header|Perl}}==
=={{header|Perl}}==


<lang perl>use v5.36;
<syntaxhighlight lang="perl">use v5.36;
use List::Util 'all';
use List::Util 'all';


Line 1,931: Line 1,931:
until all { $shuffled[$_] == $deck[$_] } 0..$#shuffled;
until all { $shuffled[$_] == $deck[$_] } 0..$#shuffled;
printf "%5d cards: %4d\n", $size, $n;
printf "%5d cards: %4d\n", $size, $n;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,945: Line 1,945:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<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: #008080;">function</span> <span style="color: #000000;">perfect_shuffle</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">deck</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">perfect_shuffle</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">deck</span><span style="color: #0000FF;">)</span>
Line 1,968: Line 1,968:
<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;">"%5d cards: %4d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">testsizes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">count</span><span style="color: #0000FF;">})</span>
<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;">"%5d cards: %4d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">testsizes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">count</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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,987: Line 1,987:
The method used here supports both shuffle types. The task states an '''out''' shuffling.
The method used here supports both shuffle types. The task states an '''out''' shuffling.
===Out shuffle===
===Out shuffle===
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
member(N,[8,24,52,100,1020,1024,10_000]),
member(N,[8,24,52,100,1020,1024,10_000]),
println(n=N),
println(n=N),
Line 2,069: Line 2,069:
R1 := R1 ++ [L1[L1Len]]
R1 := R1 ++ [L1[L1Len]]
end,
end,
R = R1.</lang>
R = R1.</syntaxhighlight>


{{out}}
{{out}}
Line 2,127: Line 2,127:
===In shuffle===
===In shuffle===
Here's an example of an '''in''' shuffle. It takes 6 shuffles to get an 8 card deck back to its original order (compare with 3 for an out shuffle).
Here's an example of an '''in''' shuffle. It takes 6 shuffles to get an 8 card deck back to its original order (compare with 3 for an out shuffle).
<lang Picat>main =>
<syntaxhighlight lang="picat">main =>
N = 8,
N = 8,
println(1..N),
println(1..N),
Line 2,133: Line 2,133:
Count = show_all_shuffles(N,InOut,true),
Count = show_all_shuffles(N,InOut,true),
println(count=Count),
println(count=Count),
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 2,147: Line 2,147:
===Uneven decks===
===Uneven decks===
The method supports decks of uneven lengths, here size 11 (using an out shuffle).
The method supports decks of uneven lengths, here size 11 (using an out shuffle).
<lang Picat>main =>
<syntaxhighlight lang="picat">main =>
N = 11,
N = 11,
println(1..N),
println(1..N),
Line 2,153: Line 2,153:
Count = show_all_shuffles(N,InOut,true),
Count = show_all_shuffles(N,InOut,true),
println(count=Count),
println(count=Count),
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 2,171: Line 2,171:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de perfectShuffle (Lst)
<syntaxhighlight lang="picolisp">(de perfectShuffle (Lst)
(mapcan '((B A) (list A B))
(mapcan '((B A) (list A B))
(cdr (nth Lst (/ (length Lst) 2)))
(cdr (nth Lst (/ (length Lst) 2)))
Line 2,180: Line 2,180:
(until (= Lst (setq L (perfectShuffle L)))
(until (= Lst (setq L (perfectShuffle L)))
(inc 'Cnt) )
(inc 'Cnt) )
(tab (5 6) N Cnt) ) )</lang>
(tab (5 6) N Cnt) ) )</syntaxhighlight>
Output:
Output:
<pre> 8 3
<pre> 8 3
Line 2,192: Line 2,192:
=={{header|Python}}==
=={{header|Python}}==


<lang python>
<syntaxhighlight lang="python">
import doctest
import doctest
import random
import random
Line 2,238: Line 2,238:
main()
main()


</syntaxhighlight>
</lang>
More functional version of the same code:
More functional version of the same code:
<lang python>
<syntaxhighlight lang="python">
"""
"""
Brute force solution for the Perfect Shuffle problem.
Brute force solution for the Perfect Shuffle problem.
Line 2,307: Line 2,307:
if __name__ == "__main__":
if __name__ == "__main__":
main()
main()
</lang>
</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Deck length | Shuffles
<pre>Deck length | Shuffles
Line 2,318: Line 2,318:
10000 | 300</pre>
10000 | 300</pre>
Reversed shuffle or just calculate how many shuffles are needed:
Reversed shuffle or just calculate how many shuffles are needed:
<lang python>def mul_ord2(n):
<syntaxhighlight lang="python">def mul_ord2(n):
# directly calculate how many shuffles are needed to restore
# directly calculate how many shuffles are needed to restore
# initial order: 2^o mod(n-1) == 1
# initial order: 2^o mod(n-1) == 1
Line 2,342: Line 2,342:
for n in range(2, 10000, 2):
for n in range(2, 10000, 2):
#print(n, mul_ord2(n))
#print(n, mul_ord2(n))
print(n, shuffles(n))</lang>
print(n, shuffles(n))</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ [] swap
<syntaxhighlight lang="quackery"> [ [] swap
times [ i^ join ] ] is deck ( n --> [ )
times [ i^ join ] ] is deck ( n --> [ )


Line 2,365: Line 2,365:
dup echo say " cards needs "
dup echo say " cards needs "
shuffles echo say " shuffles."
shuffles echo say " shuffles."
cr ]</lang>
cr ]</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,380: Line 2,380:
=={{header|R}}==
=={{header|R}}==
===Matrix solution===
===Matrix solution===
<lang rsplus>wave.shuffle <- function(n) {
<syntaxhighlight lang="rsplus">wave.shuffle <- function(n) {
deck <- 1:n ## create the original deck
deck <- 1:n ## create the original deck
new.deck <- c(matrix(data = deck, ncol = 2, byrow = TRUE)) ## shuffle the deck once
new.deck <- c(matrix(data = deck, ncol = 2, byrow = TRUE)) ## shuffle the deck once
Line 2,395: Line 2,395:
test <- sapply(test.values, wave.shuffle) ## apply the wave.shuffle function on each element
test <- sapply(test.values, wave.shuffle) ## apply the wave.shuffle function on each element
names(test) <- test.values ## name the result
names(test) <- test.values ## name the result
test ## print the result out</lang>
test ## print the result out</syntaxhighlight>
{{out}}
{{out}}
<pre>> test
<pre>> test
Line 2,402: Line 2,402:
===Sequence solution===
===Sequence solution===
The previous solution exploits R's matrix construction; This solution exploits its array indexing.
The previous solution exploits R's matrix construction; This solution exploits its array indexing.
<lang rsplus>#A strict reading of the task description says that we need a function that does exactly one shuffle.
<syntaxhighlight lang="rsplus">#A strict reading of the task description says that we need a function that does exactly one shuffle.
pShuffle <- function(deck)
pShuffle <- function(deck)
{
{
Line 2,427: Line 2,427:


#Tests - All done in one line.
#Tests - All done in one line.
mapply(function(x, y) task2(1:x) == y, c(8, 24, 52, 100, 1020, 1024, 10000), c(3, 11, 8, 30, 1018, 10, 300))</lang>
mapply(function(x, y) task2(1:x) == y, c(8, 24, 52, 100, 1020, 1024, 10000), c(3, 11, 8, 30, 1018, 10, 300))</syntaxhighlight>
{{out}}
{{out}}
<pre>> mapply(function(x, y) task2(1:x) == y, c(8, 24, 52, 100, 1020, 1024, 10000), c(3, 11, 8, 30, 1018, 10, 300))
<pre>> mapply(function(x, y) task2(1:x) == y, c(8, 24, 52, 100, 1020, 1024, 10000), c(3, 11, 8, 30, 1018, 10, 300))
Line 2,440: Line 2,440:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket/base
<syntaxhighlight lang="racket">#lang racket/base
(require racket/list)
(require racket/list)


Line 2,466: Line 2,466:
(for-each test-perfect-shuffles-needed
(for-each test-perfect-shuffles-needed
'(8 24 52 100 1020 1024 10000)
'(8 24 52 100 1020 1024 10000)
'(3 11 8 30 1018 10 300)))</lang>
'(3 11 8 30 1018 10 300)))</syntaxhighlight>


{{out}}
{{out}}
Line 2,479: Line 2,479:
=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>for 8, 24, 52, 100, 1020, 1024, 10000 -> $size {
<syntaxhighlight lang="raku" line>for 8, 24, 52, 100, 1020, 1024, 10000 -> $size {
my ($n, @deck) = 1, |^$size;
my ($n, @deck) = 1, |^$size;
$n++ until [<] @deck = flat [Z] @deck.rotor: @deck/2;
$n++ until [<] @deck = flat [Z] @deck.rotor: @deck/2;
printf "%5d cards: %4d\n", $size, $n;
printf "%5d cards: %4d\n", $size, $n;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,498: Line 2,498:
=={{header|REXX}}==
=={{header|REXX}}==
===unoptimized===
===unoptimized===
<lang rexx>/*REXX program performs a "perfect shuffle" for a number of even numbered decks. */
<syntaxhighlight lang="rexx">/*REXX program performs a "perfect shuffle" for a number of even numbered decks. */
parse arg X /*optional list of test cases from C.L.*/
parse arg X /*optional list of test cases from C.L.*/
if X='' then X=8 24 52 100 1020 1024 10000 /*Not specified? Then use the default.*/
if X='' then X=8 24 52 100 1020 1024 10000 /*Not specified? Then use the default.*/
Line 2,522: Line 2,522:


do r=1 for y; @.r=!.r; end /*re─assign to the original card deck. */
do r=1 for y; @.r=!.r; end /*re─assign to the original card deck. */
return</lang>
return</syntaxhighlight>
'''output''' &nbsp; (abbreviated) &nbsp; when using the default input:
'''output''' &nbsp; (abbreviated) &nbsp; when using the default input:
<pre>
<pre>
Line 2,536: Line 2,536:
===optimized===
===optimized===
This REXX version takes advantage that the 1<sup>st</sup> and last cards of the deck don't change.
This REXX version takes advantage that the 1<sup>st</sup> and last cards of the deck don't change.
<lang rexx>/*REXX program does a "perfect shuffle" for a number of even numbered decks. */
<syntaxhighlight lang="rexx">/*REXX program does a "perfect shuffle" for a number of even numbered decks. */
parse arg X /*optional list of test cases from C.L.*/
parse arg X /*optional list of test cases from C.L.*/
if X='' then X=8 24 52 100 1020 1024 10000 /*Not specified? Use default.*/
if X='' then X=8 24 52 100 1020 1024 10000 /*Not specified? Use default.*/
Line 2,556: Line 2,556:
do R=2 by 2 for h-1; h=h+1; !.R=@.h; end /* " right " " " */
do R=2 by 2 for h-1; h=h+1; !.R=@.h; end /* " right " " " */
do a=2 for y-2; @.a=!.a; end /*re─assign──►original deck*/
do a=2 for y-2; @.a=!.a; end /*re─assign──►original deck*/
return</lang>
return</syntaxhighlight>
'''output''' &nbsp; is the same as the 1<sup>st</sup> version.
'''output''' &nbsp; is the same as the 1<sup>st</sup> version.
<br><br>
<br><br>
Line 2,562: Line 2,562:
=={{header|Ruby}}==
=={{header|Ruby}}==


<lang ruby>def perfect_shuffle(deck_size = 52)
<syntaxhighlight lang="ruby">def perfect_shuffle(deck_size = 52)
deck = (1..deck_size).to_a
deck = (1..deck_size).to_a
original = deck.dup
original = deck.dup
Line 2,573: Line 2,573:


[8, 24, 52, 100, 1020, 1024, 10000].each {|i| puts "Perfect shuffles required for deck size #{i}: #{perfect_shuffle(i)}"}
[8, 24, 52, 100, 1020, 1024, 10000].each {|i| puts "Perfect shuffles required for deck size #{i}: #{perfect_shuffle(i)}"}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,587: Line 2,587:


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>extern crate itertools;
<syntaxhighlight lang="rust">extern crate itertools;


fn shuffle<T>(mut deck: Vec<T>) -> Vec<T> {
fn shuffle<T>(mut deck: Vec<T>) -> Vec<T> {
Line 2,609: Line 2,609:
println!("{: >5}: {: >4}", size, iterations);
println!("{: >5}: {: >4}", size, iterations);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 8: 3
<pre> 8: 3
Line 2,624: Line 2,624:
{{trans|Java}}
{{trans|Java}}
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/Ux9RKDx/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/eWeiDIBbQMGpNIQAmvXfLg Scastie (remote JVM)].
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/Ux9RKDx/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/eWeiDIBbQMGpNIQAmvXfLg Scastie (remote JVM)].
<lang Scala>object PerfectShuffle extends App {
<syntaxhighlight lang="scala">object PerfectShuffle extends App {
private def sizes = Seq(8, 24, 52, 100, 1020, 1024, 10000)
private def sizes = Seq(8, 24, 52, 100, 1020, 1024, 10000)


Line 2,647: Line 2,647:
for (size <- sizes) println(f"$size%5d : ${perfectShuffle(size)}%5d")
for (size <- sizes) println(f"$size%5d : ${perfectShuffle(size)}%5d")


}</lang>
}</syntaxhighlight>


=={{header|Scilab}}==
=={{header|Scilab}}==
{{trans|MATLAB}}
{{trans|MATLAB}}
<lang>function New=PerfectShuffle(Nitems,Nturns)
<syntaxhighlight lang="text">function New=PerfectShuffle(Nitems,Nturns)
if modulo(Nitems,2)==0 then
if modulo(Nitems,2)==0 then
X=1:Nitems;
X=1:Nitems;
Line 2,678: Line 2,678:
Result=[Result;T];
Result=[Result;T];
end
end
disp([Q', Result])</lang>
disp([Q', Result])</syntaxhighlight>


{{out}}
{{out}}
Line 2,692: Line 2,692:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>func perfect_shuffle(deck) {
<syntaxhighlight lang="ruby">func perfect_shuffle(deck) {
deck/2 -> zip.flat
deck/2 -> zip.flat
}
}
Line 2,705: Line 2,705:


printf("%5d cards: %4d\n", size, n)
printf("%5d cards: %4d\n", size, n)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,720: Line 2,720:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>func perfectShuffle<T>(_ arr: [T]) -> [T]? {
<syntaxhighlight lang="swift">func perfectShuffle<T>(_ arr: [T]) -> [T]? {
guard arr.count & 1 == 0 else {
guard arr.count & 1 == 0 else {
return nil
return nil
Line 2,756: Line 2,756:


print("Deck of \(shuffled.count) took \(shuffles) shuffles to get back to original order")
print("Deck of \(shuffled.count) took \(shuffles) shuffles to get back to original order")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,772: Line 2,772:
Using <tt>tcltest</tt> to include an executable test case ..
Using <tt>tcltest</tt> to include an executable test case ..


<lang Tcl>namespace eval shuffle {
<syntaxhighlight lang="tcl">namespace eval shuffle {


proc perfect {deck} {
proc perfect {deck} {
Line 2,817: Line 2,817:
shuffle::cycle_length perfect [range $size]
shuffle::cycle_length perfect [range $size]
}
}
} -result {3 11 8 30 1018 10 300}</lang>
} -result {3 11 8 30 1018 10 300}</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Line 2,823: Line 2,823:
{{works with|Korn Shell}}
{{works with|Korn Shell}}
{{works with|Zsh}}
{{works with|Zsh}}
<lang bash>function faro {
<syntaxhighlight lang="bash">function faro {
if (( $# % 2 )); then
if (( $# % 2 )); then
printf >&2 'Can only shuffle an even number of elements!\n'
printf >&2 'Can only shuffle an even number of elements!\n'
Line 2,856: Line 2,856:
printf '%d\t%d\t%d\n' "$size" "$count" "$taken"
printf '%d\t%d\t%d\n' "$size" "$count" "$taken"
done
done
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 2,870: Line 2,870:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit


Sub Main()
Sub Main()
Line 2,931: Line 2,931:
Private Function IsEven(Number As Long) As Boolean
Private Function IsEven(Number As Long) As Boolean
IsEven = (Number Mod 2 = 0)
IsEven = (Number Mod 2 = 0)
End Function</lang>
End Function</syntaxhighlight>
{{out}}
{{out}}
<pre> For 8 cards => 3 shuffles needed.
<pre> For 8 cards => 3 shuffles needed.
Line 2,944: Line 2,944:
{{trans|Kotlin}}
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt


var areSame = Fn.new { |a, b|
var areSame = Fn.new { |a, b|
Line 2,985: Line 2,985:
var count = countShuffles.call(a)
var count = countShuffles.call(a)
Fmt.print("$-9d $d", size, count)
Fmt.print("$-9d $d", size, count)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,001: Line 3,001:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>int Deck(10000), Deck0(10000);
<syntaxhighlight lang="xpl0">int Deck(10000), Deck0(10000);
int Cases, Count, Test, Size, I;
int Cases, Count, Test, Size, I;


Line 3,027: Line 3,027:
IntOut(0, Size); ChOut(0, 9\tab\); IntOut(0, Count); CrLf(0);
IntOut(0, Size); ChOut(0, 9\tab\); IntOut(0, Count); CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 3,041: Line 3,041:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn perfectShuffle(numCards){
<syntaxhighlight lang="zkl">fcn perfectShuffle(numCards){
deck,shuffle,n,N:=numCards.pump(List),deck,0,numCards/2;
deck,shuffle,n,N:=numCards.pump(List),deck,0,numCards/2;
do{ shuffle=shuffle[0,N].zip(shuffle[N,*]).flatten(); n+=1 }
do{ shuffle=shuffle[0,N].zip(shuffle[N,*]).flatten(); n+=1 }
Line 3,049: Line 3,049:
foreach n in (T(8,24,52,100,1020,1024,10000)){
foreach n in (T(8,24,52,100,1020,1024,10000)){
println("%5d : %d".fmt(n,perfectShuffle(n)));
println("%5d : %d".fmt(n,perfectShuffle(n)));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>