Shuffling Stitches Across a Cloth Cover
Before cutting the cover boards, I laid out six paper squares on the cloth: three marked with crosses and three with diamonds. I wanted an irregular arrangement, but I also wanted to use every square exactly once. That is a job for a shuffle.
The Fisher–Yates shuffle works backwards through a collection. At each position, it chooses one of the items at or before that position and swaps the two. The item just placed is finished; the next choice comes from the smaller unfinished section.
var motifs = ["cross", "cross", "cross", "diamond", "diamond", "diamond"]
for i in stride(from: motifs.count - 1, through: 1, by: -1) {
let j = Int.random(in: 0...i)
motifs.swapAt(i, j)
}
print(motifs.joined(separator: ", "))
Perl makes the same backwards journey, with rand supplying a number below its argument. Converting that number to an integer gives an index from zero through i.
use strict;
use warnings;
my @motifs = (('cross') x 3, ('diamond') x 3);
for (my $i = $#motifs; $i > 0; $i--) {
my $j = int(rand($i + 1));
@motifs[$i, $j] = @motifs[$j, $i];
}
print join(', ', @motifs), "\n";
One possible result is diamond, cross, cross, diamond, cross, diamond. The counts stay put even though the order changes. Choosing from the whole array at every step would be tempting, but it would not give all arrangements the same chance.
The in-place version became widely known through Robert Durstenfeld’s 1964 algorithm. It takes time proportional to the number of items and needs no second collection. The random choice can still produce a pattern I dislike, so I can shuffle again before committing the design to cloth. Once the stitches are in, thread tension and spacing will do more for the cover than another roll of the dice.