I am currently working on a dice game programme agent in which the rules include that if there are two or more dice with the same value these values are flipped to the opposite numbers contributing to the overall score.
Currently I am trying to take the values from the dice as a tuple (e.g. 1,1,2), and return those same duplicates to the agent in the form of a dictionary at the same indexes provided to return the dice to be flipped.
I have hard coded in the values at the moment with the following function:
if state[0] == state[1] == state[2]:
duplicates = {}
duplicates[0] = state[0]
duplicates[1] = state[1]
duplicates[2] = state[2]
return duplicates
elif state[0] == state[1]:
duplicates = {}
duplicates[0] = state[0]
duplicates[1] = state[1]
return duplicates
elif state[1] == state[2]:
duplicates = {}
duplicates[1] = state[1]
duplicates[2] = state[2]
return duplicates
elif state[0] == state[2]:
duplicates = {}
duplicates[0] = state[0]
duplicates[2] = state[2]
duplicates = {}
return duplicates
Where state is the current dice. However I am trying to make a more general function which would account for e.g. 2 or 5 dice. Does anyone know how I can extract this info and store it in the duplicates dict at the same indexes a bit better please?
Thank you so much:)
There are many ways to find duplicates in a tuple/list, see How do I find the duplicates in a list and create another list with them?
in your particular case you can do, among many other things
count_reps = {}
for s in state:
count_reps[s] = count_reps.get(s,0)+1
duplicates = {n:s for n,s in enumerate(state) if count_reps[s] > 1}
we use a helper dictionary count_reps
where for each value in the tuple we store how many times it appears. Than we use it to populate duplicates
from state
eg for state = (2,2,3,3,1,2)
count_reps
looks like this:
{2: 3, 3: 2, 1: 1}
and duplicates
looks like
{0: 2, 1: 2, 2: 3, 3: 3, 5: 2}