简体   繁体   English

如何从文件中的句子创建随机字符串轮换?

[英]How to create a random string rotation from senteces in a file?

How would I create a specific order of sentences with sentences that are in a file in random ways?如何使用随机方式在文件中的句子创建特定顺序的句子? For example: imagine i have a txt file with " bananas oranges apples peaches "例如:假设我有一个带有“香蕉橙苹果桃子”的 txt 文件

I would want to create an array with "oranges, apples, peaches, bananas", "apples, peaches, bananas, oranges" and so on.我想用“橙子、苹果、桃子、香蕉”、“苹果、桃子、香蕉、橙子”等创建一个数组。 It's like making them re-organize in a new random order and store it to either a new file or an array or whatever.这就像让它们以新的随机顺序重新组织并将其存储到新文件或数组或其他任何东西。 My main problem is making a new random order every time.我的主要问题是每次都下一个新的随机订单。 How would I do this?我该怎么做?

The code i've written so far only returns what I have in the file by order.到目前为止,我编写的代码仅按顺序返回文件中的内容。

private static void sendSentences() {
        String sentence;
        try{
            try(
                    InputStream fis = new FileInputStream("C:\\Users\\.....tweets.txt");
                    InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
                    BufferedReader br = new BufferedReader(isr);
            ){
                while ((sentence = br.readLine()) != null){
                    sendTweet(sentence, thandle);
                    System.out.println("sent " + sentence + ".");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

Here's an outline of a solution using Fisher-Yates shuffle algorithm .这是使用Fisher-Yates shuffle algorithm的解决方案的概要。 The idea is to calculate a hash for each generated random order and use that hash to check that order is not repeated这个想法是为每个生成的随机订单计算 hash 并使用该 hash 来检查订单是否重复

public static void main(String[] args) {
    String[] words = new String[] {"bananas", "oranges", "apples", "peaches"};
    int randomCount = 10; //this needs to <= (words.length)!

    Iterator<String[]> randomIterator = new Iterator<>() {
        Set<Integer> hashes = new HashSet<>();

        @Override
        public boolean hasNext() {
            return hashes.size() < randomCount;
        }

        @Override
        public String[] next() {
            int i = words.length;
            while(i > 1) {
                i--;
                int j = new Random().nextInt(i + 1);
                String temp = words[i];
                words[i] = words[j];
                words[j] = temp;
            }
            int h = Arrays.hashCode(words);
            if(hashes.contains(h)) next();
            hashes.add(h);
            return words;
        }
    };

    int c = 1;
    while(randomIterator.hasNext()) {
        System.out.println(c++ +  " "  + Arrays.toString(randomIterator.next()));
    }
}

This outputs:这输出:

1 [apples, oranges, bananas, peaches]
2 [apples, peaches, bananas, oranges]
3 [oranges, apples, peaches, bananas]
4 [bananas, peaches, oranges, apples]
5 [bananas, oranges, apples, peaches]
6 [oranges, bananas, apples, peaches]
7 [apples, bananas, peaches, oranges]
8 [peaches, apples, oranges, bananas]
9 [peaches, oranges, bananas, apples]
10 [bananas, apples, peaches, oranges]

Using an iterator, we can ensure that the shuffling algorithm is executed only as many times as needed before we have to repeat a pattern.使用迭代器,我们可以确保在我们必须重复一个模式之前,只根据需要执行洗牌算法的次数。 You can change the input/output mechanism to your desired method.您可以将输入/输出机制更改为您想要的方法。

This can be improved depending on use case.这可以根据用例进行改进。 For example, you can empty the hashes set when all the patterns are generated once and avoid a StackOverflow Error error by going over n!例如,您可以在所有模式生成一次时清空哈希集,并通过遍历n!来避免StackOverflow Error错误! repetitions.重复。 You can also use a List instead of an Array and use Collections.shuffle() to get a new random order as the other answer suggests.您还可以使用List而不是Array并使用Collections.shuffle()来获得新的随机顺序,如另一个答案所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM