Search code examples
python-3.xdice

Python Dice : Avoiding Triple Repetitions


I got this DICE puzzle to solve and my mind is stuck on a scenario.


How many times did it occur in the trial, that exactly two 6 were rolled after each other? For example, in sequence 56611166626634416 it occurred twice, that exactly two 6 were thrown after each other.


Question is: how to avoid letting the counter count those 666.

Note: I have tried multiple trackers (keys), but then I have another issue which is:

IndexError: list index out of range

Throws=[6,6,2,6,6,6,3,6,6,3,6,6,6]
Counter_6 = 0
X=0


for i in range (0,len(Throws)):

    if i==len(Throws) or i+1>len(Throws) or i+2>len(Throws):
        key1= Throws[i]
        key2=0
        key3=0

    elif i+2>=len(Throws):
        key1 = Throws[i]
        key2 = Throws[i + 1]
        key3 = 0

    else:
        key1=Throws[i]
        key2 = Throws[i + 1]
        key3 = Throws[i + 2]
    print("key 1 is", key1)
    print("key 2 is", key2)
    print("key 3 is", key3)

    if key1==6 and key2==6 and key3!=6 and X==0:
        Counter_6 = Counter_6 + 1
        X=1
    elif key1!=6 and key2 ==6 and key3==6 and X==0:
        Counter_6 = Counter_6 + 1
        X=1
    elif key1==6 and key2==6 and key3==6:
        Counter_6 = Counter_6
        X=0

print("number of double 6 are: ",Counter_6)

Counter should be equal to 2


Solution

  • Here's easy and efficient solution without using any extending libraries. We define stack that is equal to amount of consecutive 6's we've seen, every time any digit other than 6 occur (or after looping over our throws) we check whether stack is equal to 2, if so we increment our counter_6 and reset stack to 0.

    throws = [6,6,2,6,6,6,3,6,6,3,6,6,6]
    counter_6 = 0
    stack = 0
    
    for i in throws:
        if i == 6:
            stack += 1
        else:
            if stack == 2:
                counter_6 += 1
            stack = 0
    if stack == 2:
        counter_6 += 1
    
    print(counter_6) # --> 2