Home > Enterprise >  How do find if an index of int array ends on a specific digit Java
How do find if an index of int array ends on a specific digit Java

Time:04-24

Hi guys, how are you? =) I'm new to Java, currently, I'm learning arrays and loops, and I'm really struggling with them at the moment.

I have a task to return an array of those numbers that end in 9. Do not change the order of the remaining numbers. The only thing I can use is a for loop.

My brain is kinda melted at the moment and I don't know what to do.

When I return a result, it returns as an int 3991599399.

At the moment I think about how to take the result outside the for loop. Сan you help me find a way to store all numbers with nines in a new array?

    
public int[] leavePrice9(int[] prices) {
        
    for (int i = 0; i < prices.length; i  ) {
            int result = prices[i];
            
            if (result % 10 == 9);
    }
}
    public static void main(String[] args) {
        QuadraticEquationSolver shop = new QuadraticEquationSolver();

        //Should be [399, 1599, 399]
        int[] prices = new int[] {399, 1599, 399, 50, 10, 10, 70};
        System.out.println(Arrays.toString(shop.leavePrice9(prices)));
    }
}

CodePudding user response:

You can use the following method getAllWithLastDigit(). It takes an array of int and a digit (0-9) and returns a new array containing all elements that have that specified digit as the last digit. The elements of the original array remain untouched and therefore the order is obviously preserved.

import java.util.*;

public class Application {
    public static void main(String[] args) {
        int[] prices = new int[]{399, 1599, 399, 50, 10, 10, 70};
        System.out.println(Arrays.toString(getAllWithLastDigit(prices, 9)));
    }

    public static int[] getAllWithLastDigit(int[] array, int lastDigit){
        if(lastDigit < 0 || lastDigit > 9) throw new IllegalArgumentException("lastDigit must be between 0 and 9!");
        var lst = new ArrayList<Integer>();
        for (int i = 0; i < array.length; i  ) {
            int result = array[i];
            if (result % 10 == lastDigit) lst.add(result);
        }
        // convert array list back to integer array
        return lst.stream().mapToInt(i -> i).toArray();
    }
}

Expected ouput:

[399, 1599, 399]

This uses an ArrayList to be able to dynamically add elements to the list whenever we encounter an element that has 9 as the last digit. In the end we need to convert the list back to an array as you want to return an array of integers.

What you did is just string concatenation, instead of doing this we now add the element to a list, convert that list back to an int array and return it. Your implementation misses the part where a new array is created and returned.

Edit

Here a version without using ArrayList. Here we first create an array capable of holding the maximum number of results and add a result to it while increasing a counter for each new element. Then we have to (possibly) shrink the array down so it only contains the number of elements that are actually within the array. For this we create a copy of the array with however many elements we have in our result.

import java.util.*;

public class Application {
    public static void main(String[] args) {
        int[] prices = new int[]{399, 1599, 399, 50, 10, 10, 70};
        System.out.println(Arrays.toString(getAllWithLastDigit(prices, 9)));
    }

    public static int[] getAllWithLastDigit(int[] array, int lastDigit){
        if(lastDigit < 0 || lastDigit > 9) throw new IllegalArgumentException("lastDigit must be between 0 and 9!");
        // create an array which has the same size as the input, this way we guarantee that we have enough space for all result
        int[] elements = new int[array.length];
        // counter of how many elements are in the array 
        int counter = 0;
        for (int i = 0; i < array.length; i  ) {
            int result = array[i];
            if (result % 10 == lastDigit) elements[counter  ] = array[i];
        }
        // now we need to create a new array which is exactly as long as we need it (if we don't have that already)
        if(counter == array.length) return elements;
        // Alternative: use Java API Arrays.copyOf(elements, counter)
        return copyArray(array, counter);
    }

    public static int[] copyArray(int[] array, int newLength){
        if(newLength < 0) throw new IllegalArgumentException("Length must not be < 0");
        var copy = new int[newLength];
        // make sure we don't go out of bounds because the new array could be longer than the old one
        var until = Math.min(array.length, newLength);
        // copy over all elements
        for (int i = 0; i < until; i  ) {
            copy[i] = array[i];
        }
        return copy;
    }
}

CodePudding user response:

Here is a version based on code of the O/P:

public int[] leavePrice9(int[] prices) {
    int count = 0;  // how many prices qualify? 
    int [] result = new int [prices.length]; // hold qualifying prices
    // worst case: every price will qualify.
    // result is large enough to handle worse case
        
    for (int i = 0; i < prices.length; i  ) {                               
            if (prices[i] % 10 == 9)
                 result[count  ] = prices [i];
    }
    return Arrays.copyOf (result, count);
}
    public static void main(String[] args) {
        QuadraticEquationSolver shop = new QuadraticEquationSolver();

        //Should be [399, 1599, 399]
        int[] prices = new int[] {399, 1599, 399, 50, 10, 10, 70};
        System.out.println(Arrays.toString(shop.leavePrice9(prices)));
    }
}
  • Related