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

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];
}
}

Related

DeleteZero's using Java

I need to finish this code which involves deleting all the zero's stored in the array. I thought it was complete but it won't compile, it's my last line that is dubios and I'm not getting right. Thank you.
public class DeleteZero {
public static int[] array(int[] a) {
int k = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] !=0)
k++;
}
int[] b = new int[k];
int t = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
b[t] = a[i];
t++;
}
}
return b;
}
public static void main (String args[]) {
int[] rand = new int[20];
for (int i = 0; i < 20; i++) {
rand[i] = (int)(Math.random());
}
System.out.println(array(a));
}
}
Few errors.
This would always insert 0 at rand[i] because you are casting Math.random() to int which will always become zero.
rand[i] = (int)(Math.random());
Change it to sth like this. I have written 10 but you can write any number to define the range.
rand[i] = (int)(Math.random()*10);
This line is also wrong:
System.out.println(array(a));
You need to print the array by looping over it, but more importantly your function array() returns a new array, which should be stored somewhere before printing it.
Here is a possible workaround
rand = array(rand);
for (int i=0; i<rand.length; i++){
System.out.println(rand[i]);
}
The compile time error is due to the fact that, in the main method you have created the array named rand and passing the array named a. from the main method call System.out.print(array(rand))
You can try Java 8's Stream, which turns the whole logic to one line return Arrays.stream(a).filter(n -> n!= 0).toArray();
Little fixed your code:
import java.util.Random; // Import Random
public class DeleteZero {
public static int[] array(int[] a) {
int k = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] !=0)
k++;
}
int[] b = new int[k];
int t = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
b[t] = a[i];
t++;
} else {
System.out.println("Skip at position: [" + i + "] because a[i] == "+a[i]+";"); // Display what removed.
}
}
return b;
}
public static void main (String args[]) {
int[] rand = new int[20];
Random rnd = new Random();
for (int i = 0; i < 20; i++) {
rand[i] = rnd.nextInt(11) + 0; // 11-1 = max, 0 = min
}
int[] a = array(rand);
System.out.println(a); // since it prints something like this: [I#106d69c, we should print all elements manually through a loop.
System.out.println("a.length = " + a.length + ", rand length: " + rand.length);
System.out.print("[");
for (int i = 0; i != a.length; i++) {
String space = ", ";
if (i == a.length-1) //if last not print space
space = "";
System.out.print(a[i]+space); // Print all elements
}
System.out.print("]\n");
}
}
Example of output:
Skip at position: [2] because a[i] == 0;
Skip at position: [8] because a[i] == 0;
Skip at position: [10] because a[i] == 0;
Skip at position: [12] because a[i] == 0;
Skip at position: [16] because a[i] == 0;
[I#106d69c
a.length = 15, rand length: 20
[6, 8, 1, 8, 7, 1, 3, 5, 3, 8, 5, 2, 7, 2, 8]

Bring ints that are even to the froont of the array

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;
}

Given an array with odd length, look at the first, last, and middle values in the array and return an array with those three values

