2

I have a list of 1000 words. I need to load an array with n randomly chosen words from that list (no repeats allowed). What is the best way of going about doing that?

My ideas:

1) Load the words into R.arrays to create a String array. Use collections.shuffle to shuffle the array, then pull the first n entries from it. Right now, I am having memory issues loading the initial array with the 1000 words using this method.

2) Load the words into a text file, read each word into a String array. Use same method to get first n entries.

3) Hard code the input of the words into a String array (I'd use a script to get that output of course). Use same method to get first n entries.

Is there a better way?

1 Answer 1

1

If you're mainly worried about memory usage and you're willing to give up computation speed, here's an algorithm that will get you there.

Keep your words in a text file, one word per line, with a fixed amount of characters per word, padding each word with spaces at the end to ensure a fixed word char size, call it s.

  1. Create an array of max size n, call it w
  2. Open a stream reader to the file containing the 1000 words
  3. Get a random number between 1 and 1000, call it k
  4. Seek to position k*s in the file stream and grab the next s characters
  5. Add the word to w if it does not exist in the array yet
  6. If the w array is full (ie. size=n), we're done, otherwise go back to step 3

Let us know how it goes. Happy coding!

Sign up to request clarification or add additional context in comments.

2 Comments

That seems just crazy enough to work. Any idea why Android complains when I just load the strings directly from R.arrays? Do 1000 strings really take up that much memory?
Yes Strings are quite expensive. When memory is a concern I'd stay away from them as much as possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.