Using visual basic, what do I need to add to my for next loop to make my application display only even numbers? - vb.net

My question is not the same as the one it is flagged as similar to. I need my application to display the actual numbers that are even in a range of numbers entered by the user. The other question prints "Even" or "Odd" based on a number.
I am working on a homework assignment where I have to make my application take numbers that are input by the user in text boxes and display the even numbers between them in a list box using a For...Next statement.
(So if the user enters 2 in the From box and 10 in the To box it, the application needs to output 2, 4, 6, 8, and 10 without commas in the list box.)
This is my current interface (Showing how the application runs with the current code):
Numbers App Test
This is my current code:
Dim intFrom As Integer
Dim intTo As Integer
Integer.TryParse(txtFrom.Text, intFrom)
Integer.TryParse(txtTo.Text, intTo)
lstNumbers.Items.Clear()
For intList As Integer = intFrom To intTo
If intFrom >= intTo Then
Exit For
End If
lstNumbers.Items.Add(intList)
Next intList
End Sub

Replace your For cycle with this:
For intList As Integer = intFrom To intTo
Dim result As Integer = intList Mod 2
If result = 0 Then
lstNumbers.Items.Add(intList)
End If
Next

Alternatives
lstNumbers.Items.Clear()
'alternative 1
Dim ie As IEnumerable(Of String)
ie = From i In Enumerable.Range(intFrom, intTo - intFrom + 1)
Where (i And 1) = 0 Select CType(i, String)
lstNumbers.Items.AddRange(ie.ToArray)
lstNumbers.Items.Clear()
'alternative 2
For intList As Integer = intFrom To intTo
If (intList And 1) = 0 Then
lstNumbers.Items.Add(intList)
End If
Next

Related

For loop not working right unless i add Msgbox inside of loop

Hello there everyone.
I have little problem, didn't make sense at all. So i have kinda simple for loop. I want to create random integers and remove index of specific array by that integer.
Working perfect:
For i = 1 To CInt(rastgelesoru.Text)
Dim Rand As New Random()
Dim xIndex As Integer = Rand.Next(0, AList.Count - 1)
Dim SelectedValue = AList(xIndex)
Dim eklepanelrnd As Panel = CType(containerpanel.Controls(SelectedValue), Panel)
If eklepanelrnd.Tag = "1" Then
MsgBox(xIndex)
containerpanelrastgele.Controls.Add(eklepanelrnd)
End If
AList.RemoveAt(xIndex)
Next
For example i have 500 element in array. When i add message box like above, it works perfect. I get random numbers. (100,65,355,27,472 last output for 5). But when i remove msgbox line i get Consecutive numbers everytime. First i thought it might be really 'random' but no. Everytime i get Consecutives. (23,24,25,160,161 last output for 5 without msgbox line.)
Not working properly without msgbox line.
For i = 1 To CInt(rastgelesoru.Text)
Dim Rand As New Random()
Dim xIndex As Integer = Rand.Next(0, AList.Count - 1)
Dim SelectedValue = AList(xIndex)
Dim eklepanelrnd As Panel = CType(containerpanel.Controls(SelectedValue), Panel)
If eklepanelrnd.Tag = "1" Then
containerpanelrastgele.Controls.Add(eklepanelrnd)
End If
AList.RemoveAt(xIndex)
Next
#AlexB. on comments.
DonĀ“t create Random objects in your loop but only create one. So move Dim Rand As New Random() before the loop.
Working perfect now. Thanks <3 Have a wonderful day.

Adding a number to an element within a listbox

I have to create an application that allows me to subtract the number 1 from each element in the array and display it in the list box using the for...next statement.
Here is what I have so far.
Private intQuantities() As Integer = {45, 67, 2, 5, 90}
Dim intnum2 As Integer = intQuantities.Length
For intCount As Integer = 0 To 4
lstQuantities.Items.Add(intQuantities(intCount))
intCount = intCount + 1
Two things standout in your code.
The first is that you are never decrementing your intQuantities variable before you add it to your listbox. The second is that you are incrementing your index inside your for statement which will cause you to skip values.
Try something like this:
Dim intnum2 As Integer = intQuantities.Length
For intCount As Integer = 0 To 4
intQuantities(intCount) -= 1 'This will subtract one and store it back to the array
lstQuantities.Items.Add(intQuantities(intCount))
Next
lstQuantities.Items.Add(intQuantities(intCount) - 1)

