I have a row of bits:
001111000000000
And i want to flip all of these so that they're false, but I only have a set number of commands to do this, these commands look like this:
3, 5, 7, 11, 13, 17, 19 ... (prime numbers, excluding 2)
Each command flips the corresponding amount of bits using the NOT operator (0 becomes 1 and 1 becomes 0). My goal is to use the lowest amount of commands to achieve this.
Note that there is always enough space "after" the last 1 in our row of bits for us to complete the task.
Example Problem:
000000011000000000
The required commands that need to be issued in order for the table to be filled with 0's are the following:
STEP 1:
command: starting at index 7, type 5 (toggle 5 elements, starting from index 7)
resulting table: 0000000
00111000000
we still have 1's in the table, continue
STEP 1:
command: starting at index 9, type 3
resulting table: 000000000
000000000
All elements of the table are false, we've completed the problem with 2 steps.
What I have tried:
I have tried using a simple min-max algorithm that starts at the first 1 and, using a couple conditions, decides on the best command to use. This only works in simple scenarios, and not in more complex ones.
To better describe what I've tried I'm including pseudocode of my attempt at solving this:
primes[] = {3, 5, 7, 11, 13, 17 ... }
table[] = {0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0... }
bestFit(index)
cwi = length of 1's without 0's starting at index
if cwi == 0 then
return 0
for prime in primes do
difference = prime - cwi
if difference == 0 then
flipBits(index, cwi) return index + cwi
else if difference == 3 then
flipBits(index, cwi + 3)
return bestFit(index + cwi)
return 0
index = index of first 1
while !solved index = bestFit(index of first 1)