Question

I can not manage to find out how to do this in programming. I am using a language called chuck at the moment but you can help me with python.

i need a function that returns a value but at the same time advance or decrease by that value once is called, it needs to stay within a certain number also (like a modulo). I am explaining the code here:

variable named length = value 4

variable named play = value 0

function named advance
   return variable
   variable is advanced by one

function named goback
   return variable
   variable decrease by one

advance is called  --- return 0
advance is called  --- return 1
advance is called  --- return 2
advance is called  --- return 3
advance is called  --- return 0
decrease is called --- return 3
decrease is called --- return 2
decrease is called --- return 1
decrease is called --- return 0
decrease is called --- return 3

I hope it is clear, thanks!

Was it helpful?

Solution

The simplest way to do this would be with the help of temporary variables.

length = 4
play = 0

def advance():
    tmp = play
    play = play + 1
    return (tmp % length)

def decrease():
    tmp = play
    play = play - 1
    return (tmp % length)

Running this code with your example test cases should result in the same values being returned. My Python is a bit rusty so the syntax may not be 100% accurate, but the concept is there.

OTHER TIPS

I'm not familiar with either python or 'chuck', but based on your pseudo-code you seem to want something like:

function named advance
    variable := variable + 1
    return (variable - 1) mod length

function named goback
    variable := variable - 1
    return (variable + 1) mod length

If you need variable to stay within bounds at all times, take the mod length after decrementing\incrementing as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top