Random numbers in array without any duplicates

I'm trying to randomize an array from numbers 0 to 51 using loops but I just cannot seem to pull it off. My idea was that
Generate a Random Number
Check if this random number has been used by storing the previous in an array
If this random number has been used, generate new random number until it is not a duplicate
If it's not a duplicate, store it
My attempt:
Dim list(51) As Integer
Dim templist(51) As Integer
For i As Integer = 0 To 51 Step 1
list(i) = i
Next i
Do While counter <= 51
p = rand.Next(0, 52)
templist(counter) = p
For n As Integer = 0 To 51 Step 1
p = rand.Next(0, 52)
If templist(n) = p Then
Do While templist(n) = p
p = rand.Next(0, 52)
Loop
templist(n) = p
Else
templist(n) = p
End If
Next
counter += 1
Loop
For n As Integer = 0 To 51 Step 1
ListBox1.Items.Add(templist(n))
Next
It will be a lot easier if you just have a list of all of the possible numbers (0 to 51 in your case), then remove the number from the list so it can't be picked again. Try something like this:
Dim allNumbers As New List (Of Integer)
Dim randomNumbers As New List (Of Integer)
Dim rand as New Random
' Fill the list of all numbers
For i As Integer = 0 To 51 Step 1
allNumbers.Add(i)
Next i
' Grab a random entry from the list of all numbers
For i As Integer = 0 To 51 Step 1
Dim selectedIndex as Integer = rand.Next(0, (allNumbers.Count - 1) )
Dim selectedNumber as Integer = allNumbers(selectedIndex)
randomNumbers.Add(selectedNumber)
allNumbers.Remove(selectedNumber)
' Might as well just add the number to ListBox1 here, too
ListBox1.Items.Add(selectedNumber)
Next i
If your goal is to get the numbers into ListBox1, then you don't even need the "randomNumbers" list.
EDIT:
If you must have an array, try something like this:
Function RandomArray(min As Integer, max As Integer) As Integer()
If min >= max Then
Throw New Exception("Min. must be less than Max.)")
End If
Dim count As Integer = (max - min)
Dim randomNumbers(count) As Integer
Dim rand As New Random()
' Since an array of integers sets every number to zero, and zero is possibly within our min/max range (0-51 here),
' we have to initialize every number in the array to something that is outside our min/max range.
If min <= 0 AndAlso max >= 0 Then
For i As Integer = 0 To count
randomNumbers(i) = (min - 1) ' Could also be max + 1
Next i
End If
Dim counter As Integer = 0
' Loop until the array has count # of elements (so counter will be equal to count + 1, since it is incremented AFTER we place a number in the array)
Do Until counter = count + 1
Dim someNumber As Integer = rand.Next(min, max + 1)
' Only add the number if it is not already in the array
If Not randomNumbers.Contains(someNumber) Then
randomNumbers(counter) = someNumber
counter += 1
End If
Loop
Return randomNumbers
End Function
This is good enough for your assignment, but the computer scientist in my hates this algorithm.
Here's why this algorithm is much less desirable. If zero is in your range of numbers, you will have to loop through the array at least 2N times (so 104+ times if you are going from 0 to 51). This is a best case scenario; the time complexity of this algorithm actually gets worse as the range of numbers scales higher. If you try running it from 0 to 100,000 for example, it will fill the first few thousand numbers very quickly, but as it goes on, it will take longer and longer to find a number that isn't already in the list. By the time you get to the last few numbers, you could potentially have randomly generated a few trillion different numbers before you find those last few numbers. If you assume an average complexity of 100000! (100,000 factorial), then the loop is going to execute almost ten to the half-a-millionth power times.
An array is more difficult to "shuffle" because it is a fixed size, so you can't really add and remove items like you can with a list or collection. What you CAN do, though, is fill the array with your numbers in order, then go through a random number of iterations where you randomly swap the positions of two numbers.
Do While counter <= 51
p = rand.Next(0, 52)
While Array.IndexOf(list, p) = -1
p = rand.Next(0, 52)
End While
counter += 1
Loop
Haven't written VB in about 5 years, but try this out:
Function GetRandomUniqueNumbersList(ByVal fromNumber As Integer, ByVal toNumber As Integer) As List(Of Integer)
If (toNumber <= fromNumber) Then
Throw New ArgumentException("toNumber must be greater than fromNumber", toNumber)
End If
Dim random As New Random
Dim randomNumbers As New HashSet(Of Integer)()
Do
randomNumbers.Add(random.Next(fromNumber, toNumber))
Loop While (randomNumbers.Count < toNumber - fromNumber)
Return randomNumbers.ToList()
End Function
Ok, that was painful. Please someone correct it if I made any mistakes. Should be very quick because it's using a HashSet.
First response to forum on stackoverflow - be gentle.
I was looking for a way to do this but couldn't find a suitable example online.
I've had a go myself and eventually got this to work:
Sub addUnique(ByRef tempList, ByVal n, ByRef s)
Dim rand = CInt(Rnd() * 15) + 1
For j = 0 To n
If tempList(j) = rand Then
s = True
End If
Next
If s = False Then
tempList(n) = rand
Else
s = False
addUnique(tempList, n, s)
End If
End Sub
Then call the sub using:
Dim values(15) As Byte
Dim valueSeen As Boolean = False
For i = 0 To 15
addUnique(values, i, valueSeen)
Next
This will randomly add the numbers 1 to 16 into an array. Each time a value is added, the previous values in the array are checked and if any of them are the same as the randomly generated value, s is set to true. If a value is not found (s=false), then the randomly generated value is added. The sub is recursively called again if s is still true at the end of the 'For' loop. Probably need 'Randomize()' in there somewhere.
Apologies if layout is a bit wobbly.

