Hej jeg har brug for gentagne gange at trække et tilfældigt nummer uden at det trukne nummer gentages. Generatoren skal bruges til en Quiz. Jeg har uden held forsøgt at få denne rutine til at virke, men af og til kommer det samme nummer igen. Nogen der kan gennemskue hvad der er galt?
Randomize() Antal = Tabel1BindingSource.Count Lantal.Text = Antal
Dim C As New Collection, I As Integer For I = 1 To Antal C.Add(CStr(I), CStr(I)) Next I I = Int(Rnd() * C.Count + 1) Tabel1BindingSource.Position = (C.Item(I)) C.Remove(I)
Imports System Imports System.Collections.Generic Imports System.Linq
Namespace E Public Class Program Private Shared rng As New Random() Public Shared Function Bad(n As Integer, min As Integer, max As Integer) As List(Of Integer) Dim res As New List(Of Integer)() For i As Integer = 0 To n - 1 res.Add(rng.Next(min, max + 1)) Next Return res End Function Public Shared Function Good1(n As Integer, min As Integer, max As Integer) As List(Of Integer) Dim res As New List(Of Integer)() For i As Integer = 0 To n - 1 Dim v As Integer Do v = rng.Next(min, max + 1) Loop While res.Contains(v) res.Add(v) Next Return res End Function Public Shared Function Good2(n As Integer, min As Integer, max As Integer) As List(Of Integer) Dim res As New List(Of Integer)() For i As Integer = min To max res.Add(i) Next Return res.Select(Function(v) New Tuple(Of Integer, Integer)(v, rng.Next())).OrderBy(Function(r) r.Item2).Select(Function(r) r.Item1).Take(n).ToList() End Function Public Shared Sub Main(args As String()) Console.WriteLine("Wrong:") For Each v As Integer In Bad(5, 1, 10) Console.WriteLine(v) Next Console.WriteLine("Check for duplicate:") For Each v As Integer In Good1(5, 1, 10) Console.WriteLine(v) Next Console.WriteLine("Shuffle:") For Each v As Integer In Good2(5, 1, 10) Console.WriteLine(v) Next Console.ReadKey() End Sub End Class End Namespace
Synes godt om
Ny brugerNybegynder
Din løsning...
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.