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
Count number of 1s in the array after N moves in C
We are given an array of size N. The array has all 0's initially. The task is to count the number of 1's in the array after N moves. Each Nth move has a rule associated with it −
- 1st Move − Change element at positions 1, 2, 3, 4...
- 2nd Move − Change element at positions 2, 4, 6, 8...
- 3rd Move − Change element at positions 3, 6, 9, 12...
In each move, we flip the elements (0 becomes 1, 1 becomes 0) at the specified positions. Let's understand with examples.
Syntax
int countOnes(int arr[], int N);
Example 1: Array of Size 4
Input: Arr[] = {0,0,0,0}, N = 4
Output: Number of 1s in the array after N moves = 2
Explanation: Array after following moves −
Move 1: {1,1,1,1}
Move 2: {1,0,1,0}
Move 3: {1,0,0,0}
Move 4: {1,0,0,1}
Number of ones in the final array is 2.
Example 2: Array of Size 6
Input: Arr[] = {0,0,0,0,0,0}, N = 6
Output: Number of 1s in the array after N moves = 2
Explanation: Array after following moves −
Move 1: {1,1,1,1,1,1}
Move 2: {1,0,1,0,1,0}
Move 3: {1,0,0,0,1,0}
Move 4: {1,0,0,1,1,0}
Move 5: {1,0,0,1,0,0}
Move 6: {1,0,0,1,0,1}
Number of ones in the final array is 2.
Algorithm
- Initialize an array of size N with all zeros.
- For each move i (from 1 to N), flip elements at positions that are multiples of i.
- To flip, check if the current element is 0 (convert to 1) or 1 (convert to 0).
- Finally, count the number of 1's in the array.
Implementation
#include <stdio.h>
int countOnes(int arr[], int N) {
// Perform N moves
for (int i = 1; i <= N; i++) {
for (int j = i; j <= N; j++) {
// If j is divisible by i (position is multiple of move number)
if (j % i == 0) {
if (arr[j - 1] == 0)
arr[j - 1] = 1; // Convert 0 to 1
else
arr[j - 1] = 0; // Convert 1 to 0
}
}
}
// Count number of 1's in the final array
int count = 0;
for (int i = 0; i < N; i++) {
if (arr[i] == 1)
count++;
}
return count;
}
int main() {
int size = 6;
int Arr[6] = {0}; // Initialize all elements to 0
printf("Array size: %d<br>", size);
printf("Number of 1s in the array after %d moves: %d<br>", size, countOnes(Arr, size));
return 0;
}
Array size: 6 Number of 1s in the array after 6 moves: 2
Key Points
- The algorithm simulates each move by flipping elements at positions that are multiples of the move number.
- Array indexing is adjusted (j-1) since array indices start from 0 but move positions start from 1.
- The final count represents elements that have been flipped an odd number of times.
Conclusion
This problem demonstrates how systematic flipping operations affect array elements. The solution efficiently simulates each move and counts the final number of 1's after all N moves are completed.
