[2008] All combinations of 4 digit code-VBForums

# Thread: [2008] All combinations of 4 digit code

1. ## [2008] All combinations of 4 digit code

I'm wonder if I had a code, say 9319, how could I get every possible combination of it, IE 9319, 9139, etc..

Cheers
Icyculyr

2. ## Re: [2008] All combinations of 4 digit code

Nested loops would do this.
Code:
```For firstNumericDigit as integer = 0 to 9
For secondNumericDigit as integer = 0 to 3
' .. Other loops here
' .. linkage of variable values and output here```

3. ## Re: [2008] All combinations of 4 digit code

Thanks, it's not quite what I mean though, I want all possible combinations of specific 4 digit code, IE, every possible combination containing the numbers 9319, etc.. not every possible 4 digit combination

Cheers
Icyculyr

4. ## Re: [2008] All combinations of 4 digit code

Well so far i have come up with this.

vb Code:
`Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click        Dim A As Integer        Dim B As Integer        Dim C As Integer        Dim D As Integer         A = 1        B = 2        C = 3        D = 4         Label1.Text = A & B & C & D        Label2.Text = A & B & D & C        Label3.Text = A & C & B & D        Label4.Text = A & C & D & B        Label5.Text = A & D & B & C        Label6.Text = A & D & C & B        Label7.Text = B & A & C & D        Label8.Text = B & A & D & C        Label9.Text = B & C & A & D        ' Etc Etc Etc    End Sub`

Now the thing I am not sure on, which you might be able to do is take the first number inside of a textbox say, and put that as A, and the second as B etc.

So A = Textbox1.text.(first) or what ever.

5. ## Re: [2008] All combinations of 4 digit code

I had help on this, so I can not take all the credit.

But here you go.

vb Code:
`A = TextBox1.Text.Substring(0, 1)        B = TextBox1.Text.Substring(1, 1)        C = TextBox1.Text.Substring(2, 1)        D = TextBox1.Text.Substring(3, 1)`

I have to give thanks to Mr Ludwig

6. ## Re: [2008] All combinations of 4 digit code

Something else, you will get an error if you do not have 4 numbers. Plus you will get an error if you put letters inside. So.....

All of that into an If statement.

vb Code:
`If Textbox1.Text.Length = 4 Then ' Do the code already given Else MsgBox("TextBox does not contain 4 digits!") End If`

7. ## Re: [2008] All combinations of 4 digit code

I love it - nice challenge! Good question that! Ok I *think* this works, appears to from a quick glance but I'll leave you to check all the combinations are there:
Code:
```Public Class Form1
Private _temporaryOutputString As String

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim numericCodeOutputArrayList As New ArrayList
Dim numericCodeInitArray(3) As String
numericCodeInitArray(0) = "1" '"9"
numericCodeInitArray(1) = "2" '"3"
numericCodeInitArray(2) = "3" '"1"
numericCodeInitArray(3) = "4" '"9"

Dim firstOutputElementText As String = ""
Dim secondOutputElementText As String = ""
Dim thirdOutputElementText As String = ""

For repositionFirstIndex As Integer = 0 To 3
For repositionSecondIndex As Integer = 0 To 2
For repositionThirdIndex As Integer = 0 To 1
OutputCurrentNumericCode(numericCodeOutputArrayList)

thirdOutputElementText = numericCodeOutputArrayList.Item(2)
numericCodeOutputArrayList.RemoveAt(2)
Next repositionThirdIndex

secondOutputElementText = numericCodeOutputArrayList.Item(1)
numericCodeOutputArrayList.RemoveAt(1)
Next repositionSecondIndex

firstOutputElementText = numericCodeOutputArrayList.Item(0)
numericCodeOutputArrayList.RemoveAt(0)
Next repositionFirstIndex
End Sub

Private Sub OutputCurrentNumericCodeToTextbox(ByRef numericCodeArrayList As ArrayList)
_temporaryOutputString = numericCodeArrayList.Item(0)
_temporaryOutputString &= numericCodeArrayList.Item(1)
_temporaryOutputString &= numericCodeArrayList.Item(2)
_temporaryOutputString &= numericCodeArrayList.Item(3)
_temporaryOutputString &= Environment.NewLine
TextBox1.Text &= _temporaryOutputString
End Sub
End Class```

8. ## Re: [2008] All combinations of 4 digit code

