Reputation: 61
Given a binary number such as "100001111111110000001" where each bit is placed in an array so that the array looks like the following: [1,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1]
I want to locate the starting index and ending index of any sequence of 1's.
Desired output (reading from right to left):
-starting index = 0
-ending index = 0
(Get this numbers a do something accordingly)
Then:
-starting index = 7
-ending index = 15
(Get this numbers a do something accordingly)
last occurrence -
-starting index = 20
-ending index = 20
(Get this numbers a do something accordingly)
How can I accomplish the desired output in C?
Attaching code I tried:
for (int i = 0; i< counter; i++) {
if (bitArray[i] == 0) {
while (bitArray[i] == 0) {
startP++;
endP++;
i++;
}
}
if(bitArray[i] == 1) {
startP++;
while(bitArray[i+1]==1) {
endP++;
i++;
}
}
if (endP == startP) {
//do something
} else if (endP == (startP + 1)) {
//do something
} else if (endP > (startP + 1)) {
// do something
}
endP++;
startP = endP;
}
*counter = the len of the array
*endP and startP int, intiliazed.
*bitArray the array as described.
Upvotes: 0
Views: 77
Reputation: 1166
I don't know exactly what your code is supposed to do, but if you just want to print start and end indices of sets of 1s, I changed your code a bit to do so:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char msg[64];
int bitArray[] = {1,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1};
int inSet = 0;
int start;
int end;
for (int i = 0; i < sizeof(bitArray); i++) {
if (bitArray[i] == 1 && inSet == 0) {
inSet = 1;
start = i;
}
else if(bitArray[i] == 0 && inSet == 1) {
inSet = 0;
end = i - 1;
snprintf(msg, sizeof(msg), "-starting index = %d\n-ending index = %d\n", start, end);
printf(msg);
}
}
if(inSet == 1)
{
end = sizeof(bitArray) - 1;
snprintf(msg, sizeof(msg), "-starting index = %d\n-ending index = %d\n", start, end);
printf(msg);
}
}
Upvotes: 1