Topswops: Difference between revisions

m
m (syntax highlighting fixup automation)
m (→‎{{header|Wren}}: Minor tidy)
 
(2 intermediate revisions by 2 users not shown)
Line 480:
return 0;
}</syntaxhighlight>
 
 
=={{header|C#}}==
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
 
public class Topswops {
static readonly int maxBest = 32;
static int[] best;
 
private static void TrySwaps(int[] deck, int f, int d, int n) {
if (d > best[n])
best[n] = d;
 
for (int i = n - 1; i >= 0; i--) {
if (deck[i] == -1 || deck[i] == i)
break;
if (d + best[i] <= best[n])
return;
}
 
int[] deck2 = (int[])deck.Clone();
for (int i = 1; i < n; i++) {
int k = 1 << i;
if (deck2[i] == -1) {
if ((f & k) != 0)
continue;
} else if (deck2[i] != i)
continue;
 
deck2[0] = i;
for (int j = i - 1; j >= 0; j--)
deck2[i - j] = deck[j]; // Reverse copy.
TrySwaps(deck2, f | k, d + 1, n);
}
}
 
static int topswops(int n) {
if(n <= 0 || n >= maxBest) throw new ArgumentOutOfRangeException(nameof(n), "n must be greater than 0 and less than maxBest.");
best[n] = 0;
int[] deck0 = new int[n + 1];
for (int i = 1; i < n; i++)
deck0[i] = -1;
TrySwaps(deck0, 1, 0, n);
return best[n];
}
 
public static void Main(string[] args) {
best = new int[maxBest];
for (int i = 1; i < 11; i++)
Console.WriteLine(i + ": " + topswops(i));
}
}
</syntaxhighlight>
{{out}}
<pre>
1: 0
2: 1
3: 2
4: 4
5: 7
6: 10
7: 16
8: 22
9: 30
10: 38
 
</pre>
 
=={{header|C++}}==
Line 956 ⟶ 1,025:
end program
</syntaxhighlight>
 
=={{header|FreeBASIC}}==
{{trans|XPL0:_Faster_Version}}
<syntaxhighlight lang="vb">Dim Shared As Byte n, d, best(16)
 
Sub TrySwaps(A() As Byte, f As Byte, s As Byte)
Dim As Byte B(16), i, j, k
If d > best(n) Then best(n) = d
Do
If A(s) = -1 Or A(s) = s Then Exit Do
If d+best(s) <= best(n) Then Exit Sub
If s = 0 Then Exit Do
s -= 1
Loop
d += 1
For i = 0 To s
B(i) = A(i)
Next
k = 1
For i = 1 To s
k Shl= 1
If B(i) =- 1 AndAlso (f And k) = 0 Or B(i) = i Then
j = i
B(0) = j
While j
j -= 1
B(i-j) = A(j)
Wend
TrySwaps(B(), f Or k, s)
End If
Next
d -= 1
End Sub
 
Dim As Byte i, X(16)
For i = 0 To 16-1
X(i) = -1
best(i) = 0
Next i
X(0) = 0
 
For n = 1 To 13
d = 0
TrySwaps(X(), 1, n-1)
Print Using "##: ##"; n; best(n)
Next n
 
Sleep</syntaxhighlight>
 
{{out}}
<pre> 1: 0
2: 1
3: 2
4: 4
5: 7
6: 10
7: 16
8: 22
9: 30
10: 38
11: 51
12: 65
13: 80</pre>
 
=={{header|Go}}==
Line 2,364 ⟶ 2,498:
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt
 
var maxn = 10
9,486

edits