随机数使用PowerShell加起来定义一个数字

时间:2016-03-24 19:13:08

标签: powershell powershell-v3.0

Hello PowerShell专家,

我正在研究一个简单的代码,它产生一个产品和任务列表(一个产品有几个任务),其上花费时间"随机"。我希望totalTime将时间加起来为40(整数)(并且可以根据用户定义更改,例如50,60等)。

代码工作正常,但它不会加起来40。你能帮忙吗?

加分:我可以为产品或任务分配权重,以便在随机选择发生时获得优先权吗?例如我想在T3,T12和T15上花更多时间在P3和P7上。时间仍然应该达到40。

cls
[int]$totalTime = 40 # This will be the number that the TotalTime Adds up

$taskCategories = @("T1"
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15")

$products = @("P1"
, "P2"
, "P3"
, "p4"
, "P5"
, "P6"
, "P7"
, "P8"
, "P9"
, "P10")

for ($i = 0; $i -le 1; ++$i)
{
    $totalTime = 0
    while ($totalTime -lt 40)
    {
        [int]$task = Get-Random -Minimum 0 -Maximum 16
        [int]$product = Get-Random -Minimum 0 -Maximum 11
        $time = Get-Random -Minimum 4 -Maximum 10

        Write-Output "$($products[$product])`t$($taskCategories[$task])`t$time"
        $totalTime = $totalTime + $time
    }
}

以下是我得到的输出:

enter image description here

2 个答案:

答案 0 :(得分:1)

$totalTime移出FOR LOOP,这将有效..

#######
$totalTime = 0
#######

for ($i = 0; $i -le 1; ++$i)
{
    while ($totalTime -lt 40)
    {
        [int]$task = Get-Random -Minimum 0 -Maximum 16
        [int]$product = Get-Random -Minimum 0 -Maximum 11
        $time = Get-Random -Minimum 4 -Maximum 10

        Write-Output "$($products[$product])`t$($taskCategories[$task])`t$time"
        $totalTime = $totalTime + $time
    }
}

答案 1 :(得分:1)

cls
[int]$totalTime = 40 # This will be the number that the TotalTime Adds up

$taskCategories = @("T1", "T2", "T3", "T4", "T5", 
                    "T6", "T7", "T8", "T9", "T10", "T11", "T12", "T13", "T14", "T15")

$products = @("P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9", "P10")

$totalTime = 0
$MinValue = 4

for ($i = 0; $i -le 1; ++$i)
{

    while ($totalTime -lt 40)
    {
        if (40 - $totalTime -ge 10)
        {
        $MaxValue = 10
        }
        else 
        {
        $MaxValue = 40 - $totalTime
        }

        if ($MinValue -lt $MaxValue)
        {
        $MinValue = 4
        }
        else
        {
        $MinValue = $MaxValue
        }


        [int]$task = Get-Random -Minimum 0 -Maximum 15
        [int]$product = Get-Random -Minimum 0 -Maximum 10
        if ($MinValue -eq 4)
        {
        $time = Get-Random -Minimum $MinValue -Maximum $MaxValue
        }
        else
        {
        $time = $MaxValue
        }
        $totalTime = $totalTime + $time
        $Remainder = 40 - $totalTime
        if ($Remainder -le 3)
        {
        $time = $time + $Remainder
        $totalTime = $totalTime + $time
        }

        Write-Output "$($products[$product])`t$($taskCategories[$task])`t$time"

    }
}