Bring ints that are even to the froont of the array - java

I want to arrange the array such that even numbers are brought ahead. This is what I've done.
public int[] moveEvenToFront(int[] arr) {
arr[i - 1] = arr[i];
arr[i] = temp;
}
}
return arr;
}
}
This is what I have so far

Pretty simple. Just create a new array, then loop through the original twice. The first time, add the evens. The next time, add the odds. Looks like you were almost there:
public int[] moveEvenToFront(int[] arr) {
//declare a new array to populate with the result
int[] result = new int[arr.length];
int temp = 0;
//add the evens
for (int i = 0; i < result.length; i++) {
if (arr[i] % 2 == 0) {
result[temp] = arr[i];
temp++;
}
}
//add the odds
for (int i = 0; i < result.length; i++) {
if (arr[i] % 2 != 0) {
result[temp] = arr[i];
temp++;
}
}
//return
return result;
}

Related

How to make a new array out of only even numbers?

Basically, I am trying to make an entirely new array of a new length that contains only the even ints in an array of integers.
However, I am getting an index out of bounds error. Can you help me find what I did wrong?
import java.util.Arrays;
public class findevens {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[]{4,8,19,3,5,6})));
}
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
//add even ints to new array
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[i] += arr[i];
}
}
return result;
}
}
You should use a new variable to keep track of the current result index (let's say, j):
public static int[] evens(int[] arr) {
int length = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
// Access result with `j` and update its value
result[j++] = arr[i];
}
}
return result;
}
Also, you can you streams:
int[] array = {1, 3, 4, 5, 6};
int[] even = IntStream.of(array).filter(item -> item%2 == 0).toArray();
System.out.println(Arrays.toString(even));
You need a new index variable for the result array and your assignment is also wrong as instead of assigning you are adding the even number to the result array element.
int j = 0;
int[] result = new int[length];
// add even ints to new array
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0)
{
result[j++] = arr[i];
}
}
Problem is you are using i for the result array AND the original array. You should only increment the result array inside of the IF (when you find an even number) otherwise, you go out of bounds due to i (the original arr) being a larger size than the result array.
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
//add even ints to new array
int resultCount = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[resultCount] += arr[i];
resultCount++;
}
}
return result;
}
Simply when you want to assign a value to result[] you do it with the index in the array arr, 0, 1 and 5. You just have to declare an auxiliary int aux = 0; variable before second loop and increment according to arr[i] % 2 == 0 so true
result[i] += arr[i];
a
int aux = 0;
result[aux++] += arr[i];
Complete code
public class findevens {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[]{4,8,19,3,5,6})));
}
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
int aux = 0;
//add even ints to new array
for (int i = 0; i < arr.length; i++){
if (arr[i] % 2 == 0) {
result[aux++] += arr[i];
}
}
return result;
}
}
Since you don't really know how long the resultant array will be you can copy them to the front of the current array. Then use the final location as the count of values.
int[] input = {1,2,3,4,5,6,7,8,9};
int k = 0;
for(int i = 0; i < input.length; i++) {
if (input[i] % 2 == 0) {
input[k++] = input[i];
}
}
int[] evens = Arrays.copyOf(input, k);
System.out.println(Arrays.toString(evens));
Prints
[2, 4, 6, 8]
A simple way is to filter even numbers using the Stream API and return the result as an array.
Arrays.stream(arr)
.filter(n -> n % 2 == 0)
.toArray();
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[] { 4, 8, 19, 3, 5, 6 })));
}
static int[] evens(int[] arr) {
return Arrays.stream(arr).filter(n -> n % 2 == 0).toArray();
}
}
Output:
[4, 8, 6]
What went wrong with your code:
result.length is 3 and therefore in result[], the maximum index you can access is 2 (i.e. result.length -1) whereas your second loop counter goes up to 5 (i.e. arr.length - 1) and you are using the same counter to access elements in result[] resulting in ArrayIndexOutOfBoundsException.
If you want to do it in your own way, you need to use a separate counter for result[] e.g.
int[] result = new int[length];
//add even ints to new array
for (int i = 0, j = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[j++] = arr[i];
}
}

[Java]Why does the initial for loop starts with index i=0 post the break in else condition

