algorithm - Getting unique numbers efficiently? -
the problem in question check equation, example:
a * b / c + d = x
where - d unique numbers 1 - 4.
now run through possibilities, skip when has duplicates, o(n^n), when should able solve o(n!) can't figure out how.
is there algorithm this?
based on wording ("a - d unique numbers 1 - 4") seems want algorithm generating possible permutations of set of numbers - in case set {1, 2, 3, 4}
.
given size of set, algorithm best implemented recursively: every element in set (from left right) generate permutations of remaining elements. note once last element, there's 1 possible order.
this approach reduces problem of finding permutations of n items finding permutations of n-1 items.
here's how on set {1, 2, 3}
expect have 6 permutations:
{1, 2, 3} 1 | {2, 3} 1 | 2 | {3} 1 | 2 | 3 1 | 3 | {2} 1 | 3 | 2 2 | {1, 3} 2 | 1 | {3} 2 | 1 | 3 2 | 3 | {1} 2 | 3 | 1 3 | {1, 2} 3 | 1 | {2} 3 | 1 | 2 3 | 2 | {1} 3 | 2 | 1
so algorithm gives following 6 permutations:
123, 132, 213, 231, 312, 321
you can find lot of information on wikipedia article on permutations, including permutation generation algorithms.
Comments
Post a Comment