-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBacktracker.cs
More file actions
363 lines (316 loc) · 11.6 KB
/
Backtracker.cs
File metadata and controls
363 lines (316 loc) · 11.6 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
using System;
using System.Collections.Generic;
using System.Linq;
namespace PuzzleSolver
{
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// This is the heart of PuzzleSolver. It tries using all the rules until none of them apply any
/// more and then invokes standard backtracking. Each time it makes a guess, it tries the rules
/// again to determine the implications. If the current board turns out to be impossible to
/// solve, it backtracks.
/// </summary>
///
/// <remarks> Darrellp, 2/14/2011. </remarks>
///
/// ### <typeparam name="TPs"> The type of partial solution we apply to. </typeparam>
////////////////////////////////////////////////////////////////////////////////////////////////////
public class Backtracker<TPs> where TPs : IPartialSolution
{
// ReSharper disable once StaticFieldInGenericType
private static bool _fFirstTime;
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Return the first solution we can find if any and gather backtracking reasons. </summary>
///
/// <remarks> Darrellp, 2/14/2011. </remarks>
///
/// <param name="ps"> Partial solution so far. </param>
/// <param name="es"> Expert System to apply. </param>
/// <param name="psFinal"> [out] Final solution. </param>
/// <param name="bti"> [out] Reasons for inferences. </param>
///
///<returns> True if a solution was found, else false. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public static bool FSolve(TPs ps, ExpertSystem<TPs> es, out TPs psFinal, out BacktrackInfo bti)
{
// Set up
var lstpsSolutions = new List<TPs>();
bti = es.IsKeepingReasons ? new BacktrackInfo(BacktrackReason.InitialEntry, null) : null;
psFinal = default(TPs);
_fFirstTime = true;
// Use SearchForMultipleSolutions to search for precisely one solution
FSearchForMultipleSolutions(ps, es, bti, lstpsSolutions, 1);
// Did we find a solution?
if (lstpsSolutions.Count == 1)
{
// Put it into our out parameter and return true
psFinal = lstpsSolutions[0];
return true;
}
// No solution found - return false
return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Return the first solution we can find if any - don't gather backtracking reasons. </summary>
///
/// <remarks> Darrellp, 2/14/2011. </remarks>
///
/// <param name="ps"> Partial solution so far. </param>
/// <param name="es"> Expert System to apply. </param>
/// <param name="psFinal"> [out] Final solution. </param>
///
/// <returns> True if a solution was found, else false. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public static bool FSolve(TPs ps, ExpertSystem<TPs> es, out TPs psFinal)
{
BacktrackInfo bti;
return FSolve(ps, es, out psFinal, out bti);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> See if there is exactly one unique solution. </summary>
///
/// <remarks> Darrellp, 2/14/2011. </remarks>
///
/// <param name="ps"> Partial solution so far. </param>
/// <param name="es"> Expert System to apply. </param>
///
/// <returns> true if exactly one solution exists, false otherwise. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
///
public static bool FUnique(TPs ps, ExpertSystem<TPs> es)
{
var lstpsSolutions = new List<TPs>();
var bti = es.IsKeepingReasons ? new BacktrackInfo(BacktrackReason.InitialEntry, null) : null;
FSearchForMultipleSolutions((TPs)ps.Clone(), es, bti, lstpsSolutions, 2);
return lstpsSolutions.Count == 1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Searches for a fixed count of solutions. Returns as many up to that count as it can find.
/// </summary>
///
/// <remarks> Darrellp, 2/14/2011. </remarks>
///
/// <param name="ps"> The puzzle up to this point. </param>
/// <param name="es"> The expert system. </param>
/// <param name="bti"> Backtrack info. </param>
/// <param name="lstpsSolutions"> The list to place the found solutions in. </param>
/// <param name="csln"> The desired count of solutions. </param>
///
///<returns> True if we need to keep searching, false if there's no reason for more searching. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public static bool FSearchForMultipleSolutions(
TPs ps, ExpertSystem<TPs> es,
BacktrackInfo bti,
ICollection<TPs> lstpsSolutions,
int csln)
{
// Is an expert system available?
if (es != null)
{
// Apply rules and gather reasons. Is it an impossible board?
if (TryExpertSystem(es, ps, bti))
{
// Return true telling our caller to try something else
return true;
}
}
// Did we solve it with the expert system?
if (ps.FSolved())
{
// Record the solution
return RecordSolution(ps, bti, lstpsSolutions, csln);
}
// Didn't solve it by rules so start backtracking search
// Get the list of potential moves from this partial board
var lstIExtensions = ps.GetIExtensions();
// Are there no moves from the current position?
if (lstIExtensions.Count == 0)
{
// Are we keeping backtrack reasons?
if (bti != null)
{
// Add that we've reached a leaf node
bti.AddBacktrackReason(BacktrackReason.LeafNode);
}
// Return true to keep looking for solutions since none found on this branch
return true;
}
// Assume that we're going to have a choice of moves
var btr = BacktrackReason.Guess;
// Is there really only one move available?
if (lstIExtensions.Count == 1)
{
// Indicate that our choice is forced
btr = BacktrackReason.ForcedChoice;
}
else
{
// Put the extensions in the most likely order of succeeding heuristically
lstIExtensions.Sort();
}
// Try each extension in turn
foreach (var ext in lstIExtensions)
{
BacktrackInfo btiCur = null;
// Are we keeping track of backtrack reasons?
if (bti != null)
{
btiCur = new BacktrackInfo(btr, ext);
// Add that we're trying this new move
bti.AddBacktrackReason(btiCur);
}
// Apply the current extension
var psCur = (TPs)ps.PsApply(ext, true);
// Recursively search for a solution with this move
var fContinueSearch = FSearchForMultipleSolutions(psCur, es, btiCur, lstpsSolutions, csln);
// If there's no reason for more searching
if (!fContinueSearch)
{
// Return false to tell our caller that
return false;
}
}
// Still haven't found our goal count - tell our caller to keep looking
// If we're keeping backtrack reasons
if (bti != null)
{
// Add that there are no more moves
bti.AddBacktrackReason(BacktrackReason.NoMoreMoves);
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Searches for a fixed count of solutions. Returns as many up to that count as it can find.
/// </summary>
///
/// <remarks> Darrellp, 2/14/2011. </remarks>
///
/// <param name="ps"> The puzzle/game up to this point. </param>
/// <param name="cPlys"> Count of plys deep we've searched thus far</param>
/// <param name="bti"> Backtrack info. </param>
///
///<returns> An evaluation of how valuable the current board position is. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
private static int EvaluateBoard(TPs ps, int cPlys, BacktrackInfo bti)
{
// Get the list of potential moves from this partial board
var lstIExtensions = ps.GetIExtensions();
// Are there no moves from the current position?
if (lstIExtensions.Count == 0)
{
// Are we keeping backtrack reasons?
if (bti != null)
{
// Add that we've reached a leaf node
bti.AddBacktrackReason(BacktrackReason.LeafNode);
}
// Return the value of this leaf board
return ps.Evaluate();
}
// Assume that we're going to have a choice of moves
var btr = BacktrackReason.Guess;
// Is there really only one move available?
if (lstIExtensions.Count == 1)
{
// Indicate that our choice is forced
btr = BacktrackReason.ForcedChoice;
}
else
{
// Put the extensions in the most likely order of succeeding heuristically
lstIExtensions.Sort();
}
var iVal = int.MinValue;
// Try each extension in turn
foreach (var ext in lstIExtensions)
{
BacktrackInfo btiCur = null;
// Are we keeping track of backtrack reasons?
if (bti != null)
{
btiCur = new BacktrackInfo(btr, ext);
// Add that we're investigating this new move
bti.AddBacktrackReason(btiCur);
}
// Apply the current extension
var psCur = (TPs)ps.PsApply(ext, true);
if (psCur.FContinueEvaluation(cPlys))
{
iVal = Math.Max(iVal, EvaluateBoard(ps, cPlys + 1, btiCur));
}
else
{
iVal = Math.Max(iVal, ps.Evaluate());
}
}
return iVal;
}
private static bool RecordSolution(
TPs ps,
BacktrackInfo bti,
ICollection<TPs> lstpsSolutions,
int csln)
{
// Are we identical to solutions already identified?
if (lstpsSolutions.Any(psCur => ps.IdenticalTo(psCur)))
{
// Are we keeping track of backtrack reasons?
if (bti != null)
{
// Add Duplicate Solution as the reason for backtracking
bti.AddBacktrackReason(BacktrackReason.DuplicateSolution);
}
return true;
}
// New solution - add to the list of solutions
lstpsSolutions.Add((TPs)ps.Clone());
// If we've found our goal count of solution, shut the whole operation down
if (lstpsSolutions.Count == csln)
{
// Are we keeping track of backtrack reasons?
if (bti != null)
{
// Add goal count reached reason
bti.AddBacktrackReason(BacktrackReason.GoalCountReached);
}
// Return false to stop searching for other solutions
return false;
}
// Are we keeping track of backtrack reasons?
if (bti != null)
{
// Add that we found a soln but we need more
bti.AddBacktrackReason(BacktrackReason.GoalReachedButMoreNeeded);
}
// Return true to keep looking for more solutions
return true;
}
private static bool TryExpertSystem(ExpertSystem<TPs> es, TPs ps, BacktrackInfo bti)
{
List<ReasonRulePair> lstrrp;
var fImpossible = !es.FApply(ps, _fFirstTime, out lstrrp);
_fFirstTime = false;
// Are we keeping backtrack reasons?
if (bti != null)
{
// Add that we applied the expert system instead of backtracking
bti.AddExpertSystemReasons(lstrrp);
}
// Did we reach an impossible situation?
if (fImpossible)
{
// Are we keeping backtracing reasons?
if (bti != null)
{
// Add that we detected an impossible board
bti.AddBacktrackReason(BacktrackReason.RuleDetectedImpossibility);
}
// No possible solutions on this branch - Search other branches
return true;
}
return false;
}
}
}