【问题标题】:histogram of sorted array排序数组的直方图
【发布时间】:2014-04-26 04:10:20
【问题描述】:

我必须对给定数组做一个直方图,数组中数字的频率应该用*标记。

我的程序有效,问题是如果数组中有负数,则数组排序不正确。

    public class Histogram {

//number in the counter is shown as *
private static String convertToStars(int num){
    StringBuilder builder = new StringBuilder();
    for(int j = 0; j < num; j++){
        builder.append('*');
    }
    return builder.toString();
}


public static void outputHistogram(Integer[] array) {

    //if array is empty
    if(array.length == 0){
        System.out.println("Keine Elemente vorhanden.");
        return;
    }

    //array is cloned, so it is possible to delete same numbers
    Integer[] copy = array.clone();
    Arrays.sort(copy);
    System.out.println(Arrays.toString(copy) + "\n");

    for(int i = 0; i < copy.length; i++){
        int counter = 1;

        for(int j = 0; j < copy.length; j++){

            if(i != j && array[i] == array[j]){
                counter++;
                copy[j] = null;
            }


        }

        if(copy[i] != null){            
            System.out.println("\t" + array[i] + "\t" + convertToStars(counter));
            }
    }
}


public static void main(String[] args) {
    Integer[] array = {2, 4, 23, 23, 23, 2, -8, 56, 4, 2};      
    Histogram h = new Histogram();
    System.out.println("Histogramm des Arrays: " );
    h.outputHistogram(array);
}

}

负数应排在正数之前。无法上传图片。无论如何,感谢您的帮助。

【问题讨论】:

    标签: java arrays histogram sorted


    【解决方案1】:

    您似乎在嵌套循环中互换了 arraycopy 的用法。

    您保留已放置的已排序 copy 以用于打印目的,并操作您的原始 array 和控制变量,否则您将丢失已放置的已排序数组的信息。

    for (int j = 0; j < copy.length; j++) {
    
        if (i != j && copy[i] == copy[j]) {
            counter++;
            array[j] = null;
        }
    
    }
    
    if (array[i] != null) {
        System.out.println("\t" + copy[i] + "\t"
                + convertToStars(counter));
    }
    

    给出正确的输出,

    Histogramm des Arrays: 
    [-8, 2, 2, 2, 4, 4, 23, 23, 23, 56]
    
        -8  *
        2   ***
        4   **
        23  ***
        56  *
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2021-11-10
      • 2014-12-03
      • 2017-07-17
      • 2022-01-17
      • 1970-01-01
      • 2021-07-02
      相关资源
      最近更新 更多