Search code examples
javaarraysloopslogicnested-loops

Logic in nested loops


The task is to create a program in Java that prints a histogram to the console, that shows the frequency distribution of a set of values

The program is to read integers in the range of 1-100 incl. and then produce a chart like the one on the given image.

enter image description here

So far, I have come up with the following solution, but the teacher says that it is too complex, and that there is an easier way to implement it.

No one from my class, has been able to see how though, but I can see what she is saying about the solution I have come up with, shown below, since there is a problem scaling it, when I use the first int in the filled array, to sort it.

public void printChart() 
{
    res = new int[10];

    for (int i = 0; i < ia.length; i++) {

        int firstDigit = 0;

        if (i > 10) {
            firstDigit = Integer.parseInt(Integer.toString(ia[i]).substring(0, 1));
        }       

        res[firstDigit] += 1;
    }

    for (int i = 0; i < res.length; i++) {

        System.out.format("%-10s %-5s", (i) + "1" + " - " + (i+1) + "0", "|");

        for (int o = 0; o < res[i]; o++) {
            System.out.print("*");
        }  

        System.out.println("");
    }
}

She suggested that I make a new array containing the same amount as the original array, sort of like what I have written here, but I can't seem to figure out how to loop through it, to print it out. She even says it's possible with no if sentences, so I imagine that I will have to write some condition(s) in the for loop.

public void printChart2()
{
    res = new int[NUMBERS];

    // Fill the other array, by counting the amount of a specific int
    // and placing it on the given relevant index
    for (int i = 0; i < ia.length; i++) {
        res[ia[i]] += 1;
    }

    for (int i = 0; i < res.length; i += 10) {

        System.out.format("%-10s %-5s", (i+1) + " - " + (i+10), "|");

    }
}

Here is my fields and constructor, just in case.

private final int NUMBERS = 100;
private final int RANDOMMAX = 99;
private int[] ia;
private int[] res;

public Arbitrary() 
{
    ia = new int[NUMBERS];

    for (int i = 0; i < NUMBERS; i++) {
        ia[i] = (int) (Math.random() * RANDOMMAX) + 1;
    }   

    printChart();
}

Solution

  • Your whole code should just be simple like this...

    int NUMBERS = 100;
    int RANDOMMAX = 99;
    int tableOutput[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    for (int i = 0; i < NUMBERS; i++) {
        int temp = (int) (Math.random() * RANDOMMAX) + 1;
        tableOutput[temp % 10]++;
    }
    for (int i = 1; i <= 10; i++) {
        System.out.print(i + " - " + i * 10 + "| ");
        for (int j = 0; j < tableOutput[i-1]; j++) {
            System.out.print("*");
        }
        System.out.println();
    }