Look in VB.Net code bank. I remember seeing a thread on creating unique combinations (permutation) there. With just 4 digits, it's OK to hard code it the way you do now, but imagine if you have 10 or more digits, you will not want to hard code it then

9. ## Re: [2008] All combinations of 4 digit code

But he doesn't have 10 digits, I see where you are going with this true it would be a nightmare to hardcode all combinations of a 10 digits.

But he only wants 4, which is only a 2 min job to hardcode all those combinations.

10. ## Re: [2008] All combinations of 4 digit code

Originally Posted by Lerroy_Jenkins
But he doesn't have 10 digits, I see where you are going with this true it would be a nightmare to hardcode all combinations of a 10 digits.

But he only wants 4, which is only a 2 min job to hardcode all those combinations.
Didn't I say it's OK to hard code with only 4 digits?

11. ## Re: [2008] All combinations of 4 digit code

Yes

I am just stuck on trying to work out how to stop an error being thrown up if the user puts in letters. My code works with Numbers.

And as for Alex's code..that went right over my head!

12. ## Re: [2008] All combinations of 4 digit code

Originally Posted by Lerroy_Jenkins
Yes

I am just stuck on trying to work out how to stop an error being thrown up if the user puts in letters. My code works with Numbers.

And as for Alex's code..that went right over my head!
How about using simple If's statement to check for the string.length first?
Code:
```If userInput.Length >= 5 Then
'Do something
Else
MessageBox.Show("Input must be at least 5 character long!")
End If```

13. ## Re: [2008] All combinations of 4 digit code

Originally Posted by Lerroy_Jenkins
Something else, you will get an error if you do not have 4 numbers. Plus you will get an error if you put letters inside. So.....

All of that into an If statement.

vb Code:
`If Textbox1.Text.Length = 4 Then ' Do the code already given Else MsgBox("TextBox does not contain 4 digits!") End If`

This is what I have said a few posts ago, so I am checking that.

But all of my code only works for numbers, not letters.

14. ## Re: [2008] All combinations of 4 digit code

Ok ok I guess I can put in some comments, sorry!

I was storing the numbers in an arraylist as it has a remove() method. So 1st time it runs, the value is:
1234
After I print this, I store, then drop the 1st number using that removeat() method, so I get this:
234
and then I add that number to the end, so I get this:
2341
The loop runs round this procedure 4 times, each time dropping the 1st character, and appending it to the end to give:
1234
2341
3412
4123

The inner loops are doing the same thing, just on different characters - the 1st loop looks at the 2st character and worries about replacing that one, the 2nd loop does the same for the 2nd character out of the 4, and so-on if that makes sense...

15. ## Re: [2008] All combinations of 4 digit code

That is very clever! I understand it a little better now.

I like my code better though.... Its simple... Just like me

16. ## Re: [2008] All combinations of 4 digit code

