Search code examples
androidarraysrandom

Randomly Generating Sentences for Display


I have a few questions concerning the application I'm designing. I have many different routes I could try in order to get what I wanted, but I thought I would get suggestions instead of doing trial and error.

I'm developing a simple app that has one Game screen (activity) and a main menu to start the game. The game screen will have two buttons, "Next" and "Repeat". Every time "Next" is hit, a new sentence in a different language (with the english translation below it) will appear, audio will pronounce the sentence, and hopefully I can get a highlighter to highlight the part of the sentence being spoken. You can guess what the Repeat button does.

My question is, what do you guys think would be the best way to store these sentences so they can be randomly picked out? I thought about making an array of structures or classes with the English definition, audio, and sentence in each structure. Then using a random iterator to pick one out. However, it would take a long time to do this approach and I wanted to get some ideas before I tried it.

Also, I'm not sure how I would print the sentence and definition on the screen.


Solution

  • Using an array of structs/classes seems like that would be the normal way to go.

    Not really sure what you mean by a random iterator, but when picking out random sentences from the array of sentences, you might want to avoid repeats until you've gone through all the elements. To do that, you can make a second array of indices, select one at random from those, use the element that corresponds to that index, and remove that number from the array of indices.

    In Java, that would look something like

    ArrayList<Sentence> sentences;
    ArrayList<Integer> indices;
    Random rand;
    
    private void populateIndices() {
        for(int i = 0; i < sentences.size(); i++)
            indices.add(i);
    }
    
    public Sentence getNextSentence() {
        if(indices.isEmpty())
            populateIndices();
        int idx = rand.nextInt(indices.size());
        int val = indices.get(idx);
        indices.remove(idx);
        return sentences.get(val);
    }