-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolver.cs
More file actions
207 lines (182 loc) · 8.02 KB
/
Copy pathSolver.cs
File metadata and controls
207 lines (182 loc) · 8.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
using System.Runtime.CompilerServices;
using System.Text;
namespace rummikool;
static class Solver {
private sealed class RefEq : IEqualityComparer<Tile> {
public static readonly RefEq Instance = new();
public bool Equals(Tile? x, Tile? y) => ReferenceEquals(x, y);
public int GetHashCode(Tile obj) => RuntimeHelpers.GetHashCode(obj);
}
private sealed record MeldCandidate(List<Tile> Tiles, Dictionary<Tile, int> AssignedValues);
static List<Tile> CanonicalizeMeld(List<Tile> meld) => [.. meld];
private static IEnumerable<List<T>> KComb<T>(IReadOnlyList<T> items, int k, int start = 0) {
if (k == 0) {
yield return new List<T>();
yield break;
}
for (int i = start; i <= items.Count - k; i++) {
foreach (var tail in KComb(items, k - 1, i + 1)) {
var res = new List<T>(k) { items[i] };
res.AddRange(tail);
yield return res;
}
}
}
static IEnumerable<MeldCandidate> GenerateMelds(List<Tile> tiles) {
List<Tile> jokers = [.. tiles.Where(t => t.IsJoker)];
List<Tile> normals = [.. tiles.Where(t => !t.IsJoker)];
// Groups
foreach (var sameValue in normals.GroupBy(t => t.Value)) {
List<Tile> byColor = [.. sameValue
.GroupBy(t => t.Color)
.Select(g => g.First())];
for (int size = 3; size <= 4; size++) {
if (byColor.Count >= size) {
foreach (var subset in KComb(byColor, size)) {
Dictionary<Tile, int> assign = new(RefEq.Instance);
foreach (var t in subset)
assign[t] = t.Value;
yield return new MeldCandidate(CanonicalizeMeld(subset), assign);
}
} else {
int need = size - byColor.Count;
if (byColor.Count == 0)
continue;
if (need <= jokers.Count) {
List<Tile> meld = new(size);
Dictionary<Tile, int> assign = new(RefEq.Instance);
foreach (var t in byColor) {
meld.Add(t);
assign[t] = t.Value;
}
for (int k = 0; k < need; k++) {
var j = jokers[k];
meld.Add(j);
assign[j] = sameValue.Key;
}
yield return new MeldCandidate(CanonicalizeMeld(meld), assign);
}
}
}
}
// Runs
foreach (var sameColor in normals.GroupBy(t => t.Color)) {
List<Tile> vals = [.. sameColor
.GroupBy(t => t.Value)
.Select(g => g.First())
.OrderBy(t => t.Value)];
if (vals.Count == 0) continue;
var dict = vals.ToDictionary(t => t.Value);
for (int i = 0; i < vals.Count; i++) {
int expected = vals[i].Value;
int idx = i;
int jokersLeft = jokers.Count;
List<Tile> runTiles = [];
Dictionary<Tile, int> assignVals = new(RefEq.Instance);
bool hasReal = false;
while (expected <= 13) {
if (idx < vals.Count && vals[idx].Value == expected) {
var t = vals[idx++];
runTiles.Add(t);
assignVals[t] = t.Value;
hasReal = true;
expected++;
} else if (jokersLeft > 0) {
var j = jokers[^jokersLeft];
jokersLeft--;
runTiles.Add(j);
assignVals[j] = expected;
expected++;
} else
break;
if (runTiles.Count >= 3 && hasReal) {
yield return new MeldCandidate(
CanonicalizeMeld([.. runTiles]),
new Dictionary<Tile, int>(assignVals, RefEq.Instance));
}
}
}
}
}
public static bool Solve(
List<Tile> hand,
List<List<Tile>> board,
bool initiation,
out List<List<Tile>> newBoard,
out List<Tile> playedFromHand)
{
HashSet<Tile> boardTiles = new(board.SelectMany(b => b), RefEq.Instance);
HashSet<Tile> handTiles = new(hand, RefEq.Instance);
List<List<Tile>> best = [];
int bestHandUse = -1;
int bestHandValueSum = -1;
Dictionary<string, (int used, int val)> memo = [];
List<Tile> tilesToConsider = initiation
? [.. hand]
: [.. hand, .. board.SelectMany(b => b)];
string BuildKey(List<Tile> remaining) {
Span<int> counts = stackalloc int[5 * 14];
foreach (var t in remaining) {
int valIdx = t.IsJoker ? 0 : t.Value;
counts[(int)t.Color * 14 + valIdx]++;
}
StringBuilder sb = new(1 + counts.Length * 3);
sb.Append(initiation ? 'I' : 'P');
for (int i = 0; i < counts.Length; i++) {
sb.Append('#').Append(counts[i]);
}
return sb.ToString();
}
void Backtrack(List<Tile> remaining, List<List<Tile>> current, int handUsed, int handValueSum) {
string key = BuildKey(remaining);
if (memo.TryGetValue(key, out var seen)) {
if (handUsed <= seen.used && handValueSum <= seen.val)
return;
memo[key] = (Math.Max(seen.used, handUsed), Math.Max(seen.val, handValueSum));
} else
memo[key] = (handUsed, handValueSum);
bool allBoardTilesUsedExactlyOnce = !remaining.Any(boardTiles.Contains);
if (allBoardTilesUsedExactlyOnce) {
bool initiationOk = !initiation || handValueSum >= 30;
if (initiationOk && (handUsed > bestHandUse
|| (handUsed == bestHandUse && handValueSum > bestHandValueSum))) {
bestHandUse = handUsed;
bestHandValueSum = handValueSum;
best = [.. current.Select(m => new List<Tile>(m))];
}
}
foreach (var cand in GenerateMelds(remaining)) {
List<Tile> nextRem = [.. remaining];
foreach (var t in cand.Tiles)
nextRem.Remove(t);
int usedFromHand = cand.Tiles.Count(handTiles.Contains);
int valueFromHand = cand.Tiles
.Where(handTiles.Contains)
.Sum(t => cand.AssignedValues.TryGetValue(t, out var v) ? v : t.Value);
Backtrack(nextRem, [.. current, cand.Tiles], handUsed + usedFromHand, handValueSum + valueFromHand);
}
}
Backtrack(tilesToConsider, [], 0, 0);
// No play
if (bestHandUse <= 0) {
newBoard = board;
playedFromHand = [];
return false;
}
// Build result:
// - During initiation: best contains only hand tiles; board unchanged + add best melds
// - After initiation: best covers ALL board tiles exactly once; replace board with best
if (initiation) {
int sum = best.SelectMany(m => m)
.Where(handTiles.Contains)
.Sum(t => t.IsJoker ? // use assigned value if any
0 : t.Value);
newBoard = [];
foreach (var g in board) newBoard.Add([.. g]);
foreach (var meld in best) newBoard.Add(meld);
} else
newBoard = [.. best.Select(m => new List<Tile>(m))];
playedFromHand = [.. best.SelectMany(m => m).Where(handTiles.Contains)];
return true;
}
}