A Boolean Array Puzzle In C Program?



Here we will see one Boolean array puzzle. One array is given with two elements 0 and 1. We have to make all elements to 0. There are some specifications that we should consider −

  • In the array one element is 0, that is fixed, but we do not know what is the position of that element
  • The other element can be 0 or 1
  • Only complement operation is allowed here, no other operations cannot be performed
  • We cannot use branching and loop statements
  • We cannot assign 0 directly to the array elements

We can solve this problem in different ways. There are three of them −

Method 1

Example

#include <iostream>
using namespace std;
void makeZero(int arr[2]) {
   arr[ arr[1] ] = arr[ !arr[1] ];
}
int main() {
   int arr[] = {1, 0};
   makeZero(arr);
   cout<<"arr[0] = "<<arr[0]<<endl;
   cout<<"arr[1] = "<<arr[1];
}

Output

arr[0] = 0
arr[1] = 0

Method 2

Example

#include <iostream>
using namespace std;
void makeZero(int arr[2]) {
   arr[ arr[1] ] = arr[ arr[0] ];
}
int main() {
   int arr[] = {1, 0};
   makeZero(arr);
   cout<<"arr[0] = "<<arr[0]<<endl;
   cout<<"arr[1] = "<<arr[1];
}

Output

arr[0] = 0
arr[1] = 0

Method 3

Example

#include <iostream>
using namespace std;
void makeZero(int arr[2]) {
   arr[0] = arr[arr[0]];
   arr[1] = arr[0];
}
int main() {
   int arr[] = {1, 0};
   makeZero(arr);
   cout<<"arr[0] = "<<arr[0]<<endl;
   cout<<"arr[1] = "<<arr[1];
}

Output

arr[0] = 0
arr[1] = 0
raja
Published on 19-Aug-2019 14:11:21
Advertisements