Populating 2 dimensional array using a For loop

Currently I'm trying to fill a 3x3 square with random x's and o's to make a tic tac toe
game. Unfortunately the game doesn't seem to output all the x's and o's. Logically, from what I can see, it should be able to but it's not. Any help would be appreciated.
Shared Sub twodimension()
Dim tic(2, 2) As String
Dim min As Integer
Dim x As String
Dim random As New Random()
Dim i As Integer
Dim x1 As Integer
Dim bound0 As Integer = tic.GetUpperBound(0)
Dim bound1 As Integer = tic.GetLowerBound(1)
For i = 0 To bound0
For x1 = 0 To bound1
min = random.Next(2)
If min = 0 Then
x = "x"
Console.WriteLine("{0}", x)
Else
x = "o"
Console.WriteLine("{0}", x)
End If
Console.Write(" "c)
Next
Console.WriteLine()
Next
End Sub
So presumably you've got this declaration somewhere, right?
Public Shared Tic(2, 2) As String
In your code you've got GetLowerBound which will (almost) always returns zero and instead you should have GetUpperBound().
Dim bound0 As Integer = tic.GetUpperBound(0)
Dim bound1 As Integer = Tic.GetUpperBound(1)
EDIT (in response to comment)
GetUpperBound(int) returns the highest number that you can use for the dimension that you specify.
So for the following array:
Dim MyArray(4, 6, 8) As Integer
Trace.WriteLine(MyArray.GetUpperBound(0)) ''//Returns 4
Trace.WriteLine(MyArray.GetUpperBound(1)) ''//Returns 6
Trace.WriteLine(MyArray.GetUpperBound(2)) ''//Returns 8
GetLowerBound(int) returns the lowest number that you can use for the dimension that you specify. In almost every case this is zero but in older versions of VB (and using some COM interop) you can create arrays that don't "start" at zero and instead start at whatever you wanted. So in old VB you could actually say Dim Bob(1 To 4) As Integer and GetLowerBound(0) would return 1 instead of 0. For the most part there is no reason to even be aware that GetLowerBound exists even.

vb express 2010 populating array

it doesnt like my code:
Dim n As Integer
Dim flag As Boolean
Dim i
Dim x() As Integer
n = InputBox("How many numbers do you want to be sorted?")
For i = 1 To n - 1 Step 1
x(i) = InputBox("Please enter a record")
Next i
I want to put values into x()
You need to use a ReDim to specify the size of x as soon as you know it (ie after your first InputBox):
n = InputBox("How many numbers do you want to be sorted?")
ReDim x(n - 1)
Also, your For loop will be simpler to handle if it's zero based as in:
For i = 0 To n - 1 Step 1