I am trying to implement a solution to merge two sorted arrays to a single sorted array.
I tried to implement a code but it does not work. The issue that I am seeing here is after my outer for loop reaches the limit of array2.length(), it still gets started from i=0. Can someone please help explain whats wrong in this piece of code?
List<Integer> mergedArray = new ArrayList<>();
int counter = 0;
public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
for (int i = 0; i < array1.size(); i++) {
for (int j = counter; j < array2.size(); j++) {
if (array1.get(i) > array2.get(j)) {
mergedArray.add(array2.get(j));
counter++;
} else {
mergedArray.add(array1.get(i));
System.out.println("i " +i);
break;
}
}
}
return mergedArray;
}
One problem I see with the code is when the two arrays do not have same length. In either case of (array1.length > array2.length or reverse) the remaining elements of longer array will not be processed. So if you add a more code at end of this the loops to deal with that case, this might work well!
public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
List<Integer> mergedArray = new ArrayList<>();
int counter = 0, i = 0, j = 0;
for (i = 0; i < array1.size(); i++) {
for (j = counter; j < array2.size(); j++) {
if (array1.get(i) > array2.get(j)) {
mergedArray.add(array2.get(j));
counter++;
} else {
mergedArray.add(array1.get(i));
System.out.println("i " +i);
break;
}
}
}
// More code here
if (j==array2.size()){//copy rest of array1 into mergedArray}
if (i==array1.size()){//copy rest of array2 into mergedArray}
return mergedArray;
}
I think you called the same method twice, without resetting the counter or the previous mergedArray.
You should declare those inside the method.
Additionally, after reaching the end of array1, you should check if there are remaining elements in array2, and vice-versa:
public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
List<Integer> mergedArray = new ArrayList<>();
int counter = 0;
for (int i = 0; i < array1.size(); i++) {
for (int j = counter; j < array2.size(); j++) {
if (array1.get(i) > array2.get(j)) {
mergedArray.add(array2.get(j));
counter++;
} else {
mergedArray.add(array1.get(i));
System.out.println("i " +i);
break;
}
}
if(counter >= array2.size()) {
mergedArray.add(array1.get(i));
}
}
for (int j = counter; j < array2.size(); j++) {
mergedArray.add(array2.get(j));
}
return mergedArray;
}
I think it works but problem is that you don't handle case when inner array size is equal or bigger than size of outer array. I rewrote your method (in way I think it`s right). Hope you'll find it useful.
public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
List<Integer> mergedArray = new ArrayList<>();
int index1 = 0;
int index2 = 0;
for (int i = 0; i < array1.size() + array2.size(); i++) {
Integer num1 = null;
Integer num2 = null;
if (index1 < array1.size()) {
num1 = array1.get(index1);
}
if (index2 < array2.size()) {
num2 = array2.get(index2);
}
if (num1 != null && num2 != null) {
if (num1 < num2) {
mergedArray.add(num1);
++index1;
} else {
mergedArray.add(num2);
++index2;
}
} else if (num1 != null) {
mergedArray.add(num1);
++index1;
} else {
mergedArray.add(num2);
++index2;
}
}
return mergedArray;
}
If your array2 has all the element less then array1[i]
in this case your logic also fails because your inner loop condition always fail
you can do this way
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (arry1[i] <= arry2[j]) {
TempArry[k] = arry1[i];
i++;
}
else {
TempArry[k] = arry2[j];
j++;
}
k++;
}
/* Copy remaining elements of array1[] if any */
while (i < n1) {
TempArry[k] = array1[i];
i++;
k++;
}

create an array and a function allowing deletion zeros rom the array

i have a code that create an array of 7 integers than the system have a function that check where array[i] == 0 will place zeros at the most right of the array and at the end the system display the original array and the compressed array like this
original array:
0 5 0 12 0 0 4
compressed array :
5 12 4 0 0 0 0
can anyone help me ??
this is the code
package question3;
import java.util.Scanner;
public class ArrayWithCompression {
static int[] array = new int[7];
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
System.out.println("enter numbers");
for(int i = 0 ; i< array.length; i++){
array[i] = sc.nextInt();
}
System.out.println(compression(array));
}
public static int[] compression(int[] newarray){
for(int i = 0; i< array.length; i++ ){
if(array[i] == 0){
array[i] = i++;
}
array[i] = newarray[i];
}
return newarray;
}
}
You are close to the right answer. I suggest you step through your code in your debugger to see what you are doing.
Since it is hard to give you a hint without giving you the answer...
public static int[] compression(int[] array){
int j = 0;
// iterate over all the numbers in the array.
for (int i : array)
// if the number is not 0 add it back into the array
if (i != 0)
// add it back only counting non-0 for the index
array[j++] = i;
// fill the rest of the array with zero.
Arrays.fill(array, j, array.length, 0);
}
you can try this code in your compression method:
public static int[] compression(int[] newarray){
int []arr= new int[newarray.length];
int j=0;
for(int i = 0; i< newarray.length; i++ ){
if(newarray[i] != 0){
arr[j++] = newarray[i];
}
}
return arr;
}
without using other array :
public static int[] compression(int[] newarray){
for(int i = 0; i< newarray.length; i++ ){
if(newarray[i] != 0){
continue;
}else
{
for(int j = i; j< newarray.length; j++)
{
if(newarray[j] != 0)
{
newarray[i]=newarray[j];
newarray[j]= 0;
break;
}
}
}
}
return newarray;
}
and you can change your main method (printing array ) :
array= compression(array);
for(int i = 0 ; i< array.length; i++){
System.out.println(array[i]);
}
You can try it out like:
for (int i = 0; i < arr.length - i; i++) {// loop decreases as after each loop a zero if found is put at last
for (int j = 0; j < arr.length - 1; j++) { // this loop puts first 0 in last by swapping each nos.
if (arr[j] == 0) {
arr[j] = arr[j + 1];
arr[j + 1] = 0;
}
}
}
return arr;
and in main function:
array = compression(array);
for (int i : array) {
System.out.println(i);
}

