Home  >  Article  >  Backend Development  >  What is the binary array after M range switching operations?

What is the binary array after M range switching operations?

王林
王林forward
2023-09-04 11:49:061343browse

What is the binary array after M range switching operations?

Here we will see a problem. We have a binary array. It has n elements. Each element is either 0 or 1. Initially, all elements are 0. Now we will provide the M command. Each command will contain a start and end index. So command(a, b) means that the command will be applied from the element at position a to the element at position b. This command will toggle the value. So it switches from ath index to bth index. The question is simple. Examine algorithms to get an idea.

Algorithm

toggleCommand(arr, a, b)

Begin
   for each element e from index a to b, do
      toggle the e and place into arr at its position.
   done
End

Example

#include <iostream>
using namespace std;
void toggleCommand(int arr[], int a, int b){
   for(int i = a; i <= b; i++){
      arr[i] ^= 1; //toggle each bit in range a to b
   }
}
void display(int arr[], int n){
   for(int i = 0; i<n; i++){
      cout << arr[i] << " ";
   }
   cout << endl;
}
int main() {
   int arr[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
   int n = sizeof(arr)/sizeof(arr[0]);
   display(arr, n);
   toggleCommand(arr, 3, 6);
   toggleCommand(arr, 8, 10);
   toggleCommand(arr, 2, 7);
   display(arr, n);
}

Output

0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 1 1 1 1 0

The above is the detailed content of What is the binary array after M range switching operations?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete