Tony
Tony

Reputation: 419

More efficient way to store values?

I'm thinking about making a math program. It will ask a random question from a set of questions, and then verify the answer. Here is what I have so far:

String[] questions = {"3 * 19", "21 * 9", "7 * 4", "349274 * 0", "16 / 2", "3 + 86", "5 - 9"};
int[] answers =      {57,        189,       28,         0,           8,       89,      -4};

(It is not normally spaced like this; I did it just to show which answers went with what question)

Is there a more efficient way of doing this (I'm only interested in storing the data, not retrieving it)?

Upvotes: 3

Views: 306

Answers (2)

fireshadow52
fireshadow52

Reputation: 6516

This should do it:

Map<String,Integer> map = new HashMap<String, Integer>(){{     
    put("3 * 19", 57);     
    put("21 * 9", 189);     
    put("7 * 4", 28);     
    put("349274 * 0", 0);
    put("16 / 2", 8);
    put("3 + 86", 89);
    put("5 - 9", -4); 
}};

A quick note from @Bruno Reis:

Just note that this creates an anonymous inner class that inherits from HashMap. Therefore, it has a (non-transient) reference to the instance of the class where it has been created, which might pose problems if you try to serialize the map.

UPDATE: Here is how you would retrieve the value of a random question:

Random generator = new Random();
Object[] values = map.values().toArray();
int randomAns = values[generator.nextInt(value.length)];  

Upvotes: 2

Adamski
Adamski

Reputation: 54697

My recommendation would be to create a dedicated class to store both the question and answer, store these in a List and use Collections.shuffle to shuffle the questions.

Using shuffle offers a far more uniform distribution of questions each time the application runs compared with relying on the order in which HashMap stores questions internally (which will most likely be the same for a given JVM implementation).

In addition, encapsulating the question and answer together is better from an OO-point of view IMO.

public class Question {
  private final String question;
  private final int answer;

  public Question(String question, int answer) {
    this.question = question;
    this.answer = answer;
  }

  public String getQuestion() { return question; }
  public int getAnswer() { return answer; }
}

Then populate list of questions, shuffle and iterate:

// Use ArrayList as it supports random access for efficient element swapping:
List<Question> questions = new ArrayList<Question>();

questions.add(new Question("3 * 19", 57));
// etc.

Collections.shuffle(questions);

for (Question qn : questions) {
  System.out.println(qn.getQuestion());
  // Prompt for answer, etc.
}

Upvotes: 2

Related Questions