ElektroStudios
ElektroStudios

Reputation: 20464

How I can randomize the content of a text file?

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?

Upvotes: 0

Views: 1022

Answers (3)

Andrew Morton
Andrew Morton

Reputation: 25013

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

Upvotes: 1

Victor Zakharov
Victor Zakharov

Reputation: 26424

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)

Upvotes: 1

Poya Eraghi
Poya Eraghi

Reputation: 117

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

Upvotes: 2

Related Questions