Tirage au sort aléatoire

Skali-asta Messages postés 8 Date d'inscription dimanche 3 avril 2022 Statut Membre Dernière intervention 19 avril 2022 - 6 avril 2022 à 14:11
vb95 Messages postés 3474 Date d'inscription samedi 11 janvier 2014 Statut Contributeur Dernière intervention 7 mai 2024 - 6 avril 2022 à 14:59
Bonjour,

j'ai un ensemble des employés mais ils sont répartit sur plusieurs villes ( 6 au total)

je veux tirer aléatoirement 3 villes avec un tirage de 3,2,2 ou 2,2,3 ; l'essentiel de ne pas dépasser 7 au total mais tirer seulement 3 villes avec un quota min2 ou max 3

j'espère que j'ai bien expliqué ma contrainte

mon code initial me permet seulement de tirer aléatoirement 7 au total mais j'ai besoin de le modifier afin de respecter ma 2 contrainte

merci d'avance
voilà mon code :
Sub planning()

Const LIMIT = 1000000 ' limit iterations to solve

Dim wb As Workbook, ws As Worksheet
Dim lastrow As Long
Dim dict As Object, key, bLoop As Boolean
Dim n As Long, x As Long, sType As String

Set dict = CreateObject("Scripting.Dictionary")
dict.Add "W", 7
dict.Add " ", 0

Set wb = ThisWorkbook
Set ws = wb.Sheets("planning")
bLoop = True
With ws
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("C2:C" & lastrow).Cells.Clear

Do While bLoop

' select random row
x = lastrow * Rnd() + 1
sType = Trim(.Cells(x, "B"))

' check if needed
If Len(.Cells(x, "C")) = 0 And dict(sType) > 0 Then
.Cells(x, "C") = "W"
dict(sType) = dict(sType) - 1

' check if finished
bLoop = False
For Each key In dict
If dict(key) > 0 Then bLoop = True
Next
End If

' avoid infinite loop
n = n + 1
If n > LIMIT Then
For Each key In dict.keys
Debug.Print key, dict(key)
Next
MsgBox "Too many iterations to solve", vbCritical, "limit=" & LIMIT
Exit Sub
End If
Loop
End With
MsgBox "Done in " & n & " iterations", vbInformation
End Sub
A voir également:

1 réponse

vb95 Messages postés 3474 Date d'inscription samedi 11 janvier 2014 Statut Contributeur Dernière intervention 7 mai 2024 169
6 avril 2022 à 14:59
Bonjour
Déjà en premier pour poster du code il serait bien de suivre ce tuto : https://codes-sources.commentcamarche.net/faq/11288-les-balises-de-code .
Ainsi votre code serait bien plus agréable à lire .
Maintenant désolé mais je n'ai pas compris les contraintes de votre tirage aléatoire
0
Rejoignez-nous