Skip to content
Advertisement

Can you use the value of a variable to select an already defined variable with that same name?

I’m trying to try something out for my AP statistics class where I need to randomly select five words from the lyrics of a song and calculate the average length of those strings. This is what I have so far: (There’s 297 lyrics but I don’t want to type all of those out if it won’t work)

JavaScript

What I can’t figure out is how to take the value in num1 to select one of the Strings named the same thing. I need to do that for all five selected random numbers.

I’m sure there’s a way to do this, but it’s my first year in a CS class and I can’t seem to find the answer anywhere.

Advertisement

Answer

Here is a suggestion.

  • put all the words in a List<String>
    (e.g. List<String> = new ArrayList<>())
  • Use Collections.shuffle to shuffle the list.
  • then take the first 5 entries.

Doing the above will guarantee you won’t repeat any word unless there are duplicates in the list.

Figuring out how to average the lengths is up to you.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement