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;
}
}
CodePudding user response:
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]);
}
}
CodePudding user response:
This algorithm would not require to store too many numbers:
- loop over the array
- check if your variable contains the same as the current element
- if yes, increase a counter
- if no:
- check if counter is three
- if yes, output the element you counted (not the current one)
- reset counter to zero
- check if counter is three
- save the element you are looking at in the variable
- after the loop, check if the last element was counted three times (and not yet printed). If yes, print it.
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.
CodePudding user response:
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);
}
}