Posted by sijin on Fri 29 Aug 14:27
report abuse | View followups from kathirvel | download | new post
- class CrazyBobBeust
- {
- public static void findAll(long max) {
- Digit one = zero.next;
- 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;
- }
- 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);
- }
- }
- }
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.