How to find minNumber of operations such that binary string of length N is all zeros?

Question:

How to find minNumber of operations such that binary string of length N is all zeros?

choose two adjacent character and replace both of them with their xor value.

for example take binary string "101"

pick 1st and 2nd and xor => 111

pick 1st and 2nd and xor => 001

pick 2nd and 3rd and xor => 011

pick 2nd and 3rd and xor => 000

so the minimum number of operations is 4

here is my attempt

def checkAllZeros(astr):
    for each_char in astr:
        if each_char == 1:
            return False
    return True


def getMinOperations(astr):
    totalOps = 0
    while checkAllZeros(astr):
        i = 0
        j = 1
        if j < len(astr):
            if (astr[i] == '0' and astr[j] == '1') or (astr[i] == '1' and astr[j] == '0'):
                astr = astr[0:i] + '11' + astr[i + 2:]
                totalOps += 1
            elif astr[i] == '1' and astr[j] == '1':
                astr = astr[0:i] + '00' + astr[i + 2:]
                totalOps += 1
                i += 1
                j += 1
            else:
                i += 1
                j += 1


if __name__ == '__main__':
    print(getMinOperations('1111'))

I am assuming this requires dynamic programming? somehow it doesnt work on big strings

Asked By: user1870400

||

Answers:

update:

we can break it down like this:

’00’ -> 0 (times)

’01’ -> 2

’10’ -> 2

’11’ -> 1

so the answer can be this:

astr = '1101010010111'
operations = 0
operations += astr.count('11')
astr = astr.replace('11', '')
operations += sum(list(map(int, astr))) * 2
print(operations) # 10

How to define an ‘operation’?

for example:

astr = '110111'
sumOne = sum(list(map(int, astr)))
operations = sumOne // 2 + sumOne % 2
print(operations) # 3

pick 1st and 2nd and xor => 000111

pick 4th and 5th and xor => 000001

pick 5th and 6th and and => 000000

so the minimum number of operations is 3

the problem is that whether find the index of ‘1’ using an ‘operation’

Answered By: scli
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.