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

Random Number add up to a defined number using PowerShell

PowerShell 专家您好,

我正在编写一个简单的代码,生成一个产品和任务列表(一个产品有多个任务)以及花费的时间 "Randomly"。我希望 totalTime 将时间加起来为 40(整数)(并且可以根据用户定义进行更改,例如 50 、 60 等)。

代码运行良好,但加起来不等于 40。你能帮忙吗?

奖励:我可以为产品或任务分配权重,以便在随机选择发生时获得优先级吗?例如我想花更多的时间在 P3 和 P7 上,以及 T3、T12 和 T15。时间加起来应该还是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
    }
}

下面是我得到的输出:

$totalTime 移出将起作用的 FOR 循环..

#######
$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
    }
}
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"

    }
}