forked from heal-research/TreesearchLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChooseSmallestProblem.cs
84 lines (71 loc) · 2.25 KB
/
ChooseSmallestProblem.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using TreesearchLib;
namespace SampleApp
{
class ChooseSmallestProblem : IMutableState<ChooseSmallestProblem, int, Minimize>
{
public const int minChoices = 2;
public const int maxChoices = 10;
public const int maxDistance = 50;
private int size;
private Stack<int> choicesMade;
public ChooseSmallestProblem(int size)
{
this.size = size;
choicesMade = new Stack<int>();
}
public bool IsTerminal => choicesMade.Count == size;
public Minimize Bound => new Minimize(choicesMade.Peek() + (size - choicesMade.Count));
public Minimize? Quality => IsTerminal ? new Minimize(choicesMade.Peek()) : null;
public void Apply(int choice)
{
choicesMade.Push(choice);
}
public object Clone()
{
var clone = new ChooseSmallestProblem(size);
clone.choicesMade = new Stack<int>(choicesMade.Reverse());
return clone;
}
public IEnumerable<int> GetChoices()
{
if (choicesMade.Count >= size)
{
yield break;
}
var current = 0;
if (choicesMade.Count > 0)
{
current = choicesMade.Peek();
}
var rng = new Random(current);
var chosen = new HashSet<int>();
for (int i = 0; i < rng.Next(minChoices, maxChoices); i++)
{
var choice = rng.Next(current + 1, current + maxDistance);
if (chosen.Add(choice))
{
yield return choice;
}
}
}
public void UndoLast()
{
choicesMade.Pop();
}
public override string ToString()
{
return $"ChooseSmallestProblem [{string.Join(", ", this.choicesMade.Reverse())}]";
}
public override bool Equals(object obj)
{
if (!(obj is ChooseSmallestProblem other))
{
return false;
}
return this.size == other.size && this.choicesMade.SequenceEqual(other.choicesMade);
}
}
}