How I can randomize the content of a text file?

与世无争的帅哥 提交于 2019-12-25 00:19:10

问题


I need to randomize ALL the lines inside a text file and then save the unsorted lines by replacing the same text file.

How I can do all that?


回答1:


Another take on it:

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



回答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()



回答3:


Here is my take on it:

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)


来源:https://stackoverflow.com/questions/13499409/how-i-can-randomize-the-content-of-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!