Thanks Quite a challenge and took a little while though! I noticed in the original, you had 2 of the same number there 9319 so the sample above will throw duplicates up (I was testing 1234 to make things easier in that one above). Here is a second sample for your scenario specifically, which removes the duplicates which the two 9 values create:
Code:
```Public Class Form1
Private _temporaryOutputString As String
Private _temporaryOutputArrayList As ArrayList

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim numericCodeOutputArrayList As New ArrayList
Dim numericCodeInitArray(3) As String
numericCodeInitArray(0) = "9"
numericCodeInitArray(1) = "3"
numericCodeInitArray(2) = "1"
numericCodeInitArray(3) = "9"

Dim firstOutputElementText As String = ""
Dim secondOutputElementText As String = ""
Dim thirdOutputElementText As String = ""
_temporaryOutputArrayList = New ArrayList

For repositionFirstIndex As Integer = 0 To 3
For repositionSecondIndex As Integer = 0 To 2
For repositionThirdIndex As Integer = 0 To 1
StoreCurrentNumericCode(numericCodeOutputArrayList)

thirdOutputElementText = numericCodeOutputArrayList.Item(2)
numericCodeOutputArrayList.RemoveAt(2)
Next repositionThirdIndex

secondOutputElementText = numericCodeOutputArrayList.Item(1)
numericCodeOutputArrayList.RemoveAt(1)
Next repositionSecondIndex

firstOutputElementText = numericCodeOutputArrayList.Item(0)
numericCodeOutputArrayList.RemoveAt(0)
Next repositionFirstIndex

RemoveNumericCodeDuplicates(_temporaryOutputArrayList)
OutputUniqueNumericCodes(_temporaryOutputArrayList)
End Sub

Private Sub StoreCurrentNumericCode(ByRef numericCodeArrayList As ArrayList)
_temporaryOutputString = numericCodeArrayList.Item(0)
_temporaryOutputString &= numericCodeArrayList.Item(1)
_temporaryOutputString &= numericCodeArrayList.Item(2)
_temporaryOutputString &= numericCodeArrayList.Item(3)
_temporaryOutputString &= Environment.NewLine
End Sub

Private Sub RemoveNumericCodeDuplicates(ByRef storedNumericCodeArrayList As ArrayList)
Dim currentlyEvaluatedElementText As String = ""
Dim IsReadLoopOfArraylistComplete As Boolean = False
Dim IsDuplicateRemovalLoopOfArraylistComplete As Boolean = False
Dim storedNumericCodeElementIndex As Integer = 0
Dim duplicateSearchElementIndex As Integer = 0

Do Until storedNumericCodeElementIndex >= storedNumericCodeArrayList.Count
currentlyEvaluatedElementText = _
storedNumericCodeArrayList(storedNumericCodeElementIndex)
duplicateSearchElementIndex = storedNumericCodeElementIndex + 1
If currentlyEvaluatedElementText = 9139 Then
Dim i As Integer = 1
End If
Do Until duplicateSearchElementIndex >= storedNumericCodeArrayList.Count
If (storedNumericCodeArrayList(duplicateSearchElementIndex) = _
currentlyEvaluatedElementText) Then
storedNumericCodeArrayList.RemoveAt(duplicateSearchElementIndex)
duplicateSearchElementIndex = duplicateSearchElementIndex - 1
If Not (storedNumericCodeElementIndex = 0) Then
storedNumericCodeElementIndex = storedNumericCodeElementIndex - 1
End If
End If
duplicateSearchElementIndex += 1
Loop
storedNumericCodeElementIndex += 1
Loop
End Sub

Private Sub OutputUniqueNumericCodes(ByRef storedNumericCodeArrayList As ArrayList)
For storedNumericCodeElementIndex = 0 To storedNumericCodeArrayList.Count - 1
TextBox1.Text &= storedNumericCodeArrayList(storedNumericCodeElementIndex)
'TextBox1.Text &= Environment.NewLine
Next storedNumericCodeElementIndex
End Sub
End Class```

17. ## Re: [2008] All combinations of 4 digit code

I had help on a different part of this code from "Shuja Ali".

But here is the end piece, this will give you all possible combinations for a 4 digit number.

vb Code:
`Public Class Form1     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click         Dim A As Integer        Dim B As Integer        Dim C As Integer        Dim D As Integer         If IsNumeric(TextBox1.Text) Then            If TextBox1.Text.Length = 4 Then                 A = TextBox1.Text.Substring(0, 1)                B = TextBox1.Text.Substring(1, 1)                C = TextBox1.Text.Substring(2, 1)                D = TextBox1.Text.Substring(3, 1)                 Label1.Text = A & B & C & D                Label2.Text = A & B & D & C                Label3.Text = A & C & B & D                Label4.Text = A & C & D & B                Label5.Text = A & D & B & C                Label6.Text = A & D & C & B                Label7.Text = B & A & C & D                Label8.Text = B & A & D & C                Label9.Text = B & C & A & D                Label10.Text = B & C & D & A                Label11.Text = B & D & A & C                Label12.Text = B & D & C & A                Label13.Text = C & A & B & D                Label14.Text = C & A & D & B                Label15.Text = C & B & A & D                Label16.Text = C & B & D & A                Label17.Text = C & D & A & B                Label18.Text = C & D & B & A                Label19.Text = D & A & B & C                Label20.Text = D & A & C & B                Label21.Text = D & B & A & C                Label22.Text = D & B & C & A                Label23.Text = D & C & A & B                Label24.Text = D & C & B & A             Else                 MsgBox("TextBox does not contain 4 Numbers!")            End If         Else             MsgBox("TextBox does not contain 4 Numbers!")         End If    End Sub      Public Function IsNumeric(ByVal inputString As String) As Boolean        Dim _isNumber As System.Text.RegularExpressions.Regex = New  _        System.Text.RegularExpressions.Regex("(^[-+]?\d+(,?\d*)*\.?\d*([Ee][-+]\d*)?\$)|(^[-+]?\d?(,?\d*)*\.\d+([Ee][-+]\d*)?\$)")        Return _isNumber.Match(inputString).Success    End FunctionEnd Class`

