如何随机化文本文件的内容? [英] How I can randomize the content of a text file?

查看:46
本文介绍了如何随机化文本文件的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

另一个问题:

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

这篇关于如何随机化文本文件的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