วันพุธที่ 14 พฤษภาคม พ.ศ. 2557

สุ่มแบบไม่ซ้ำใน vb.net ใน Array

Imports System.Security.Cryptography 

Public Class ArrayUtilities
    
Private Random As RNGCryptoServiceProvider = New RNGCryptoServiceProvider
    Private Bytes(4) As Byte 

    Public
 Function ShuffleArray(ByVal argArr As Array) As Array
        Dim FirstArray As New ArrayList(argArr)
        Dim SecoundArray As Array = Array.CreateInstance(GetType(Object), FirstArray.Count)
        Dim intIndex As Integer
        For
 i As Integer = 0 To FirstArray.Count - 1
            intIndex = RandomNumber(FirstArray.Count)
            SecoundArray(i) = FirstArray(intIndex)
            FirstArray.RemoveAt(intIndex)
        Next
        FirstArray = Nothing
        Return SecoundArray
    End Function 

    Private
 Function RandomNumber(ByVal argMax As Integer) As Integer
        If
 argMax <= 0 Then Throw New Exception
        Random.GetBytes(Bytes)
        Dim intValue As Integer = (BitConverter.ToInt32(Bytes, 0)) Mod argMax
        If intValue < 0 Then intValue = -intValue
        Return intValue
    End Function
End
 Class 

Module
 Module1
    Sub Main()
        Dim AU As ArrayUtilities
        AU = New ArrayUtilities
        Dim GivenArray As Integer() = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
        Dim NewArray As Array = AU.ShuffleArray(GivenArray)
        Dim i As Integer
        Dim
 stb As New System.Text.StringBuilder
        stb.Append("GivenArray = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}")
        stb.Append(vbCrLf)
        stb.Append(
"NewArray = {")
        For i = 0 To NewArray.Length - 2
            stb.Append(NewArray(i).ToString)
            stb.Append(
", ")
        Next
        stb.Append(NewArray(NewArray.Length - 1).ToString)
        stb.Append(
"}")
        Console.Write(stb.ToString)
        Console.Read()
    End Sub
End
 Module 

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

การใช้ WebClient สำหรับเรียก URL

Dim _url As String = " https :// www . MyDomain . com /?q=ทดสอบ " Dim wc As New System . Net . WebClient () wc . Encodin...