The Question :
How can I get all the possible combinations of numbers?
For example the input numbers are 1, 2 and 3
How can i get all the possible combinations of these numbers
For example
1 2 3
3 2 1
3 1 2
2 1 3
2 3 1
1 3 2
How can i get all of this??? The numbers depends on the input for example the input numbers are from 1 - 9
how can i get all the possible combinations for that.
Hope someone could help me out here...
Thanks in advance!
The Best Answer by Robert Rossney :
Recursion is the key. To find all of the permutations of an n-element set, find, for each element in the set, all of the permutations of the n-element subset that doesn't contain that element.
Here's an implementation. It's not very efficient (an efficient algorithm would keep the current permutation in an array that it passes by reference, instead of accumulating it in a string), but it's correct:
class Program { static int count; static void Main(string[] args) { char[] set = new char [] { 'a', 'b', 'c' }; FindPermutations(String.Empty, set); Console.WriteLine("{0} permutations found", count); Console.ReadLine(); } static void FindPermutations(string permutation, char[] set) { if (set.Length == 1) { Console.WriteLine(permutation + set[0]); count++; return; } for (int i = 0; i <> { char n = set[i]; string newPermutation = permutation + n; char[] subset = new char[set.Length - 1]; int j = 0; for (int k = 0; k <> { if (set[k] != n) { subset[j++] = set[k]; } } FindPermutations(newPermutation, subset); } } } The Code converted to VB.net
Shared count As Integer
PrivateSharedSub Main(ByVal args As String())
Dim [set] As Char() = New Char() {"a"C, "b"C, "c"C}
FindPermutations([String].Empty, [set])
Console.WriteLine("{0} permutations found", count)
Console.ReadLine()
EndSub
PrivateSharedSub FindPermutations(ByVal permutation As String, ByVal [set] As Char())
If [set].Length = 1 Then
Console.WriteLine(permutation + [set](0))
count += 1
Return
EndIf
For i As Integer = 0 To [set].Length - 1
Dim n As Char = [set](i)
Dim newPermutation As String = permutation + n
Dim subset As Char() = New Char([set].Length - 2) {}
Dim j As Integer = 0
For k As Integer = 0 To [set].Length - 1
If [set](k) <> n Then
subset(System.Math.Max(System.Threading.Interlocked.Increment(j),j - 1)) = [set](k)
EndIf
Next
FindPermutations(newPermutation, subset)
Next
EndSub
EndClass
0 comments:
Post a Comment