So for any given odd length array, I need to look at the first, middle and last value, and return an array with only hose 3 values but in ascending order.This is what I have, but it's only working with arrays of 3 elements, it's not working for other odd length arrays:
public int[] maxTriple(int[] nums) {
int toSwap, indexOfSmallest = 0;
int i, j, smallest;
for( i = 0; i < nums.length; i ++ )
{
smallest = Integer.MAX_VALUE;
for( j = i; j < nums.length; j ++ )
{
if( nums[ j ] < smallest )
{
smallest = nums[ j ];
indexOfSmallest = j;
}
}
toSwap = nums[ i ];
nums[ i ] = smallest;
nums[ indexOfSmallest ] = toSwap;
}
return nums;
}
You're getting the sorted array, so if you need just the first, middle and last values you can try it like this:
public int[] maxTriple(int[] nums) {
int toSwap, indexOfSmallest = 0;
int i, j, smallest;
for( i = 0; i < nums.length; i ++ )
{
smallest = Integer.MAX_VALUE;
for( j = i; j < nums.length; j ++ )
{
if( nums[ j ] < smallest )
{
smallest = nums[ j ];
indexOfSmallest = j;
}
}
toSwap = nums[ i ];
nums[ i ] = smallest;
nums[ indexOfSmallest ] = toSwap;
}
nums=new int[]{nums[0],nums[(nums.length/2)],nums[nums.length-1]};
return nums;
}
You're thinking about this too hard. If the length of your array is less than 3 or even, return null.
Otherwise, get the first element, the last element, and the middle element and store them in a new array. Sort the array with Arrays.sort() and return the new array.
public static void main(String[] args) throws Exception {
System.out.println(Arrays.toString(maxTriple(new int[] {1, 4, 2, 4})));
System.out.println(Arrays.toString(maxTriple(new int[] {1, 4, 2, 4, 5})));
System.out.println(Arrays.toString(maxTriple(new int[] {75, 99, 4, 999, 4, 65, 23})));
}
public static int[] maxTriple(int[] nums) {
if (nums.length < 3 || nums.length % 2 == 0) {
return null;
}
int[] result = new int[3];
result[0] = nums[0]; // First
result[1] = nums[nums.length - 1]; // Last
result[2] = nums[nums.length / 2]; // Middle
Arrays.sort(result);
return result;
}
Results:
null
[1, 2, 5]
[23, 75, 999]
I used another approach with ternary operators. I hope it can be useful...
public int maxTriple(int[] nums) {
return (nums[0] > nums[nums.length/2]) ? (nums[0] > nums[nums.length-1] ?
nums[0] : nums[nums.length-1]) : (nums[nums.length/2] > nums[nums.length-1]
? nums[nums.length/2] : nums[nums.length-1]);
}
This code works fine:
public int[] maxTriple(int[] nums) {
int[] myArray = new int[3];
int length = nums.length;
int middle = nums[(length + 1) / 2 - 1];
int last = nums[length - 1];
int first = nums[0];
myArray[0] = nums[0];
myArray[1] = nums[middle];
myArray[2] = nums[last];
return myArray;
}
What you are tyring to do is called selection sort. Here is the code for that:
int[] maxTriple(int[] nums, int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = i; j < size; j++) {
if (nums[j] < nums[i]) {
int toSwap = nums[i];
nums[i] = nums[j];
nums[j] = toSwap;
}
}
}
return nums;
}

Java > Array-2 > zeroMax

