Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class CrazyBobBeust
- {
- public static void findAll(long max) {
- Digit zero = new Digit(null, 0);
- Digit one = zero.next;
- Listener listener = new Listener();
- for (int length = 1; length <= 10; length++) {
- if (find(one, zero, length, 0, max, listener)) return;
- }
- listener.output();
- }
- private static bool find(Digit start, Digit head, int remaining, long value, long max, Listener listener) {
- for (Digit current = start; current != null; current = current.next) {
- long newValue = value + current.value;
- if (remaining == 1) {
- if (newValue > max) return true;
- listener.hear(newValue);
- }
- else {
- current.use();
- Digit newHead = (current == head) ? head.next : head;
- if (find(newHead, newHead, remaining - 1, newValue * 10, max, listener))
- return true;
- current.yield();
- }
- }
- return false;
- }
- class Digit
- {
- public readonly int value;
- public Digit previous;
- public Digit next;
- public Digit(Digit previous, int value) {
- this.value = value;
- this.previous = previous;
- if (value < 9) next = new Digit(this, value + 1);
- }
- public void use() {
- if (previous != null) previous.next = next;
- if (next != null) next.previous = previous;
- }
- public void yield() {
- if (previous != null) previous.next = this;
- if (next != null) next.previous = this;
- }
- }
- class Listener
- {
- private int _total = 0;
- public void hear(long value) {
- ++_total;
- }
- public void output() {
- Console.WriteLine("Total: {0}", _total);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement