Random number generator to array
(Moved to here, accidently posted in the wrong section)
Hi, I'm new to visual basic, I have 2010 express version.
I was wondering how to make a random number generator that generates 100 numbers, then puts those numbers in a file, then reads the numbers from that file. It sounds like a lot to do, so any help would be appreciated!
Re: Random number generator to array
For future reference, please don't post the same question twice. If you post in the wrong forum then use the Report Post icon to send a message to the mods and ask them to move it.
As for your question, it's not just one question. That's quite a few steps there. First of all, to generate random numbers, you would use the Random class. You would create one instance and then call the appropriate method, e.g. Next, of that one instance repeatedly to generate multiple random numbers. You could call that method inside a For loop to do it a specific number of times. If you want to populate an array then you can use the loop counter to specify the element to set.
To write to a file, you could either call File.WriteAllLines and pass the array, which will write the whole lot in one go, or you could create a StreamWriter and call WriteLine in a loop.
Likewise, you have choices for reading. You could call File.ReadAllLines, which will read the whole file into a String array. You would then have to convert that into an Integer array, which you could do in a loop or perhaps by calling Array.ConvertAll. Alternatively, you could create a StreamReader and then call ReadLine in a loop, converting as you go.
Re: Random number generator to array
Re: Random number generator to array
Code:
Public Class Form1
Public Shared rand As Random = New Random()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New System.Text.StringBuilder()
'write 100 random numbers to file
For x As Integer = 1 To 100
sb.AppendLine(rand.Next().ToString())
Next
System.IO.File.WriteAllText("random numbers.txt", sb.ToString().Trim())
'read 100 numbers into List(Of Integer)
Dim randomNumbers As New List(Of Integer)
System.IO.File.ReadAllLines("random numbers.txt").ToList().ForEach(Sub(x) randomNumbers.Add(Integer.Parse(x)))
End Sub
End Class
Re: Random number generator to array
Quote:
Originally Posted by
Mariner
... then puts those numbers in a file, then reads the numbers from that file...
Is there a particular reason for having the file in the middle of the process?
Re: Random number generator to array
Code:
Public Class Form1
Dim r As New Random
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim numbers() As Integer = Enumerable.Range(1, 100).Select(Function(x) r.Next(1, 101)).ToArray
IO.File.WriteAllLines("path", Array.ConvertAll(numbers, Function(x) x.ToString))
Dim savedNumbers() As Integer = Array.ConvertAll(IO.File.ReadAllLines("path"), Function(s) CInt(s))
End Sub
End Class