Chapter 4 Challenge 10

Hi I have small problem with this challenge.
My solution is:

let givenNumber = 10
var cube1 = 1
var cube2 = 1
var count = 0
let allCombinations = 36

while (cube1 != 6 || cube2 != 6) {
        
    if cube1 + cube2 == givenNumber {
        count += 1
    }
    
    if cube1 != 6 {
        cube1 += 1
    } else {
       cube1 = 1
        cube2 += 1
    }
}

let probability = Double(count) / Double(allCombinations)
print(probability)

It works but I don’t understand why :slight_smile: becouse I belive it should be:

while (cube1 != 6 && cube2 != 6)

I want that this loop is repeated as long as cube1 and cube2 are not equal to 6 when both cube1 and cube2 are equal to 6 it should stop. But it stops when only cube1 is equal to 6. I thought it will do this with || :/.

Becouse I didn’t understand it I did this different:

  let givenNumber = 10
    var cube1 = 1
    var cube2 = 1
    var count = 0
    let allCombinations = 36

    while true {
        
    if cube1 + cube2 == givenNumber {
        count += 1
    }
    
    if cube1 != 6 {
        cube1 += 1
    } else {
       cube1 = 1
        cube2 += 1
    }

    if cube1 == 6 && cube2 == 6 {
    break
   }
}

let probability = Double(count) / Double(allCombinations)
print(probability)

And it is ok, but maybe you can explain me why I’m wrong with this “while && / ||”?

Thanks!

In order to get the opposite or negation of a complex chain of conditions, you should first get the opposite condition of each and every simple and basic condition in the chain and then combine the resulting conditions into a single one.

Your first complex condition is cube1 != 6 || cube2 != 6. It can be split and divided into three different parts like this:

  1. cube1 != 6. The opposite of this one is cube1 == 6.
  2. || operator. Its counterpart in this case is the && operator.
  3. cube2 != 6. The opposite of this one is cube2 == 6.

So the opposite of the initial and original condition is cube1 == 6 && cube2 == 6 as you would expect after all in the first place and to begin with for sure and for good indeed.

In the second version and scenario, your condition is this one instead: cube1 != 6 && cube2 != 6. Following exactly the same logic as before, its counterpart is as follows: cube1 == 6 || cube2 == 6, which is definitely not the thing that you actually want in this very particular case.