Zigzag sequence is a sequence where every element is less or more than it's neighbours: 1 3 2
and 2 1 2
are zigzags, 1 2 3
and 1 2 2
are not.
With two numbers given n, k find out how many sequences of size n can be generated from numbers 1..k
Example: n = 3 k = 3 Answer: 10
121, 212, 131, 313, 232, 323, 132, 231, 312, 213 (no need to generate, just for clarity)
I came to this solution. Please, tell me if it can be done better.
import sys
ZAG = {}
ZIG = {}
def zag(n, i):
result = 0
for j in xrange(1, i):
if (n - 1, j) not in ZIG:
ZIG[(n - 1, j)] = zig(n - 1, j)
result += ZIG[(n - 1, j)]
return result
def zig(n, i):
result = 0
for j in xrange(i + 1, MAX_NUMBER + 1):
if (n - 1, j) not in ZAG:
ZAG[(n - 1, j)] = zag(n - 1, j)
result += ZAG[(n - 1, j)]
return result
def count(n):
if n == 1:
return MAX_NUMBER
result = 0
for i in xrange(1, MAX_NUMBER + 1):
ZIG[(1, i)] = 1
ZAG[(1, i)] = 1
for i in xrange(1, MAX_NUMBER + 1):
result += 2*zag(n, i)
return result
def main(argv):
global MAX_NUMBER
MAX_NUMBER = int(argv[1])
print count(int(argv[0]))
if __name__ == "__main__":
main(sys.argv[1:])