To remove 3 consecutive numbers in an array - java

I need to remove 3 consecutive integers, done with the code but i am not able to print the last index number. can you please help me out..
here is the code..
public class MyClass {
public static void main(String args[]) {
int[] list={ 1, 1, 1, 2, 3, 4, 5, 5, 6, 5, 7, 8, 9};
for(int i=0; i<list.length;i++)
{
if((list[i]==list[i+1]) )
{
if(list[i]==list[i+2])
{
i=i+2;
continue;
}
System.out.print(list[i]) ;
}
else
{
System.out.print(list[i]);
}
}
}
}

As stated by #Dr.Will in his/her answer, one of the problems in your code is the check i < list.length.
Anyway, it's not the only one: you are accessing [i+1] and [i+2] elements without checking if those two values are acceptable indexes.
I just want to add some hint:
Use a debugger while writing such algorithms (it may save you A LOT of time)
cache the value of intermediate results, to avoid multiple access to the same element of the array
cache the size of the array, for the same reason, or use a reverse loop (which has some advantages)
The result would look something like this:
public class MyClass {
public static void main(String... args) {
int[] list = { 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 5, 7, 8, 9}; // sample list
int len = list.length;
if(len < 3)
return; // avoid ArrayIndexOutOfBoundsException
// forward loop
System.out.println("Forward loop:");
int elem1;
for(int i = 0; i < len; i++){
elem1 = list[i];
if(i+1 < len && elem1 != list[i+1])
System.out.println(elem1);
else if (i+2 < len && elem1 == list[i+2] && ++i < len){
// note that "&&" in java is a shot-circuit "AND", so the last "++i" will not be executed if not necessary
// also note that i'm not incrementing "+2", because the for loop will add another "+1" just after this "continue" statement
continue;
} else
System.out.println(elem1);
}
// reverse loop
System.out.println("\nReverse loop (if the order is not that relevant):");
for(int i = len; --i >= 0;){
elem1 = list[i];
if(i-1 >= 0 && elem1 != list[i-1])
System.out.println(elem1);
else if(i-2 >= 0 && elem1 == list[i-2] && --i >= 0)
continue;
else
System.out.println(elem1);
}
}
}

thank you for your logic (–Marco Carlo Moriggi), your logic is helpful and also slightly look complicated, but i changed or edited one line after referring your logic, this seems not much complicated as your logic but gives same result.
public class MyClass {
public static void main(String args[]) {
int[] list={ 1, 1, 1, 2, 3, 4, 5, 5, 6, 5, 7, 8, 9};
int elem = list.length;
for(int i=0; i<list.length;i++)
{
if((i+2<elem) && (list[i]==list[i+1]) )
{
System.out.print(list[i] + " ") ;
if(list[i]==list[i+2])
{
i=i+2;
continue;
}
}
else
{
System.out.print(list[i] + " ");
}
}
}
}

I think that is the i<list.length-1 clause. Your lis.length will return a value of 13, if i remember how to count, adding the -1, you are giving a value of 12, and if you add the <, you´re telling the i to only reach the 11 position.
So i think the solution could be either one of these:
for(int i=0; i<=list.length-1;i++)
or
for(int i=0; i<list.length;i++)

Related

Save integer into vector after foor loop with conditionals

