0

how to find out the solution to this problem in python/java or any other language:

enter image description here

Thanks in advance

3
  • 1
    Doesn't really seem like a programming problem at all. It seems like a homework problem for a discrete math class. Commented Oct 27, 2020 at 18:37
  • @JohnColeman Yeah, i need hint :) Commented Oct 27, 2020 at 18:41
  • 1
    It would be easy enough to write a Python program which would brute-force the answer for small n. For reasons that I can't quite articulate, I suspect that the answer has something to do with Fibonacci numbers. Commented Oct 27, 2020 at 18:43

1 Answer 1

1

Since a program isn't a proof and you would still need to prove it, here is some Python code:

def zig_zag(seq):
    """tests if binary sequence seq satsifies zig-zag pattern"""
    for i in range(len(seq)-1):
        if (i%2 == 0 and seq[i] > seq[i+1]) or (i%2 == 1 and seq[i] < seq[i+1]):
            return False
    return True

def count_zig_zags(n):
    """counts the number of binary zig-zag patterns of length n"""
    count = 0
    for i in range(2**n):
        b = bin(i)[2:]
        if zig_zag(b): count += 1
    return count

For example:

>>> [count_zig_zags(n) for n in range(1,12)]
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]

A proof would be via strong induction.

Sign up to request clarification or add additional context in comments.

4 Comments

I think for the length 3, the output has to be 10, for example. Why 5?!
Is there any recursive solution?
How could the output for n = 3 be 10? 2^3 = 8, so even with no restrictions on the binary sequences it would have to be <= 8. The 5 binary sequences that satisfy the constraints are 000, 010, 011, 110, 111.
For a recursive solution, note that a valid solution of length n can be extended to a valid solution of length n+1 in either 1 way or 2 ways, and that the number that can be extended in 2 ways is the same as the number of valid sequences of length n-1 (proof, which seems to require 2 cases depending on whether n is even or odd, not given).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.