0

I have a HashMap<Character, Integer> that counts the frequencies of letters in a string, called freq. For example, if the word is PUPPY, then the map holds the values {P=3, U=1, Y=1}.

I am using this for a wordle-like game. When assigning yellow and green to the letters of a submitted guess, I am subtracting from the frequencies of the letters, so that there are not more colors assigned than letters.

So if the target word is PUPPY and the user guesses PRUNE, then the colors work fine for the first guess but the map values become {P=2, U=0, Y=1}. I need the frequencies to return to the original values.

I tried creating a second hashmap of the same kind and setting revert (my second hashmap) equal to freq, then setting freq equal to revert after the function is executed, but it retains its changed values.

1 Answer 1

3

Make a copy, modify it as you like then discard it:

Map<Character, Integer> originalFreq = ...;
while (<making guesses>) {
    Map<Character, Integer> guessFreq = new HashMap<>(originalFreq); // make fresh copy
    // modify guessFreq as you like - it will be discarded next loop iteration
}
Sign up to request clarification or add additional context in comments.

1 Comment

Figured out I could just use putAll() andd it worked. thanks

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.