I have to set up a for loop that differences between odd and even numbers. I'm thinking to use an if/else statement into the for loop that evaluates de residue to know if is even or odd. Once done it, i'd like to save the number in a vector: one vector for the if condition, and another for the else.
This is my code!
import java.io.*;
import java.util.Arrays;
import java.util.*;
class Even_odd_array {
static void CountingEvenOdd(int arr[],
int arr_size)
{
int even_count = 0;
int odd_count = 0;
//int [] subvector_odd = {};
Vector<Integer> vector_odd = new Vector<Integer>();
Vector<Integer> vector_even = new Vector<Integer>();
// loop to read all the values in
// the array
for(int i = 0 ; i < arr_size ; i++)
{
// checking if a number is
// completely divisible by 2
if ((arr[i] & 1) == 1)
odd_count ++ ;
vector_odd.addElement(arr[i]);
else
even_count ++ ;
vector_even.addElement(arr[i]);
}
System.out.println( "Number of even"
+ " elements = " + even_count
+ " Number of odd elements = "
+ odd_count) ;
System.out.println(vector_odd); //This vector should look like [1, 3, 5, 7]
}
// Driver Code
public static void main (String[] args)
{
int arr[] = {2, 4, 6, 8, 10, 1, 3, 5, 7};
int n = arr.length;
CountingEvenOdd(arr, n);
}
}
The output should be:
Number of even elements = 5 Number of odd elements = 4
even_vector = [2, 4, 6, 8, 10]
odd_vector = [1, 3, 5, 7]
I'm getting an error in the else statement line when I include the vector.add() method inside the if statement, and I don't understand why...
Thanks!!
Modulo operator is %, not & which is bitwise and (see https://www.tutorialspoint.com/java/java_basic_operators.htm ). In addition, array length does not need to be given as parameter and a for loop is not needed. You have everything you need by using the two lines below.
Integer[] array = {2, 4, 6, 8, 1, 3, 7};
Vector<Integer> vectorEven = Arrays.stream(array).filter(i -> i % 2 == 0).collect(Collectors.toCollection(Vector::new));
Vector<Integer> vectorOdd =Arrays.stream(array).filter(i -> i % 2 == 1).collect(Collectors.toCollection(Vector::new));
System.out.println(vectorEven);
System.out.println(vectorOdd.size());
Currently your else block is not related to any if condition (you can omit curly braces if the block contains a single statement, though) .
To fix this, use curly braces to delimit the if and else blocks :
if ((arr[i] & 1) == 1) {
odd_count ++ ;
vector_odd.addElement(arr[i]);
}
else {
even_count ++ ;
vector_even.addElement(arr[i]);
}
Your current code is equivalent to :
if ((arr[i] & 1) == 1) {
odd_count ++ ;
}
vector_odd.addElement(arr[i]);
else {
even_count ++ ;
}
vector_even.addElement(arr[i]);
As you see, the else part can't be related to the if part here.

Java array order

I have the following array:
int [] mi_array= {9,4,0,0,4,0,3,0,1,8,0};
I want to order the numbers other than 0 on the left, and the 0s on the right, but I find that the function steps on one of the numbers.
The output must be
{9,4,4,3,1,8,0,0,0,0,0}
public class Array {
public static void main(String[] args) {
int [] mi_array= {9,4,4,3,1,8,0,0,0,0,0};
int x=0;
int y=mi_array.length-1;
for (int i=0;i<mi_array.length;i++)
if(mi_array[i]!=0) {
mi_array[x]=mi_array[i];
x++;
}
else {
mi_array[y]=mi_array[i];
y--;
}
for (int i=0;i<mi_array.length;i++)
System.out.println(mi_array[i]);
System.out.println(x);
}
}
Try this.
int[] mi_array = {9, 4, 0, 0, 4, 0, 3, 0, 1, 8, 0};
for (int i = 0, j = i + 1, s = mi_array.length; j < s;)
if (mi_array[i] == 0) {
mi_array[i] = mi_array[j];
mi_array[j] = 0;
++j;
} else if (++i >= j)
j = i + 1;
System.out.println(Arrays.toString(mi_array));
// -> [9, 4, 4, 3, 1, 8, 0, 0, 0, 0, 0]
You can use filter and IntStream.concat to merge the parts of the array that are not 0 with the parts that are.
final int[] mi_array = { 9, 4, 0, 0, 4, 0, 3, 0, 1, 8, 0 };
final int[] result = IntStream.concat(Arrays.stream(mi_array).filter(i -> i != 0),
Arrays.stream(mi_array).filter(i -> i == 0)).toArray();
System.out.println(Arrays.toString(result));
Demo!
You can also do this:
final int[] mi_array = { 9, 4, 0, 0, 4, 0, 3, 0, 1, 8, 0 };
final int[] result = new int[mi_array.length];
final AtomicInteger idx = new AtomicInteger();
Arrays.stream(mi_array).filter(i -> i != 0).forEach(val -> result[idx.getAndIncrement()] = val);
System.out.println(Arrays.toString(result));
Your primary problem here is that you overwrite numbers you haven't already covered.
if (mi_array[i] != 0) {
mi_array[x] = mi_array[i];
x++;
}
x can never exceed i in this code; it starts at 0 just like i does, and increments at most by 1 every loop (and i increments by 1 every loop). So, no problem here; at 'worst' this is mi_array[i] = mi_array[i]; which does nothing.
however...
} else {
mi_array[y]=mi_array[i];
y--;
}
This is much more problematic. Given inputs {9,4,0,0,4,0,3,0,1,8,0};, when i is 2, then mi_array[i] is 0, thus this code runs. y is still 10, so this will end up running: mi_array[10] = 0;. The second 0 occurs when i is 3, and ends up running: mi_array[9] = 0;. And at that point, the 8 at index 9? You deleted it. It cannot be recovered.
The solution
The dumb solution is to make a copy of the array; edit the copy, refer to the original (which you won't change at all). You don't actually end up needing a copy; this code will write every number back, so just make a new array of the same size and write in that.
A slightly more elegant solution will not write 0s at all. Instead, it just writes the non-zeroes (as that code cannot overwrite anything, as shown before), and then at the end, overwrite the rest with zeroes. Now you don't need a copy.
O(n), two-pointer approach:
public static void shiftZeroesRight(int[] array) {
int notZeroPos;
for (int i = 0; i < array.length; i++) {
if (array[i] != 0)
continue;
notZeroPos = i + 1;
while (notZeroPos < array.length && array[notZeroPos] == 0)
++notZeroPos;
if (notZeroPos >= array.length)
break;
array[i] = array[notZeroPos];
array[notZeroPos] = 0;
}
}

How to output same numbers from previously defined two different integer arrays

I need to write a program which defines two arrays of int's and prints all elements of the first array which do not appear in the second, but each value once only, without repetitions (the order of printed values is irrelevant).
For example for arrays:
int[] arr = { 4, 3, 4, 3, 6, 7, 4, 8, 2, 9 };
int[] brr = { 2, 3, 6, 8, 1, 5 };
The result should be:
7 4 9
It only use the java.lang. package and it can't create any arrays, collections or Strings.
This prints all elements of the first array which do not appear in the second, now you just have to check for repetitions.
public static void compareArrays(int[] arr1, int[] arr2) {
boolean equal = false;
int[] printed = null;
for (int i = 0; i < arr1.length; i++) {
for (int x = 0; x < arr2.length; x++) {
if (arr1[i] == arr2[x]) {
equal = true;
break;
} else {
equal = false;
}
}
if (equal != true) {
System.out.println(arr1[i]);
}
}
}
public static void main(String[] args) {
int[] arr = { 4, 3, 4, 3, 6, 7, 4, 8, 2, 9 };
int[] brr = { 2, 3, 6, 8, 1, 5 };
compareArrays(arr, brr);
}
I will give you some pointers, but will not provide any code as I've not seen any attempt from your side. You can tackle this problem several ways, have a look and try to implement this yourself. You will learn much more during the process, rather than if someone gives you a complete full-code answer. So here goes:
First method:
Create a new ArrayList that will hold your output.
Iterate through the first array, iterate through the second array. Compare each value.
If value is not present and is not present in the output list (you would need to check for that specifically, so you dont have repetition of values), then add it to output list.
Print output list.
Second method:
Convert both arrays into an ArrayList.
Use the removeAll() method provided with Lists to get difference between the arrays. This will be stored in one of the lists you created earlier.
Remove repetitive items from the list (e.g. using Streams).
Third method:
Create a new ArrayList that will hold your output.
Iterate through values of array1.
Initialize a boolean variable (e.g. call it contains) that will determine whether a value from array1 is present in array2 using an IntStream.
Create if statement - if contains is true, add the value to your output list. Check that your output List already doesn't have the value and only add if it doesn't. Print output list.
Try using this instead:
String[] unique = new HashSet<String>(Arrays.asList(arr)).toArray(new String[0]);
for (int uEach : unique) {
for (int bEach : brr) {
if (unique[uEach] == brr[bEach]) {
ArrayUtils.removeElement(unique, uEach);
}
}
};
System.out.print(unique);
You can use to get distanct value from an array:
int[] unique = Arrays.stream(arr).distinct().toArray();
Then loop over both arrays and match strings if not found print that:
int i, j, occ;
int[] arr = { 4, 3, 4, 3, 6, 7, 4, 8, 2, 9 };
int[] brr = { 2, 3, 6, 8, 1, 5 };
arr = Arrays.stream(arr).distinct().toArray();
for (i = 0; i < arr.length; i++) {
occ = 0;
for (j = 0; j < brr.length; j++) {
if (arr[i] == brr[j]) {
occ++;
}
}
if (occ == 0) {
System.out.println(arr[i]);
}
}
static void findMissing(int a[], int b[]) {
for (int i = 0; i < a.length; i++) {
int j;
for (j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
break;
}
}
if (j == b.length) {
System.out.print(a[i] + " ");
}
}
}

