Reputation: 1
Consider an array as shown
int[] nums = {1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 1, 1, 2, 2, 2}
Output the number that's repeating consecutively n
times. For example if we need to output a number that repeats consecutively 3
times then the output must be 1
, 3
, 5
and 2
. 4
should not be considered as it's repeating consecutively four times.
Please let me know how this can be achieved in Java with both traditional and Java 8 streams way.
I tried something like below, but it ignores the last three elements. If I doesn't give it will reach out of bound.
for(int i = 0; i < nums.length - 3; i++) {
if(nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2] && nums[i + 2] != nums[i + 3]) {
System.out.println(nums[i]);
continue;
}
}
Upvotes: 0
Views: 184
Reputation: 1
public class Xyz {
public static void main(String[] args) {
//Try This just change the value of n.
String s = "";
int[] nums = {1,1,1,2,2,2,2,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,1,1,2,2,2};
int n =3;
for(int i=0; i<nums.length-2;i++) {
int c = 0;
for (int j = i+1; j < nums.length; j++){
if (nums[i] == nums[j]) {
c++;
if (c>=n) {
i=i+n;
break;
}
}
else{
break;
}
}
if(c == n-1) {
s = s + nums[i] + ' ';
i = i + n-1 ;
}
}
System.out.println(s);
}
}
Upvotes: 0
Reputation: 9463
This algorithm would not require to store too many numbers:
Ok, I implemented the above algorithm and came up with this:
public class Test {
static int[] nums = {1,1,1,2,2,3,3,3,4,4,4,4,5,5,5,1,1,2,2,2};
public static void main(String[] args) {
int countingNumber = 0;
int count = 0;
for (int num: nums) {
if (countingNumber == num) {
count++;
} else {
if (count == 3) {
System.out.print(String.format(" %d", countingNumber));
}
count = 1;
countingNumber = num;
}
}
if (count == 3) {
System.out.print(String.format(" %d", countingNumber));
}
}
}
When run, it prints
1 3 5 2
as was requested.
Upvotes: 1
Reputation: 126
You need to check if there are numbers that are the same before the group i
, i+1
, and i+2
as well:
for(int i = 0; i <= nums.length - 3; i++){
if((i == 0 || nums[i] != nums[i - 1]) && nums[i] == nums[i+1] && nums[i+1] == nums[i+2] && (i + 2 == nums.length - 1 || nums[i+2] != nums[i+3])){
System.out.println(nums[i]);
}
}
Upvotes: 2