Java - Adding element at specific index and pushing other elements down

This feature is supposed to add an element at the selected index and push all other in the array elements down. So, for instance, say I have the following array:
[0] = zero
[1] = one
[2] = two
if I add another element at index 0 called NEWZERO, the array has to look like this:
[0] = NEWZERO
[1] = zero
[2] = one
[3] = two
but currently I'm getting IndexOutOfBounds exception and it doesn't work.
P.S. I don't want to use the built-in ArrayList library, which automatically does it for you.
public void insert(int i, String s) {
if (array[i] == null) {
array[i] = s; //Need to add feature that instantly puts the element at the first available spot on the list.
} else {
for (int j = i; j < array.length; j++) { //Can't use >= i
array[j + 1] = array[j];
if (j == array.length - 1) {
break;
}
}
array[i] = s;
Try this
public void insert(int i, String s) {
String[] newArr = new String[array.length + 1];
for (int j = 0; j < array.length; j++) {
if(j < i){
newArr[j] = array[j];
} else if(j == i){ // '==' insted of '='
newArr[j] = s;
} else {
newArr[j+1] = array[i];
}
}
array = newArr;
}
Well, arrays are not dynamic, so if you have an array that has size 3 you cannot add anything to it unless you create a new array that has size of oldArray.length+1 and then populate it with new data.
public static int[] addAtIndex(int[] a, int index, int value) {
int[] newArr = new int[a.length + 1];
int temp;
for (int j = 0; j < a.length + 1; j++) {
if (j < index) {
newArr[j] = a[j];
} else if (j == index) {
//copy value at index to temp so that value added at specific index can be shifted right
temp = a[j];
newArr[j] = value;
newArr[j + 1] = temp;
} else {
newArr[j] = a[index];
index++;
}
}
return newArr;
}

Debugging Mergesort Implementation

Okay, I know this question doesn't show research effort, but I've been going through this code so many times and I couldn't figure out was I was doing wrong. I know there are many Mergesort implementation examples but I wanted to do it my way. Any help is appreciated, thanks.
import java.util.Scanner;
public class MergeSort
{
public static int[] mergeSort(int[] arr)
{
if (arr.length > 1)
{
int[] arr1 = splitLeft(arr);
int[] arr2 = splitRight(arr);
arr1 = mergeSort(arr1);
arr2 = mergeSort(arr2);
return merge(arr1, arr2);
}
else
return arr;
}
public static int[] splitLeft(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[middle];
for (int i = 0; i < middle; i++)
newarr[i] = arr[i];
return newarr;
}
public static int[] splitRight(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[arr.length - middle];
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
return newarr;
}
public static int[] merge(int[] arr1, int[] arr2)
{
int[] sorted = new int[arr1.length+arr2.length];
int i1 = 0;
int i2 = 0;
int i = 0;
while (i1 < arr1.length && i2 < arr2.length)
{
if (arr1[i1] < arr2[i2])
{
sorted[i] = arr1[i1];
i1++;
}
else
{
sorted[i] = arr2[i2];
i2++;
}
i++;
}
while (i1 < arr1.length)
{
sorted[i] = arr1[i1];
i1++;
i++;
}
while (i2 < arr2.length)
{
sorted[i] = arr1[i2];
i2++;
i++;
}
return sorted;
}
public static int getNum(int x)
{
int num = (int)(Math.random()*x + 1);
return num;
}
public static void printArr(int[] arr)
{
System.out.println();
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
static Scanner reader = new Scanner(System.in);
public static void main(String [ ] args)
{
int i;
System.out.println("Type the length of the array");
int n = reader.nextInt();
System.out.println("Type the range of the random numbers generator");
int range = reader.nextInt();
int[]arr = new int[n];
for (i = 0; i < n; i++)
arr[i] = getNum(range);
printArr(arr);
int[] sorted = new int[n];
sorted = mergeSort(arr);
printArr(sorted);
}
}
I think the problem is in your splitRight function. Consider this code:
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
This tries to copy the ith element from arr to the ith position of newarr, but this is incorrect. For example, if the array arr has ten elements, you want to copy element 5 of arr to position 0 of newArr, element 6 of arr to position 1 of newarr, etc.
To fix this, consider trying something like this:
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
Hope this helps!
When you do
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
You are surely asking for positions in the original array and at the same time looking for them in the new array (which happens to be shorter).

Categories