Comparing two arrays and then making another array with common elements (and no duplicates)

Hi, I'm a newbie to Java and I was doing this lab assignment where we compare elements of two arrays to get the common elements. I am stuck on how to get rid of duplicates.
My current code is giving me the output [3, 0, 5, 6, 5, 0, 9, 0] and the desired output of common is [3, 5, 6, 9, 0, 0, 0, 0].
Also, since I am not that experienced, please do not post professional ways to do the problem or "experienced" answers to my question, as that would not help me at all :D.
Thanks!
public static void main (String[] args) {
int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2};
int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13};
int[] common = new int[a1.length];
System.out.println("Exercise 3: ");
findCommon(a1,a2,common);
}
public static void findCommon(int[] a1, int[]a2, int[] common) {
int num = 0;
for (int i = 0; i < common.length; i++)
{
for (int j = 0; j < a2.length; j++)
{
if (a1[i] == a2[j]) // loops through every index of j, while keeping i at one index
num = a1[i];
for (int k = 0; k < common.length; k++) // makes sure there are no duplicates in common
{
if (num != common[k])
common[i] = num;
}
}
}
for (int elements : common)
System.out.print(elements + " ");
}
You should look into using Sets to do this kind of thing, but since this is an exercise I've provided a solution with some comments along the way in the code.
Basically you should break the problem down into pieces, each of which is its own method. That way you will have an easier time getting it straight.
arrayIntersect(int[], int[])
This method's job is to create an array from two arrays. The resulting array must have unique elements that are present in both arrays.
You can do n. 1 with a helper method (mentioned below).
inArray(int, int[])
This method returns true if an array contains the given element, false otherwise.
Example
public static void main (String[] args) {
int[] a1 = {3, 8, 5, 6, 5, 8, 9, 2};
int[] a2 = {5, 15, 4, 6, 7, 3, 9, 11, 9, 3, 12, 13, 14, 9, 5, 3, 13};
int[] a3 = arrayIntersect(a1, a2);
for (int a : a3) {
System.out.println(a);
}
}
private static int[] arrayIntersect(int[] a1, int[] a2) {
int[] intersect = new int[Math.min(a1.length, a2.length)];
int curIndex = 0;
for (int x : a1) {
if (inArray(x, a2) && !inArray(x, intersect)) {
intersect[curIndex] = x;
curIndex++;
}
}
// resize intersect array to not include unused indexes
int[] tmp = intersect;
intersect = new int[curIndex];
for (int i = 0; i < intersect.length; i++) {
intersect[i] = tmp[i];
}
return intersect;
}
private static boolean inArray(int element, int[] array) {
boolean result = false;
for (int a : array) {
if (element == a) {
result = true;
break;
}
}
return result;
}
You are very close to the correct anwser, but the for loop for (int k = 0; k < common.length; k++) is being executed for every element of a2. So, when an value exist for a1 but doesn't exist for a2, you are putting the old value of num at the common array. If you look at the elements printed, you will see that every time that an element just exist in a1, the element repeat.
The result of the code is
3 3 5 6 5 5 9 9
You put the right identation, but forgot the curly brackets. If you put the curly brackets at the if (a1[i] == a2[j]), this will be the result:
3 0 5 6 5 0 9 0
But why these 0 are there? Because when you create an int array in java, all elements start with the value of 0. And you are putting the common elements at the same position of the presence of this elements in the a1 array. You can correct this by populating the int array with an invalid number and them ignorin it. At this code, I assumed that -1 is an invalid value.
public static void findCommon(int[] a1, int[] a2, int[] common) {
int num = 0;
for (int i = 0; i < common.length; i++) {
common[i] = -1;
}
for (int i = 0; i < common.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) { // loops through every index of j, while keeping i at one index
num = a1[i];
for (int k = 0; k < common.length; k++) // makes sure there are
// no duplicates in common
{
if (num != common[k])
common[i] = num;
}
}
}
}
for (int elements : common) {
if (elements != -1)
System.out.print(elements + " ");
}
}
If you see, At the if (elements != -1) I didn't put the curly brackets but it worked. If you don't put the curly brackets, it will just execute the next command.

