首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印垂直直方图到控制台

打印垂直直方图到控制台
EN

Stack Overflow用户
提问于 2018-06-17 13:51:07
回答 1查看 933关注 0票数 1

我需要编写一个void方法() "printHistogram(int )“,该方法可以打印主人关于他们拥有的狗的直方图。参数为"int bin“,用于将直方图划分为间隔。最多一个用户可以养10只狗。因此,考虑bin = 5,这种情况下的间隔将是2,因为10/5 =2,因此,间隔为(0-5,5-10)。

代码语言:javascript
复制
_
_
_
_     _
0-5  5-10

类似的情况,这意味着4个用户的狗在0到5之间,等等。不需要知道获取狗数的方法等等,我只需要逻辑和算法。我真的需要帮助。谢谢。该方法的输出是打印"_“下划线并构造垂直直方图。

这是我的密码:-

代码语言:javascript
复制
public void drawHistogram(int bin) {

      int highestDogs = owners.get(0).countDogs(); //method for getting number of dogs of a user
      int intervals = 10/bin;
      int temp = 0;
      int tempBin = bin;

      for (int i =0; i < owners.size(); i++) 
      {
         tempBin = bin;
         temp = 0;
         do{
            System.out.println(i + "iteration" + " " + owners.get(i).countDogs() );
            if(owners.get(i).countDogs() >= temp && owners.get(i).countDogs() < tempBin)
            {

               if( tempBin > bin)
               {

                  System.out.print("    ");  
               }


               System.out.print("_  ");
               temp = tempBin;
               tempBin = bin + bin;
               System.out.println(tempBin);

            }
            else { 
               temp = tempBin;
               tempBin = bin + bin;

               System.out.println(tempBin);
            }

         }while(tempBin < 11);
         System.out.println();
      }

   }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-18 04:21:58

下面是绘制直方图的mcve。请注意以下评论:

代码语言:javascript
复制
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    static List<Integer> owners;  //represents number of dogs per owner
    static final int MAX_DOGS_NUM = 10;

    public static void main(String[] args) {
        //test data
        owners = Arrays.asList(new Integer[] {0,1,2,3,4,5,6});
        drawHistogram(2);
    }

    static void drawHistogram(int bin) {

        //todo add check to make sure bin < MAX_DOGS_NUM
        List<Column> columns = makeColumns(bin);
        calcColumnsData(columns);
        System.out.println(new Histogram(columns));
    }

    //construct all columns, set interval ends 
    private static List<Column> makeColumns(int bin) {

        List<Column> columns = new ArrayList<>();

        for (int i = 0 ; i <= MAX_DOGS_NUM ; i += bin ) {
            int intervalEnd = (i+ bin) > MAX_DOGS_NUM ? MAX_DOGS_NUM : (i+ bin);
            columns.add(new Column(i, intervalEnd));
            i++;
        }
        return columns;
    }

    //calculate quantity of each column 
    private static void calcColumnsData(List<Column> columns) {

        for(Column col : columns) {
            //count the number of owners who has dogs within interval 
            int ownersCounter = 0;   
            for(int numberOfDogs : owners) {
                if((numberOfDogs >= col.getInteravalStart())
                        && (numberOfDogs <= col.getIntervalEnd())) { ownersCounter++ ;}
            }
            col.setQty(ownersCounter); //update column quantity 
        }
    }
}

//represents a single histogram column
class Column {
    //interval ends, quantity of owners 
    int interavalStart, intervalEnd, qty =0;

    Column(int interavalStart, int intervalEnd) {
        this.interavalStart = interavalStart;
        this.intervalEnd = intervalEnd;
    }

    int getQty() {  return qty; }

    void setQty(int qty) {  this.qty = qty; }

    int getInteravalStart() {return interavalStart; }

    int getIntervalEnd() {return intervalEnd; }

    @Override
    public String toString() {
        return interavalStart +"-" +intervalEnd+": "+ qty;
    }
}

//represents histogram graph
class Histogram{

    private List<Column> columns; //histogram columns 
    //representation of graph mark and space 
    private static final String MARK = "-", SPACE =" ";
    private static final int COLUMN_WIDTH = 8; 
    private int maxHeight =0; //size of highest histogram 
    //histogram data. each row contains makrs or space. last 
    //row contains footer 
    private String graphRepresentation[][]; 

    Histogram(List<Column> columns) {
        this.columns = columns;
        calculateMaxHeight();
        prepareGraphRepresentation();
    }

    //find tallest column 
    private void calculateMaxHeight() {
        for(Column col : columns) {
            if(col.getQty() > maxHeight) { maxHeight = col.getQty();}
        }
        maxHeight +=1; //add 1 for column footer
    }

    //fill graphRepresentation with spaces, marks or footer 
    private void prepareGraphRepresentation() {

        graphRepresentation = new String[maxHeight][columns.size()];

        for(int colIndex = 0 ; colIndex < columns.size() ; colIndex ++ ) {

            Column col = columns.get(colIndex);
            int rowCounter = 0;

            for(int rowIndex = maxHeight -1 ; rowIndex >=0; rowIndex -- ) {

                String s = SPACE;
                if (rowCounter == 0 ) { //histogram footer
                     s = col.getInteravalStart()+"-"+col.getIntervalEnd();
                }else if(rowCounter <= col.getQty()) {
                    s = MARK;
                }
                graphRepresentation[rowIndex][colIndex] = format(s);
                rowCounter++;
            }
        }
    }

    //add spaces to s to make it as wide as column width
    private String format(String s) {

        int leftSpaces = (COLUMN_WIDTH - s.length())/2;
        int rightSpaces = COLUMN_WIDTH - s.length() - leftSpaces;

        StringBuilder sb = new StringBuilder();
        //add left spaces
        for(int spaces =0 ; spaces <leftSpaces; spaces++) {
            sb.append(SPACE);
        }
        sb.append(s);
        for(int spaces =0 ; spaces <rightSpaces; spaces++) {
            sb.append(SPACE);
        }

        return sb.toString();
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();
        for(String[] row : graphRepresentation ) {
            for(String s : row ) {
                sb.append(s);
            }
            sb.append("\n");
        }

        return sb.toString();
    }
}

输出:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50897286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档