samedi 9 février 2019

Get random items from hashtable but the total of values has to be equal to a set number (Powershell)

I'm struggling big time at the logic I should use for this.

Trying to build a simple "task distributor" for the house tasks between me and my wife :) Although the concept will be really useful at work too so I need to learn it properly :)

My hashtable :

$Taches = @{
"Balayeuse plancher" = 20
"Moppe plancher" = 20
"Douche" = 15
"Litières" = 5
"Poele" = 5
"Comptoir" = 5
"Lave-Vaisselle" = 10
"Toilette" = 5
"Lavabos" = 10
"Couvertures lit" = 5
"Poubelles" = 5
}

The total value for all the items is 105 (minutes).

My goal :
I want to select random items from that list and build two different hashtables - one for me and my wife, each having a total value of 50 (So it's fair :)). For example 20+20+10 or 5+5+5+15+20, etc.

What would be the best option?

For now I successfully achieved a random hashtable of a total value of 50 like this :

do {
$Me = $null
$sum = $null
$Me = @{}
$Me = $Taches.GetEnumerator() | Get-Random -Count 5 
$Me | ForEach-Object { $Sum += $_.value }
} until ($sum -eq 50)

Result example :

Name                           Value                                                                                                                                  
----                           -----                                                                                                                                  
Poubelles                      5                                                                                                                                      
Balayeuse plancher             20                                                                                                                                     
Douche                         15                                                                                                                                     
Poele                          5                                                                                                                                      
Toilette                       5       

It works but boy does it feel like it's a roundabout and crooked way of doing it. I'm sure there is a better approach?

Much appreciated as always.




Aucun commentaire:

Enregistrer un commentaire