This question was asked in interview and deals with recursion/backtracking. Suppose we have two arrays of booleans:bool* source and bool* target,each of them the same length n(source/target/n are given as arguments). The goal of the question is to transform source to target using operation switch.
- If there are several transforns: present any one of them
- If there is no solution: assert that there is no solution
Definition: operation switch(int i, bool* arr) inverts the value at arr[i] and arr[i-1] and arr[i+1] (if these indices are in the range 0…n-1).
In other words, switch operation will usually flip three bits (i and its neighbors), but only two at the ends.
For example:
- switch(0,arr) will switch the values of arr[0] and arr[1] only
- switch(n-1,arr) will switch the values of arr[n-1] and arr[n-2] only
Thank you in advance for the suggestions about the algorithm.
As far as I understand the problem, the main observation is that we never need to perform more than one switch on any position. This is because switching twice is the same as not switching at all, so all even switches are equivalent to 0 switches and all odd switches are as good as 1 switch.
Another thing is that the order of the switches don’t matter. switching the i-th and i+1-th elements is the same as switching i+1-th and then the i-th. The pattern obtained at the end is the same.
Using these two observations, we can simply try out all possible ways of applying switch to the n length array. This can be done recursively (i.e. doing a switch at index i/not doing a switch at index i and then trying out i+1) or by enumerating all 2**n n bit bitmask and using them to apply switches until one of them creates the target value.
Below is my hack at the solution. I have packed the arrays into ints and used them as bitmasks to simplify the operations. This prints out the indices that need to be switched to get the target array and prints “Impossible” if the target is not obtainable.