18. ## Re: [2008] All combinations of 4 digit code

Originally Posted by Lerroy_Jenkins
This is what I have said a few posts ago, so I am checking that.

But all of my code only works for numbers, not letters.
So, in other words, you want to restrict the user to input only numeric values, right? If it's the case, there are various methods you can implement.

1. Use a NumericUpDown control instead of a TextBox. This is by far the easiest method because the control handles the filtering for you automatically, you don't have top write any additional code.

2. If you MUST use a TextBox, then you should handle the KeyPress event of the textbox and check to see if the inputted KeyChar is numeric. If it's not, you cancel the event. Search the forum for "numeric textbox" and you'll find some example.

3. Depending on what value type you're expecting to get from the user, use the TryParse method of that Type (i.e Integer.TryParse, Double.TryParse...), and if the TryParse returns false, you know that it's not a valid number.

19. ## Re: [2008] All combinations of 4 digit code

I don't know about you guys but I had the same question for a homework assignment when I took a VB.Net course about 4 years ago. You may have done his homework for him.

20. ## Re: [2008] All combinations of 4 digit code

Drat. I wondered that, but I thought no - couldn't be as that was a hard one. Ohh well got caught out that time then.

21. ## Re: [2008] All combinations of 4 digit code

This is pretty interesting. Here's what I came up with. It's totally dynamic, so it works with any number you input. But it is not the best method, only a quick and dirty one. It works on this principle:

Permute: 1234

Take 2, and place it at every possible position in 1: 21, 12

Take 3, and place it at every possible position in the previous numbers: 321, 231, 213, 312, 132, 123

Take 4, and place it at every possible position in each of the previous numbers: 4321, 3421, 3241, 3214, 4231, 2431, 2341, 2314, ...

Continue indefinitely.

This takes approx. 10 seconds to calculate every permutation of a 9-digit number = 362880 permutations

Code:
```Public Class Robust_Permutator
'This list stores each number within the raw number
Private Initial_Number_List As List(Of Integer)
'This list stores the first number within the raw number, in order to pass it into the permutation function
Private Initial_Permutations_List As List(Of Integer)

Private Sub btn_Permutate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Permutate.Click
'Initialise the lists
Initial_Number_List = New List(Of Integer)
Initial_Permutations_List = New List(Of Integer)

'This loop loads all of the numbers within the raw number into the Number_List, starting from the second number
For Number = 1 To txt_RawNumber.TextLength - 1
Next

'Add the first number in the raw number to the Permutations_List to set it up

'Disable the button
btn_Permutate.Enabled = False

'Make the progress bar visible
prg_Permutations.Visible = True

'Initialise the background worker
bgr_Permutator.RunWorkerAsync()
End Sub

Private Sub txt_RawNumber_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_RawNumber.TextChanged
'Enable the button if the value in the textbox is a number of at least 2 digits
btn_Permutate.Enabled = (IsNumeric(txt_RawNumber.Text) And txt_RawNumber.TextLength > 1)
End Sub

Private Function Permutate(ByVal Worker As System.ComponentModel.BackgroundWorker, ByVal Numbers As List(Of Integer), ByVal Permutated_Combinations As List(Of Integer)) As String
'Declare a background worker and assign it to the Worker parameter
Dim bgrWorker As System.ComponentModel.BackgroundWorker = Worker
'Declare a list and assign it to the Numbers parameter
Dim Number_List As List(Of Integer) = Numbers
'Declare a list and assign it to the Permutated_Combinations parameter
Dim Permutations_List As List(Of Integer) = Permutated_Combinations

'Declare a variable to record the current number of objects in the Permutations_List
Dim Permutation_Count As Integer = Permutations_List.Count

'Declare a variable to hold the currently selected Permutations_List number as a string
Dim Current_Number As String
'Declare a variable that will be manipulated and added to the Permutations_List
Dim Temporary_Number As String

'Loop through each of the original numbers in the Permutations_List
For List_Index As Integer = 0 To Permutation_Count - 1
'Convert the current number to a string for manipulation
Current_Number = Permutated_Combinations(List_Index).ToString()
'Loop through each position in the Current_Number
For Place_Holder As Integer = 0 To Current_Number.Length
'Assign the Current_Number to the Temporary_Number
Temporary_Number = Current_Number
'Insert the first number in the Number_List into the Temporary_Number string at the current position and add the new number to the Permutations_List
Next
Next

'Remove the first number in the Number_List
Number_List.RemoveAt(0)

'Loop through the Permutations_List until the last original number
For List_Index As Integer = 0 To Permutation_Count - 1
'Remove the first number in the list
Permutations_List.RemoveAt(0)
Next

'Update the UI thread with the number of recursions left to go
bgrWorker.ReportProgress(0, Number_List.Count)

'Check whether there are any more numbers in the Numbers_List
If Number_List.Count = 0 Then
'Declare and initialise a new stringbuilder
Dim Permutated_Numbers As New System.Text.StringBuilder
'Loop through each number in the Permutations_List
For List_Index As Integer = 0 To Permutations_List.Count - 1
'Add the string representation to the stringbuilder
Permutated_Numbers.AppendLine(Permutations_List(List_Index).ToString())
Next
'Return all of the permutated values
Return Permutated_Numbers.ToString()
Else
'Call the function from itself
Return Permutate(bgrWorker, Number_List, Permutations_List)
End If
End Function

Private Sub bgr_Permutator_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgr_Permutator.DoWork
'Declare a background worker and assign it to sender
Dim Worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)

'The background worker returns the permutated values
e.Result = Permutate(Worker, Initial_Number_List, Initial_Permutations_List)
End Sub

Private Sub bgr_Permutator_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgr_Permutator.ProgressChanged
'Update the progress bar value
prg_Permutations.Value = (CDbl(txt_RawNumber.TextLength) - CDbl(e.UserState)) / CDbl(txt_RawNumber.TextLength) * 100
End Sub

Private Sub bgr_Permutator_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgr_Permutator.RunWorkerCompleted
'Fill the permutations textbox with the permutated values
txt_Permutations.Text = DirectCast(e.Result, String)

'Make the progress bar invisible
prg_Permutations.Visible = False

'Enable the button
btn_Permutate.Enabled = True
End Sub
End Class```

