Function GetSingleValue(ByRef aArr() As String, sResult As String) As Boolean If UBound(aArr) = 0 Then ' reste rien GetSingleValue = False Else GetSingleValue = True ' on récupère un index Dim Index As Long Index = Int((UBound(aArr) * Rnd) + (LBound(aArr) + 1)) ' on récupère la valeur sResult = aArr(Index) ' on écrase la position par la dernière valeur et on supprime la dernière position aArr(Index) = aArr(UBound(aArr)) ReDim Preserve aArr(UBound(aArr) - 1) End If End Function ' EXEMPLE D'UTILISATION (nécessite un bouton et une textbox) Option Explicit Dim aMyArray() As String 'attention, la premier index (0 ici) ne sera pas utilisé ' ' Private Sub Form_Load() ' applique le facteur "aléatoire" Randomize Timer ' redimension et remplissage du tableau Dim i As Long ReDim aMyArray(0 To 10) For i = LBound(aMyArray) + 1 To UBound(aMyArray) aMyArray(i) = "chaîne [" & CStr(i) & "]" Next i ' pour le test.... Text1.Width = 2895 Text1.Text = vbNullString End Sub ' ' Private Sub Command1_Click() Dim sRet As String If GetSingleValue(aMyArray, sRet) Then Text1.Text = sRet Else Text1.Text = "Toutes les valeurs ont été piochées" End If End Sub
public static bool GetSingleValue(List<string> list, out string value) { value = null; // Return false if the array is empty if (list.Count == 0) return false; else { int lastElementIndex = list.Count - 1; int index = _rand.Next(0, lastElementIndex); value = list[index]; // Return a randomed value list[index] = list[lastElementIndex]; // Replace with the last element list.RemoveAt(lastElementIndex); // Delete the last element return true; } }
import java.util.*; public static String randomize (Vector<String> array) { if (array == null || array.isEmpty ()) return null; Random random = new Random (); random.setSeed (System.currentTimeMillis ()); int index = random.nextInt (array.size ()); return array.get (index); }
import random def get_random_and_pop(liste): if not liste: return -1 position = random.randrange(len(liste)) valeur = liste.pop(position) return valeur, liste # exemple liste = range(50) valeur, liste = get_random_and_pop(liste) print valeur print liste
var tab=[1,2,3,4,5,6,7,8,9,10]; var valeur_extraite=tab[Math.round(Math.random()*tab.length)];
Private _rand As New System.Random Public Function GetSingleValue(ByVal list As List(Of String), ByRef value As String) As Boolean Dim result As Boolean = False value = String.Empty If (list.Count > 0) Then Dim lastIdx As Integer = list.Count - 1 Dim idx = _rand.Next(0, lastIdx) Value = list(idx) 'retourne une valeur aléatoire list(idx) = list(lastIdx) 'remplace par le dernier élément list.RemoveAt (lastIdx) 'efface le dernier élément result = True End If Return result End FunctionBy Renfield