my code only misses 5 cases and i dont know why, somebody help me.
problem
Return a version of the given array where each zero value in the array
is replaced by the largest odd value to the right of the zero in the
array. If there is no odd value to the right of the zero, leave the
zero as a zero.
zeroMax({0, 5, 0, 3}) → {5, 5, 3, 3}
zeroMax({0, 4, 0, 3}) → {3, 4, 3, 3}
zeroMax({0, 1, 0}) → {1, 1, 0}
my code
public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for( i = 0; i < nums.length;i++){
if(nums[i]==0){
for(int j = i; j < nums.length;j++){
if (nums[j]%2!=0){
acum = nums[j];
break;
}
}
nums[i]=acum;
}
}
return nums;
}
This can be done much more efficiently by rearranging the problem a bit.
Instead of traversing left-to-right, then scanning the integers on the right for the replacement, you can instead just go right-to-left. Then, you can store the previous replacement until you encounter a larger odd number.
public int[] zeroMax(final int[] nums) {
int replace = 0; // Stores previous largest odd - default to 0 to avoid replacement
for (int i = nums.length - 1; i >= 0; i--) { // start from end
final int next = nums[i];
if (next == 0) { // If we should replace
nums[i] = replace;
} else if (next % 2 == 1 && next > replace) {
// If we have an odd number that is larger than the replacement
replace = next;
}
}
return nums;
}
Given your examples, this output:
[5, 5, 3, 3]
[3, 4, 3, 3]
[1, 1, 0]
What you are missing is, that there could be more than one odd number on the right side of your zero and you need to pick the largest one.
Edit: And you also need to reset 'acum'. I updated my suggestion :)
Here's a suggestion:
public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for (i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
for (int j = i; j < nums.length; j++) {
if (nums[j] % 2 != 0 && nums[j] > acum) {
acum = nums[j];
}
}
nums[i] = acum;
acum = 0;
}
}
return nums;
}
public int[] zeroMax(int[] nums) {
for (int i=0; i<nums.length; i++)
{
if (nums[i] == 0)
{
int maxindex = i;
for (int j=i+1; j<nums.length; j++)
{
if ((nums[j]%2 == 1) && (nums[j] > nums[maxindex]))
{
maxindex = j;
}
}
nums[i] = nums[maxindex];
}
}
return nums;
}
This alows you to find the index of the maximum odd number to the right, replacing the zero with the number at that index
The basic problem is that this algorithm doesn't search for the biggest odd value, but for the first odd value in the array, that is to the right of a given value. Apart from that, you might consider creating a table for the biggest odd value for all indices to simplify your code.
Here is one of the possible solutions to this :)
public int[] zeroMax(int[] nums) {
for(int i=0;i<nums.length;i++){
if(nums[i] == 0){
int val = largestOddValue(nums,i);//finding largest odd value
nums[i] = val; // assigning the odd value
}
}
return nums;
}
//finds largest odd value from the index provided to end
public int largestOddValue(int[] nums,int i){
int value = 0; // for storing value
for(int k=i;k<nums.length;k++){
if(nums[k]%2!=0 && value<nums[k]) // got the odd value
value = nums[k];
}
return value;
}
public int[] zeroMax(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 0) {
int max = 0;
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] % 2 != 0 && nums[j] > max) {
max = nums[j];
}
}
nums[i] = max;
max = 0;
}
}
return nums;
}
public int[] zeroMax(int[] nums) {
int val = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 0) {
for(int j = i + 1; j < nums.length; j++) {
if(val <= nums[j]) {
if(nums[j] % 2 == 1) {
val = nums[j];
}
}
}
nums[i] = val;
val = 0;
}
}
return nums;
}
public int[] zeroMax(int[] nums) {
int[] result = nums.clone();
for (int i = nums.length - 1, max = 0; i >= 0; i--)
if (isOdd(nums[i])) max = Math.max(nums[i], max);
else if (nums[i] == 0) result[i] = max;
return result;
}
boolean isOdd(int num) { return (num & 1) == 1; }
We iterate backwards, always storing the biggest encountered odd number (or 0, if none was found) in max.
When we find a 0, we simply override it with max.
The input is untouched to avoid ruining somebody else's input.
Here is the code which works for every input. Try this on your IDE
public int[] m1(int a[]){
int j = 0;
for (int i = 0; i < a.length; i++) {
if(a[i]!=0){
continue;
}
else if(a[i]==0){
j=i;
while(j<a.length){
if(a[j] % 2 != 0){
if(a[i]<=a[j]){
a[i] = a[j];
j++;
}
else{
j++;
continue;
}
}
else{
j++;
continue;
}
}
}
}
return a;
}

Find out the odd value and meet criteria in java

I would like to write a function in java that receives a parameter and returns 1 or 0, in the following conditions:
If the length of the array is odd, return 1 if the sum of the odd numbers is greater than the sum of the even numbers, and 0 otherwise.
If the length of the array is even, check the largest number less or equal then 10. If it is odd, return 1. If it is even, return 0.
For example, using the following arrays:
array1 = {13, 4, 7, 2, 8}
array2 = {11, 7, 4, 2, 3, 10}
The first array returns 1, because there 13(odd) + 7(odd) = 20 is greater then 4 + 2 + 8 = 14.
The second array returns 0, because there 11, 7 are odd but, 10 is greater then 7.
What I already tried, please check below:
public static int isOddHeavy(int[] arr) {
int summationOd = 0;
int summationEv = 0;
for (int i = 0; i < arr.length; i++) {
if (i % 2 != 0) {
summationOd = sumOddEven(arr);
} else {
summationEv = sumOddEven(arr);
}
}
if(summationOd > summationEv) {
return 1;
} else {
return 0;
}
}
public static int sumOddEven(int[] arr) {
int total = 0;
for (int i = 1; i < arr.length; i++) {
total += arr[i];
}
return total;
}
Here is a Java function that does what you want. Just iterate through the array, updating the variables and check your conditions in the end.
public static int yourFunction(int[] arr) {
int sumOdd = 0;
int sumEven = 0;
int maxOdd = 0;
int maxEven = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
sumEven += arr[i];
if (maxEven < arr[i] && arr[i] <= 10)
maxEven = arr[i];
}
else {
sumOdd += arr[i];
if (maxOdd < arr[i] && arr[i] <= 10)
maxOdd = arr[i];
}
}
if (arr.length%2 != 0)
return (sumOdd > sumEven) ? 1 : 0;
return (maxOdd > maxEven) ? 1 : 0;
}

Categories