Algorithm Check for Switch Program

252 views Asked by At

I have 4 switches that are randomly generated at run time. Ex:

Switch1: 1 0 0 0
Switch2: 0 1 0 0
Switch3: 0 0 1 0
Switch4: 0 0 0 1

When the switch is generated, the column for the switch number needs to be 1, but all other columns are randomly assigned (1 or 0).

A main switch performs an XOR operation on a switch that the user selects. The main switch starts at 0 0 0 0.

When the user selects a switch ( s1,s2,s3,s4 ) it is "XOR"ed to the current main switch.

Real Case:
S1: 1 1 0 0
S2: 0 1 1 0
S3: 0 0 1 0
S4: 1 0 0 1
START: 0 0 0 0
AND S1:1 1 0 0
AND S3:1 1 1 0

The objective is to get the main switch to 1 1 1 1.

When the four switches are created at run-time, I need to ensure that the puzzle is solvable. Any suggestions on how I can compare the four switches to determine if there is a combination to achieve a winning result of 1 1 1 1.

UPDATE------------ Note:
0 and 0 = 0
1 and 1 = 0
0 and 1 = 1

2

There are 2 answers

4
Tony Tuttle On

The main switch starts at 0 0 0 0.

When the user selects a switch ( s1,s2,s3,s4 ) it is ANDED to the current main switch.

If you start with 0000 and the only operation available is AND, you cannot get anything except 0000 as a result: 0 & 1 = 0, not 0 & 1 = 1.

Based on the example in your Real Case, it appears that you are performing an OR operation. If this is the case then any puzzle is solvable since

the column for the switch number needs to be 1

If you OR each switch with the original 0000 main switch you will always get 1111. You may get it before OR'ing with all four switches, based on the other randomly assigned bits, but you are guaranteed to get 1111 if you OR each switch with the original main switch.

1
AudioBubble On

This can be solved pretty easy, assuming you represent the switches as Integer:

public boolean isSolvable(Switch[] switches){
    int[] tmp = new int[SWITCH.COUNT];

    //generate an integer with all 1s of all switches
    for(Switch sw : switches)
        for(int i = 0 ; i < tmp.length ; i++)
            tmp[i] |= sw.get(i);

    //check if all bits that are part of the switches are 1
    for(int i : tmp)
        if(i == 0)
            return false;//this bit is 0 -> can't be set to 1 by combining switches

    //all bits can be set to 1 by combining switches
    return true;
}

Hope this java-code helps. I can explain further if necassary. Though the constraint that switch i has column i set to 1 ensures that a solution exists, if the number of switches is atleast equal to the number of columns in each switch.