Repeat Same Action In VB Console every second - vb.net

I want to execute this code, unfortunately it executes only once and then stops. how do execute this code to display every second? and after doing this 100 times, to stop, that is, after a fixed 100 seconds.
Do
Dim index As Integer = 0
index += 1
Console.WriteLine(RandomString(102, 102))
Console.ReadLine()
Do
Threading.Thread.Sleep(1000)
Loop Until index = 100
Loop

Try this:
Dim index As Integer = 0
Do Until index = 100
index += 1
Console.WriteLine(RandomString(102, 102))
Threading.Thread.Sleep(1000)
Loop
Console.ReadLine()

Related

Progress Reporting causes BackGroundWorker to Run Slow. VB

I am using a BackgroundWorker to write to pixels on an internal bitmap, using a loop.
The BackgroundWorker DoWork routine does not access any GUI components.
If I run the loop without any Progress Reporting, the loop takes about 2 seconds to complete, which is satisfactory.
If I add Progress Reporting, the loop takes about 20 seconds to complete!! Not good!!
I notice that when Progress Reporting is on and the loop is running, the form cannot be dragged about the screen, and my Cancel button (code for this not included here) is not responded to until the loop completes.
Its as if the program was not running in a BackGroundWorker.
The Progress Reporting code is quite standard, and has been used a number of times before:
Dim x As Integer = 5000
Dim y As Integer = 2500
Dim i as Integer = 0
For a As Integer = 0 To x
For b As Integer = 0 To y
' Other fast code
worker.ReportProgress(CInt(100 * (i / (x * y)))
i += 1
Next
Next
Private Sub BGW_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BGW.ProgressChanged
ProgressBar.Value = e.ProgressPercentage
StatusLabel.Text = "Progress: " & e.ProgressPercentage & "%"
End Sub
This all seems good and standard, until I realised that the ReportProgress line is actually sending its value to the ProgressChanged routine 12,500,000 times, when actually we only need to send a value 100 times. It was the flood of values that caused the problem.
This code works perfectly. I hope it is useful to someone else:
Dim x As Integer = 5000
Dim y As Integer = 2500
Dim i as Integer = 0
Dim j As Double = (x * y) / 100
Dim k As Integer = 0
For a As Integer = 0 To x
For b As Integer = 0 To y
' Other fast code
i += 1
If i > j Then
k += 1
worker.ReportProgress(CInt(k))
i = 0
End If
Next
Next
You should use a public variable (Like "ReportValue") and a timer .
The timer is in a continuos loop and it set the value of the progressBar using the "ReportValue" .
On the other side , your backgroundWorker reports the progress in the "ReportValue" variable .
So you can refresh your ProgressBar without losing time in handling the [Progress state change]
then add this code to the timer:
If Not ReportValue = MyProgressBar.Value Then
MyProgressBar.Value = ReportValue
end if
The timer will refresh the progressbar value only if the value is changed
( preventing an high CPU usage )
Hope it helps :)
An easy way is to only report progress if there is progress to report:
Dim x As Integer = 5000
Dim y As Integer = 2500
Dim i as Integer = 0
Dim oldProgress = 0
For a As Integer = 0 To x
For b As Integer = 0 To y
' Other fast code
Dim progress = CInt(100 * (i / (x * y))
If progress > oldProgress Then
worker.ReportProgress(progress)
oldProgress = progress
End If
i += 1
Next
Next

Does this code not work because it will take a long time or is it broken?

I am currently trying to generate random numbers until a user defined amount of identical numbers in a row appears. The numbers range from 1 to 10.
When I want 8 identical numbers in a row it takes between 3 and 5 seconds. It goes through about 5 million random numbers. When I want 9 in a row I have left it for over 45 minutes without any luck.
I thought it would only take about 10 times the amount of time as it did for 8 since 1/10 to the power of 9 is only ten times bigger than to the power of 8.
Is it a problem with my code or have I messed up the maths?
MY CODE:
Sub Main()
Console.WriteLine("how many identical numbers in a row do you want")
Dim many As Integer = Console.ReadLine
Dim storage(many - 1) As Integer
Dim complete As Boolean = False
Dim part As Integer = 0
Dim count As Integer = 0
Randomize()
While complete = False
count += 1
storage(part) = Int(Rnd() * 10) + 1
' Console.WriteLine(storage(part))
part += 1
If part = many Then
part = 0
End If
If storage.Min = storage.Max Then
complete = True
End If
End While
Console.WriteLine("===========")
Console.WriteLine(count.ToString("N"))
Console.WriteLine("===========")
For i = 0 To many - 1
Console.WriteLine(storage(i))
Next
Console.ReadLine()
End Sub
There is more than one possibility: it could be that the VB Rnd function is written so that it can never work, or it could be that it really does simply take a long time sometimes. You would have to do many trials and average them out to find out if your expected ratio of 1:10 works as expected.
Incidentally, you don't need to keep the last ten numbers. You can just keep a count of how many times the next random number equals the previous number. Also I suggest trying a different RNG (random number generator), for example the .NET one:
Module Module1
Dim rand As New Random()
Sub Main()
Console.Write("How many identical numbers in a row do you want: ")
Dim howMany As Integer = CInt(Console.ReadLine)
Dim count As Long = 0
Dim previous = -1
Dim soFar = 0
Dim n = 0
While soFar < howMany
count += 1
n = rand.Next(1, 11)
'Console.Write(n.ToString() & " ")
If n = previous Then
soFar += 1
Else
'If previous >= 0 Then
' Console.WriteLine(" X")
' Console.Write(n.ToString() & " ")
'End If
previous = n
soFar = 1
End If
End While
Console.WriteLine()
Console.WriteLine("Tries taken: " & count.ToString())
Console.ReadLine()
End Sub
End Module

Parallel Loop & Stringbuilder

Intro: Hi all this is my first question, so please do let me know if I did or am doing anything wrong. I working on a project and one of its functions is to write a huge chunk of text to process the data and replace specific text at certain lines and output the file to a richtextbox/file.
Problem: The problem is that when I use a parallel foreach, my results in the richtextbox are all over the place, they are not according to lines (e.g. the first line may become the 15th line after the parallel foreach loop is run).
What the code does: It loops through a richtextbox and checks if the line matches the first line in a temporary richtextbox, if so it would stop the append and copy the text from the temporary richtextbox and let the loop run until the amount of lines which have past match the number of lines in the temporary richtextbox and then continue the append. It is basically a replace of text. Total output I am looking at about 20K lines.
Dim completertb4text As New StringBuilder("")
Parallel.ForEach(newrtb.Lines, Function() New StringBuilder(), Function(x, [option], sb)
If x.Contains(richtextboxl0) Then
startcount = True
sb.Append(vbNewLine & richtextbox3text & "111111")
End If
If startcount = True Then
If counter = temptextbox3count Then
startcount = False
Else
counter += 1
End If
End If
If sb.Length = 0 Then
sb.Append(vbNewLine & x & "222222")
End If
If sb.Length > 0 Then
sb.Append(vbNewLine & x & "3333333")
End If
Return sb
Function, Sub(sb)
SyncLock completertb4text
completertb4text.Append(sb.ToString())
End SyncLock
End Sub
Any help is kindly appreciated, thanks in advance!
Here is how I shrank my code from 08:00 seconds to 00:01 seconds.
Dim counter As Integer = 0
Dim countertrue As Integer = 0
Dim countintertal As Integer = 0
Dim newrtbstrarray As String() = newrtb.Lines
Dim rtb3array As String() = richtextbox3text.Lines
For Each line As String In newrtbstrarray
If line.Contains(richtextboxl0) Then
countertrue = counter
For Each element As String In rtb3array
newrtbstrarray(countertrue) = rtb3array(countintertal)
countertrue += 1
countintertal += 1
Next
End If
counter += 1
Next

If an INDEX exist in Listbox in vb.net

I am running a Do Until Loop and its giving the error Index out of range. I am using this code:
If Not imgList.Item(i).ToString = Nothing Then
but its not working..
Actually this loop (in a private sub) is called before addition of any value in the Listbox..
here is the complete loop..
Dim i As Integer = 0
Do Until i = pagesRange
If Not imgList.Item(i).ToString = Nothing Then
'other code
i += 1
Else
End If
Loop
for the given code to avoid Index out of range exception try below
If imgList.Count < i AndAlso Not (imgList.Item(i).ToString Is Nothing) Then
End If
Remember about Zero Based ..
Dim i As Integer = 0
Do Until i = pagesRange -1
If Not imgList.Item(i).ToString = Nothing Then
'other code
i += 1
Else
End If
'why i += 1 not here ?
Loop

Visual Basic - Looping an array 100 times not working?

I'm trying to loop this array 100 times (gets a number from 0-99,999). I've tried it several different ways with no luck. I've got it set up so you click a button and it generates the array. The user will then enter a number and hit the other button to check how many times that number shows up in the group of a 100 numbers. Any thoughts how to fix it? I'm stuck.
Dim i As Integer
Dim rnd As New Random()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnter.Click
Dim num As Integer
If Int32.TryParse(txtEnter.Text, num) AndAlso num >= 0 AndAlso num < 10 Then
lblNumber.Text = i.ToString()
Dim counts = From c In i.ToString()
Group By c Into Group
Select DigitGroup = New With {.Count = Group.Count(), .Digit = c, .Group = Group}
Order By DigitGroup.Count Descending, DigitGroup.Digit
Dim numCount = counts.FirstOrDefault(Function(grp) grp.Digit.ToString() = num.ToString())
If numCount IsNot Nothing Then
Dim numMessage = String.Format("There are {0} number {1}'s found.", numCount.Count, num)
MessageBox.Show(numMessage)
Else
MessageBox.Show("Your number does not contain a " & num)
End If
Else
MessageBox.Show("Please enter a number between 0 and 9.")
End If
End Sub
Private Sub btnGetNumber_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetNumber.Click
btnEnter.Enabled = True
i = 0
Do Until i > 100
Dim randomInt = rnd.Next(0, 100000)
i = i + 1
i = rnd.Next(0, 100000)
Loop
End Sub
End Class
First of all, it is common to use For Loops when you know the number of loops.
Secondly, you forgot to increment i in the until loop
Finally, you don't need to redeclare rnd in every loop. Something like that sounds better to me :
Dim rnd As New Random()
For i = 1 To 100
Dim randomInt = rnd.Next( 0 , 100000 )
Next
Move the New Random() out of that loop. Make it global and create the instance just one time.
(The Random generator starts using a seed obtained from the current time. Declaring a Random variable inside a loop result in the same seed used again and again. This gives back the same number defeating the randomness of the function) It is like: http://xkcd.com/221/
See another explanation here
Of course, if you don't increment the variable i used to control the loop, you will loop forever
Dim i As Integer
Dim rnd As New Random()
.....
i = 0
Do Until i > 100
Dim randomInt = rnd.Next(0, 100000)
i = i + 1
Loop
Said that, now I can't get what are you trying to do here. There is no array to check and you do not use the value obtained from the Random generator, simply, your i variable exits with value 101.
Now I am just guessing what are your intentions, but perhaps you want just this?
i = rnd.Next(0, 100000)
This will give to the variable i a random number and your subsequent code checks how many, of the required digit, are present in i
I see that you are not adding the variable "i" to increment:
i = 1
Do Until i > 100
Dim rnd As New Random()
Dim randomInt = rnd.Next(0, 100000)
i+=1 'Increment value of i by 1, same as i = i + 1
Loop
The variable of "i" will always be 1 if not incremented. Check that and let me know if that solves the problem!