Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
A Boolean Array Puzzle in C?
This is an array-based puzzle that requires you to change all the numbers of an array that contains two elements to 0. One element of the array is 0 and the other may or may not be 0.
To solve this puzzle, the program needs to find the non-zero element and change it to 0.
There are the following constraints that are needed to solve the boolean array puzzle −
- Allowed operation is complement, other operations are not allowed.
- Loops and conditional statements are not allowed.
- Direct assignment is also not allowed.
Syntax
a[a[1]] = a[!a[1]]; // Using complement operation a[a[1]] = a[a[0]]; // Alternative approach
Example: Using Complement Operation
This approach uses the complement operator to solve the puzzle without loops or conditional statements −
#include <stdio.h>
void makeZero(int a[2]) {
a[a[1]] = a[!a[1]];
}
int main() {
int a[] = {1, 0};
printf("Before: arr[0] = %d, arr[1] = %d<br>", a[0], a[1]);
makeZero(a);
printf("After: arr[0] = %d, arr[1] = %d<br>", a[0], a[1]);
return 0;
}
Before: arr[0] = 1, arr[1] = 0 After: arr[0] = 0, arr[1] = 0
Alternative Method: Without Negation
You can also solve this puzzle without using the negation operation −
#include <stdio.h>
void makeZeroAlternative(int a[2]) {
a[a[1]] = a[a[0]];
}
int main() {
int a[] = {0, 1};
printf("Before: arr[0] = %d, arr[1] = %d<br>", a[0], a[1]);
makeZeroAlternative(a);
printf("After: arr[0] = %d, arr[1] = %d<br>", a[0], a[1]);
return 0;
}
Before: arr[0] = 0, arr[1] = 1 After: arr[0] = 0, arr[1] = 0
How It Works
-
Method 1:
a[a[1]] = a[!a[1]]uses the indexa[1]to access array element and assigns the value from the complement index. -
Method 2:
a[a[1]] = a[a[0]]works when one element is guaranteed to be 0, using it as both index and value source. - Both methods cleverly use array indexing to avoid explicit conditionals while satisfying the puzzle constraints.
Conclusion
The Boolean array puzzle demonstrates clever use of array indexing and complement operations to achieve the desired result without using traditional control structures. Both approaches successfully convert the array to all zeros while respecting the given constraints.
