Swift - Hard to explain, little mathy function

51 views Asked by At

Ok so heres the deal, I'm trying to make a function that checks if the amount of player moves is equal to a number with a factor of 12. (like 12, 24, 36, and 48 and so on.)

This is what I've got so far:

//Changables
var playerMoves = 0
var solidNumbers =[ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "and So on"]

//Functions
func checkForPlayerMovesEqual12() {
//What a very long function name XD

if playerMoves / 12 == solidNumbers {
    //Do this } else {
//Do this if else }

Another Explanation of what I'm trying to do:

So I'm trying to find out a way to check if the total Player Moves is divisible by 12 ( like 48/12 = 3 , and only to run if the answer has no decimals, so 3.0, 1.0 work & 2.4, 4,8 doesn't work) and if it is it will do ___.

Thanks, may have explained it a little confuzzling.

2

There are 2 answers

0
ndmeiri On BEST ANSWER

Your condition should test to see if division by 12 leaves no remainder. In code, that would look like this:

if playerMoves % 12 == 0 {
    // do this
} else {
    // do something else
}

You do not need your solidNumbers array.

0
nhgrif On

What you're looking for is the modulo operator.

Given integers a and b, the result of a % b will give you c would would be the remainder if you did integer division.

For example:

15 % 12 // 3
12 % 12 // 0
 6 % 12 // 6
17 % 12 // 5
24 % 12 // 0
33 % 12 // 9

So if you want to find even multiples of 12, just look for any case where variable % 12 == 0.