我如何随机化文本文件的内容?

时间:2012-11-21 18:07:43

标签: vb.net random text-files

我需要随机化文本文件中的所有行,然后通过替换相同的文本文件来保存未排序的行。

我怎么能做到这一切?

3 个答案:

答案 0 :(得分:2)

Dim filepath as String = "text_path"
Dim arr() As String = File.ReadAlllines(filepath)
Dim a As Random
Dim b(str.Length) As Integer
Dim result=1, c As Integer

    File.Delete(filepath)
Dim f As StreamWriter = File.AppendText(filepath)

    For i = 0 To str.Length
    while(result)
        result = 0
        c = a.Next(0, str.Length)
        For j = 0 To b.Length
            If b(j) = c Then result = 1
        Next
    end while
        f.WriteLine(arr(c))
    Next
    f.Close()

答案 1 :(得分:1)

以下是我的看法:

Dim linesList As New List(Of String)(IO.File.ReadAllLines("filepath"))
Dim newLinesList As New List(Of String)
Randomize()
While linesList.Count > 0
  Dim randomIndex As Integer = Math.Floor(Rnd() * linesList.Count)
  newLinesList.Add(linesList(randomIndex))
  linesList.RemoveAt(randomIndex)
End While
IO.File.WriteAllLines("filepath", newLinesList.ToArray)

答案 2 :(得分:1)

另一种观点:

Imports System.IO

Module Module1

    Sub CreateFile(destFile As String)
        Using sw = New StreamWriter(destFile)
            For i = 1 To 200
                sw.WriteLine("Line " & i.ToString)
            Next
        End Using
    End Sub

    Function RandomList(nNumbers As Integer) As List(Of Integer)
        ' generate a List of numbers from 0..nNumbers-1 in a random order.
        Dim ns As New List(Of Integer)
        Dim rnd As New Random
        For i = 0 To nNumbers - 1
            ns.Insert(rnd.Next(0, i + 1), i)
        Next
        Return ns
    End Function

    Sub RandomiseFile(srcFile As String)
        Dim lines = File.ReadAllLines(srcFile)
        Dim nLines = lines.Count
        Dim randomNumbers = RandomList(nLines)
        ' use a temporary file in case something goes wrong so that
        ' the original file is still there.
        Dim tmpFile = Path.GetTempFileName()
        ' output the lines in a random order.
        Using sw = New StreamWriter(tmpFile)
            For i = 0 To nLines - 1
                sw.WriteLine(lines(randomNumbers(i)))
            Next
        End Using
        File.Delete(srcFile)
        File.Move(tmpFile, srcFile)
    End Sub

    Sub Main()
        Dim fileToUse As String = "C:\temp\makerandom.txt"
        CreateFile(fileToUse)
        RandomiseFile(fileToUse)
    End Sub

End Module