2

I have written these two functions to get a random number 1 through 10 X number of times.

function randomNum(){
    $availableNums = 1..9
    $availableNums | Get-Random
}

function randNumXTimes($x){
    $global:rando = @()
    for($i; $i -lt $x; $i++){
        $rando += randomNum;
        $rando
    }
}

If I do the randomNum function it will always do what it looks like it should do, it will give me a random number 1 through 9.

Then I have this function randNumXTimes, if I run this function which calls the randomNum function it now produces random two digit numbers, they are only supposed to be single digit numbers.

What the heck?

Example results from randomNum: 6 7 2 7 8 2

Example results from randNumXTimes which simply runs the randomNum function X number of times...

(randNumXTimes 10): 7 12 20 25 30 36 43 45 51 53

My question is, WHY does this do this when it looks like it should only produce single digit numbers X number of times? How can I fix this?

shadow2020
  • 1,315
  • 1
  • 8
  • 30
  • 1
    you defined `$rando` as a **_global_** array and then added items to `$rando` **_without referring to the global scope. if you add `$rando.GetType()` just after your `$rando` line, you will see that it aint an array - it's an int. – Lee_Dailey Sep 13 '19 at 00:29

1 Answers1

1

Although you assign an empty array to $global:rando at the start of the function, you don't actually ever use it - please see the inline comments:

function randNumXTimes($x){
    # create global var "rando"
    $global:rando = @()
    for($i; $i -lt $x; $i++){
        # assign to local var "rando" - not the same as $global:rando
        # its type will be [int], which is why the numbers keep adding up
        $rando += randomNum;
        $rando
    }
}

The solution is simple, just don't rely on global variables:

function randNumXTimes($x) {
    for($i = 0; $i -lt $x; $i++){
        randomNum
    }
}

You could easily accomplish both things with a single function:

function Get-RandomDigit {
    param(
        [Parameter(Position = 0)]
        [ValidateRange(1,2147483647)]
        [int]$Count
    )

    for($i = 0; $i -lt $Count; $i++){
        1..9 |Get-Random
    }
}
mklement0
  • 382,024
  • 64
  • 607
  • 775
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206