Reverse plus Even and Odd of an array

I am a newbie to programming. I am trying to create a program that would display an array in reverse. Plus also find the even and odd numbers of an array,sum the count and also display the even and odd numbers. The code works but the problem is that it also reverses the even and odd arrays and it shows this weird zero in those arrays. What am I doing wrong?
Please also provide explanation. Thanks!
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[i] = array[i];
even++;
}
else
{
Odd[i] = array[i];
odd++;
}
}
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
The output is:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[0, 12, 0, 10, 0, 8, 0, 6, 0, 4, 0, 2, 0]
Odd: 7
[13, 0, 11, 0, 9, 0, 7, 0, 5, 0, 3, 0, 1]
You need to correct your logic
int[] Even = new int[(array.length/2)+1];
int[] Odd = new int[(array.length/2)+1];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
As per you code, you are initializing array of size 13 for odd and even, which is not correct.
int[] Even = new int[13];
int[] Odd = new int[13];
So, by default, Even and Odd array will be initialized by 0 value. Then, you are setting value as per main array, which a size of 13 on alternate basis (even/odd).
==Updated==
Since, you don't want Even and Odd array in reverse order. Then, you can move the code up.
>>Demo<<
You faced 2 problems (I guess so)
The odd and even arrays are also in reverse order
Reason: The first For loop reverses the 'array' and stores the results in array itself. So, the next time when you try working with 'array' to find odd/even numbers, you are actually working with the reversed array.
Solution: You can assign the original array to a backup array and use that backup array to find odd and even nos.
Unnecessary zeros:
Reason: In your second for loop you used odd[i]=array[i] which seems to be a logical error in your code. Consider the case:
value of i : 0 1 2 3 4 5 ... 12
value of array[i]: 1 2 3 4 5 6 ... 13
value of odd[i] : 1 0 3 0 5 0 ... 13
value of even[i] : 0 2 0 4 0 6 ... 0
This means, the control inside for loop is made to flow either to if{} block or the else{} block and not the both. So, when if(condition) is satisfied, then even[i] array will be updated. But meanwhile what happens to the odd[i] array? It retains the inital value '0'. That's it!
I hope the following code helps you:
import java.util.Arrays;
public class A
{
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int[] arr2 = new int[array.length]; // backup array
arr2=Arrays.copyOfRange(array,0,array.length);
for ( int i=0; i<arr2.length/2; i++ )
{
int temp = arr2[i];
arr2[i] = arr2[arr2.length-(1+i)];
arr2[arr2.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(arr2));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
Even=Arrays.copyOfRange(Even,0,even);
Odd=Arrays.copyOfRange(Odd,0,odd);
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
Note: I have used Arrays.copyOfRange(array,start,end) function to copy a certain part of the array from start to end-1 position.
Output:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[2, 4, 6, 8, 10, 12]
Odd: 7
[1, 3, 5, 7, 9, 11, 13]
Hope this helps :)
--Mathan Madhav
You select even and odd numbers from reversed array.
You use wrong index for even and odd arrays.
If you don't want to see zeros in output, use print in for statement. Another solution - firstly count odd and even numbers and create arrays with exact size.
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even++] = array[i];
}
else
{
Odd[odd++] = array[i];
}
}
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}

Categories