Reputation: 43
I have an array of bits. Bits will be toggled off and on according to following criteria: 1. if the bits left and right of bit is on put the bit to one otherwise zero. 2. boundary condition(leftmost and rightmost bit will only depend on one bit. ie either left of it or right of it.
this array will be processed m times with the following criteria.
I wrote the following code where A is the original array and subsiquent is the array for processing. But this will give me O(nm) where n is the length and m is no of times i want to do the process. Please suggest me some alternative for the solution so that i can decrease my complexity.
for(int k = 0;k < m;k++){
for(int l = 0;l < n;k++){
if(l == 0){
if(A[l+1]==1)
subsiquent[l]=1;
else
subsiquent[l]=0;
//** is there a } missing here?
else if(l==n){
if(A[l-1]==1)
subsiquent[l]=1;
else
subsiquent[l]=0;
} else {
if(A[l+1]==1 && A[l-1]==1 ){
subsiquent[l]=1;
}else{
subsiquent[l]=0;
}
}
//** or is there a } missing here?
}
A = subsiquent;
}
Upvotes: 3
Views: 82
Reputation: 3264
Some things to see:
Edit: with p>=2 in my examples for extremities of course
Edit: you can represent your array as the number of similar bits in an int array + memorizing the first bit
000111101100110101
would be represented as [0]3412221111 (begin with zero, then 3 zero, then 4 one, then 1 zero, then 2 one, etc.)
I didn't check all, but you can infer the rule to go from one step to an other rather easily with minimum step. (there are many cases, I let you find them. You only have to go from left to right and remember that you switch from 0 and 1, but may have to modify/decrease the number on the right when iterating, or inserting number. A linked list will be well suited here)
For example, the steps will be:
000111101100110101 [0]3-4-1-2-2-2-1-1-1-1
000011010000001010 [0]4-2-1-1-6-1-1-1-1
000000100000000101 [0]6-1-8-1-1-1
000000000000000010 [0]16-1-1
000000000000000001 [0]17-1
000000000000000000 [0]18
Upvotes: 1