Sum of digits in random generated arrays

Saeed Zaghdoudi :

I know this may stand for a silly question but I have got a lot of problems with this.
I will first explain how it should work :
1)Generate random Array with size in range <4,7>
2)Fill it with random elements in range <100, 999>
3)Print the index of three numbers with biggest digit sum
So the question is-how? I know I should implement this:

             SumOfDigits += ElementFromArray % 10;
              ElementFromArray /= 10;

But i have got no idea where. I tried to add this as a if (i>0) loop inside for loop-but its not working.
Also how at the end im going to print the proper elements? Should I use Arrays.sort(tab) and then System.out.println(tab[tab.length - 1]) (and so on with -2, -3 for 3 last elements)?

import java.util.Arrays;
import java.util.Random;

public class Ex1 {

    public static void main(String[] args) {
        Random rand = new Random();
        int size = rand.nextInt(4) + 4;

        int tab[] = new int[size];

        for (int i = 0; i < tab.length; i++) {
            int elements = rand.nextInt(900) + 100;
            tab[i] = elements;

        }
        System.out.println(Arrays.toString(tab));
    }
}
Samuel Silver Moos :

Just use while loop: here is a quick and dirty solution:

private static void main10(String[] args) {
    Random rand = new Random();
    int size = rand.nextInt(4) + 4;

    int[] tab = new int[size];

    for (int i = 0; i < tab.length; i++) {
        int element = rand.nextInt(900) + 100;
        tab[i] = element;

    }
    System.out.println(Arrays.toString(tab));
    // calculate digits:
    int[] digitsums = new int[size];
    for (int i = 0; i < tab.length; i++) {
        int element = tab[i];
        int sumOfDigits = 0;
        while (element > 0) {
            sumOfDigits += element % 10;
            element /= 10;
        }
        digitsums[i] = sumOfDigits;
    }
    System.out.println(Arrays.toString(digitsums));
    int[] copyOfdigitsums = Arrays.copyOf(digitsums, digitsums.length);
    for (int i = 1; i <= 3; i++) {
        int j = getIndexOfLargest(copyOfdigitsums);
        System.out.println("index of " + i + "largest is " + j + ", with a digitsum of " + copyOfdigitsums[j]);
        copyOfdigitsums[j] = 0;
    }
}

static int getIndexOfLargest(int[] digitsums) {
    int largest = 0;
    int index = 0;
    for (int i = 0; i < digitsums.length; i++) {
        int d = digitsums[i];
        if (largest < d) {
            largest = d;
            index = i;
        }
    }
    return index;

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=316772&siteId=1