简体   繁体   中英

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 "

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 . The idea is to calculate a hash for each generated random order and use that hash to check that order is not repeated

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! 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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