# Need help understanding % in Steelclaw Gap

I need help with understanding the % operator in this level, because it just doesn’t seem to make sense to me. This isn’t about finishing the level, as I already have, this is just understanding the code. My only thought is that maybe I’m not understanding what hero.built is actually doing? I’ve stripped it down to just the part I’m struggling to understand:

``````# This level introduces the % operator, also known as the modulo operator.
# a % b returns the remainder of a divided by b
# This can be used to wrap around to the beginning of an array when an index might be greater than the length

summonTypes = ["soldier", "soldier", "soldier", "soldier", "archer", "archer", "archer", "archer"]

# You start with 360 gold to build a mixture of soldiers and archers.
# hero.built is an array of the troops you have built, alive or dead
# Here we use "len(hero.built) % len(summonTypes)" to wrap around the summonTypes array

def summonTroops():
type = summonTypes[len(hero.built) % len(summonTypes)]
builtArrayLength = len(hero.built)
objectiveArrayLength = len(summonTypes)
hero.say(builtArrayLength % objectiveArrayLength)
if hero.gold >= hero.costOf(type):
hero.summon(type)

while True:
summonTroops()
``````

It’s my understanding that % (modulo) returns the remainder of two integers. In this example the two integers are the length of the “hero.built” array and the length of the “summonTypes” array.

The length of summonTypes is and will always be 8. The length of hero.built, however, starts at 0 and will increase by one for every unit that is built.

So to start things off, the first time through summonTroops(), the equation would look like this:

type = summonTypes[len(hero.built) % len(summonTypes)]

len(summonTypes) is always 8, and you have not previously built any troops so len(hero.built) is 0 because the array is empty, therefore:

type = summonTypes[0 % 8]

this works, because the remainder of 0/8 is 0, so summonTypes[0] is summoned.

This is where I get confused. On the next iteration it would be, type = summonTypes[1 % 8], but the remainder of 1/8 is still 0, so once again type = summonTypes[0].

This would be the case until you’ve summoned 9 units, at which point the remainder of 9/8 is 1. In that case type = summonTypes[1], but that’s still a soldier. In fact, mathematically, you’d have to summon 33 units before you get to the first archer.

So how is this ACTUALLY working?

nevermind, I’m a silly good. Because we’re talking remainders, then there are no fractions or decimals returned, only whole numbers, so the first series of 8 would always be 0 with a remainder of hero.built.

I’ve obviously been out of school for too long.

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.