- #1
Arnoldjavs3
- 191
- 3
Homework Statement
Say that a "clump" in an array is a series of 2 or more adjacent elements of the same value. Return the number of clumps in the given array.
countClumps([1, 2, 2, 3, 4, 4]) → 2
countClumps([1, 1, 2, 1, 1]) → 2
countClumps([1, 1, 1, 1, 1]) → 1
Homework Equations
The logic is that it'll set a number to currentNum in the first for loop, and then run another for loop(with how many iterations that it must run so it doesn't go out of bounds) to check if there are clumps. If the number nums[x] = nums, then it'll notice that it's found a clump. This will increment the ctr by 1 and set the boolean to true. Then the loop will find the index of which the clump ends and set i = x, that index. Hopefully this makes sense verbally and more so in my code
The Attempt at a Solution
Java:
public int countClumps(int[] nums) {
int length = nums.length;
boolean clumpFound = false;
int clumpCtr = 0;
int currentNum = 0;
int iterationsLeft = 0;
for(int i = 0;i<length;i++) {
currentNum = nums[i];
iterationsLeft = length-i;
for(int x = i+1; x<iterationsLeft;x++) {
if (nums[x]==currentNum && clumpFound == false) {
clumpCtr++;
clumpFound = true;
}
else if(nums[x]!=currentNum && clumpFound == true) {
clumpFound = false;
i=x;
break;
}
else if(nums[x]!=currentNum && clumpFound == false) {
break;
}
}
}
return clumpCtr;
}
I'm having a really hard time visualizing this in my head as to what's going wrong here.
Here are the tests it fails/passes:
http://prntscr.com/dz1x1f