View Single Post
 
Old 11-30-2014, 08:32 AM
naton naton is offline
Freshman
 
Join Date: Aug 2004
Posts: 30
Default Seed, Class and shared Random

Hi there,

Let's say that a have a Car class and a FleetOfCars class. I want each car in the fleet to have a different engine power. For this I added to the class Car a member variable rnd of type Random.

In order to have the same behavior whenever I run my program (mainly for debugging reason), I did the following :

Code:
Class Car
   private power as Double
   private shared rnd as Random = new Random (1234)

   Public Sub New(Byval maxPower as Double)
      power = rnd * maxPower
   End Sub

   Public Function MyPower() as String
      Return power.ToString
   End Function
End Class

Class FleetOfCar
   private cars() as Car
   private maxPower as Double = 300
   
   Public Sub New(Byval numberOfCars as Integer)
      ReDim cars(numberOfCars - 1)

      For i as Integer = 0 to numberOfCars - 1
         cars(i) = New Car(maxPower)
      next
   End Sub

   Public Sub PrintCarsSpecs()
      Dim str as String

      For i as Integer = 0 to Cars.GetUpperBound(0)
         str = str + "Car" + i.ToString + " : power " + Cars(i).MyPower + VbNewLine
      Next

      MsgBox(str)
   End Sub
End Class

Public Sub Main()
   Dim MyFleetOfCars as FleetOfCars = New FleetOfCars(20)
   MyFleetOfCars.PrintCarsSpecs()
End Sub
Every time I run the sub Main() of the above code I will have the same sequence of power. Now and here is where I'm struggling, I want to automate the code so it runs several times without having to re-execute Main() each time. How can I get the program to print the same sequence of cars' power if I change the sub Main() into the one below:

Code:
Public Sub Main()
   For i = 0 to 10
      Dim MyFleetOfCars as FleetOfCars = New FleetOfCars(20)
      MyFleetOfCars.PrintCarsSpecs()
   Next 
End Sub
Thanks.

Last edited by naton; 12-01-2014 at 02:29 AM.
Reply With Quote