C++ Program to solve A Boolean Array Puzzle
In this tutorial, we are going to solve a Boolean Array Puzzle. First of all, we need to understand what is the Boolean Array Puzzle. To understand the Boolean Array puzzle read the following paragraph carefully.
We will be given an array containing the two-element. Out of the two-element one will be 0 and the other maybe 1 or 0, currently, we didn’t know which element is 0 and which one is 1, means we are not familiar with their value and position. Our task is to make all elements in the given array 0, though there is some condition as following which we have to follow.
- One fixed element is zero and the position is unknown.
- Assigning 0 directly to the element’s is not allowed.
- Only complement operation is allowed.
- The other element can be 0 or 1.
- Use of branching and loop statements are also prohibited.
Code for Boolean Array Puzzle in C++
#include <bits/stdc++.h> using namespace std; //function to convert into 0 void DoZero(int arr[2]) { arr[ arr[1] ] = arr[ !arr[1] ]; } int main() { int arr[] = {1, 0}; DoZero(arr); cout<<"arr[0] = "<<arr[0]<<endl; cout<<" arr[1] = "<<arr[1]; return 0; }
OUTPUT:
arr[0] = 0 arr[1] = 0
Another Approach
#include <bits/stdc++.h> using namespace std; //function to convert into 0 void DoZero(int x[2]) { x[0] = x[x[0]]; x[1] = x[0]; } int main() { int x[] = {1, 0}; DoZero(x); cout<<"arr[0] = "<<x[0]<<endl; cout<<"arr[1] = "<<x[1]; }
OUTPUT:
arr[0] = 0 arr[1] = 0
For more topics you can also be referred to the following:
Leave a Reply