22. ## Re: [2008] All combinations of 4 digit code

Might be a quick and dirty one but so were ours, I like the novel idea of the background worker for this, and making it generic. Was thinking of that when I hardcoded 4 loops in and wouldn't have been nice altering that way. Nice different take there! you too Leeroy Jenkins ??!! :P nothing wrong with keeping it simple - if it is homework or Icyculyr is at a novice level at the mo, then yours is the one which'll be used!

23. ## Re: [2008] All combinations of 4 digit code

>>It's not homework, nor am I a novice I just didn't want to spend time figuring it out -.- (nor did I have any)

Cheers
Icyculyr

24. ## Re: [2008] All combinations of 4 digit code

lol, I am simple Makes it easier for me to understand until I am big and brainy like you guys lol.

And you lazy monkey Icyculyr! lol. '_'

25. ## Re: [2008] All combinations of 4 digit code

And you lazy monkey Icyculyr! lol. '_'
Haha, why be pro-active when I have a whole community of people to do things for me? LOL

I'm just joking, but seriously I was busy, I didn't have time, I was thinking how to calculate how many different combinations there was..

it's not 4^4, is it 4*4? I don't know..

Cheers
Icyculyr

26. ## Re: [2008] All combinations of 4 digit code

1 Digit there is 1 combination

2 digits there are A B and B A combinations SO 2.

3 digits A B C, A C B, B A C, B C A, C A B, C B A. So 6 combinations

4 digits theres 24 combinations.

So we are going 1, 2, 6, 24. Can you see a pattern? Want me to work out 5 digits and their combinations?

27. ## Re: [2008] All combinations of 4 digit code

Its simple. THe penny just dropped.

4 numbers to pick from (the user has put 4 numbers into the program) A B C D for example.

There are 4 possible options for the first choice.

There are then 3 possible options for the second choice.

There are then 2 possible options for the third choice.

And that leaves 1 possible option for the last choice.

So 4 * 3 * 2 * 1 = 24. 24 possibilities.

So to work out 5 possibilities 5 * 4 * 3 * 2 * 1 = 120.

6 possibilities = 6 * 5 * 4 * 3 * 2 * 1 = 720.

So you can work out how many possibilities there are. I wouldn't recomend hard coding for 5 digits +. 4 is easy, 5 and above is rediculouse.

28. ## Re: [2008] All combinations of 4 digit code

Thanks, that makes sense

Cheers
Icyculyr

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Featured