ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Random (https://www.excelbanter.com/excel-programming/394816-random.html)

smandula

Random
 
Could someone help with a VBA code - to compute
random integers for Col B1 .. L1 with repeated integers.

With thanks


Rick Rothstein \(MVP - VB\)

Random
 
Could someone help with a VBA code - to compute
random integers for Col B1 .. L1 with repeated integers.


How big can the integers be at maximum? Is zero the smallest integer you can
have, or can there be negative values (if so, what is the biggest negative
integer you can have)? By the way, did you really mean to say "with repeated
integers" or did you perhaps mean 'without'?

Rick


smandula

Random
 
Thanks for replying. Usually, repeats are not wanted in a small
series.
In this case number 1 to 5.

Sub rndNo()
Dim str As String

For i = 1 To 5
str = str & Int((5 - 1 + 1) * Rnd + 1) & vbCrLf
Next i

MsgBox str
End Sub

I need to favour a certain number i.e. 3 so it would come out more
often,
in this series of 11 quess' and be displayed across Cols B1 to L1

With Thanks


Rick Rothstein \(MVP - VB\)

Random
 
Thanks for replying. Usually, repeats are not wanted in a small
series.
In this case number 1 to 5.

Sub rndNo()
Dim str As String

For i = 1 To 5
str = str & Int((5 - 1 + 1) * Rnd + 1) & vbCrLf
Next i

MsgBox str
End Sub

I need to favour a certain number i.e. 3 so it would come out more
often,
in this series of 11 quess' and be displayed across Cols B1 to L1


You might try code something like this...

Dim X As Long
Dim Choices As Variant
Choices = Array(1, 3, 2, 3, 3, 3, 4, 3, 5, 3)
For X = 0 To 10
Range("B1").Offset(0, X).Value = _
Choices(Int((1 + UBound(Choices) - LBound(Choices)) * Rnd))
Next

What I have done is placed the numbers 1 through 5 into an array named
Choices; however, I added extra 3's into the mix. The numbers I assigned to
the array are the 10 numbers 1,3,2,3,3,3,4,3,5,3. The code works by
generating a random array index (0 to 9) and assigning the array's value at
that random index to the cells you indicated. This should make assigning the
number 3 a little more than twice as likely as any of the other numbers. You
can adjust the likelihood of the number 3 coming by varying how many extra
ones of them you place in the array via the Array function (the rest of the
code will adjust automatically around this assignment). By the way, the
order you assign values to the elements of the Choices array is immaterial
as you will randomly be picking the index numbers.

Rick


smandula

Random
 
That's an excellent approach to a difficult problem
I don't know how you came up with the answer.
But, I like it.
I wanted to use random but not random.

Many Many Thanks




All times are GMT +1. The time now is 12:27 AM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com