Java 2阵列min max avg?

时间:2012-08-11 14:41:03

标签: java

如何创建一个循环来为2个数组列表生成min,max,avg,到目前为止,我只为单个数组列表生成了min,max和avg。

这是2个阵列User []&取款[]:

User, Withdrawals
1 , 90.00
2 , 85.00
4 , 75.00
5 , 65.00
2 , 40.00
1 , 80.00
3 , 50.00
5 , 85.00
4 , 80.00
1 , 70.00

size = 10

这是我尝试过的,因为我不知道2个阵列是否相互依赖:

double min = 0.0;
double max = 0.0;
double sum = 0.0;
double avg = 0.0;

for(int i = 0; i <size; i++){
.
.
for(int j = 0; j < Withdrawals.length; j++){
   if(Withdrawals[User[i]] > max){  
      max = Withdrawals[j];  
   }  
   if(Withdrawals[User[i]] < min){  
      min = Withdrawals[j];  
   }
}  
sum += Withdrawals[j];
avg = sum/size;
}

如何从每个用户的提款数打印最小值,最大值,平均值? :S

我已经计算了每位用户的提款次数。

条件是:从头开始创建所有内容,而不是使用Java的可用库功能。

5 个答案:

答案 0 :(得分:0)

Quick n Dirty:对第二个数组使用第二个for循环,但不要再次重新初始化min,max等。

Cleaner将创建一个类来保存min,max等,以及一个传递此结果对象和数组的方法。然后该方法扫描数组并更新结果对象min,max等。为每个数组调用方法。

答案 1 :(得分:0)

为什么不尝试查看Commons Math库中Descriptive Statistics的代码?或者更好的是,使用它而不是重新发明轮子?

DescriptiveStatistics de = new DescriptiveStatistics();

de.addValue(..) // Your values
// Add more values

Double max = de.getMax();
Double min = de.getMin();
Double avg = de.getSum() / de.getN(); // or de.getMean();

为每个数组使用DescriptiveStatistics实例。

答案 2 :(得分:0)

我认为如果您将每个用户的详细信息存储在单独的数据结构中,例如以下名为UserWithdrawals的类,那会更好。

public class Program1{
    public static class UserWithdrawals{
        private LinkedList<Double> withdrawals=new LinkedList<>();

        public void add(Double amt){
            this.withdrawals.add(amt);
        }

        public Double getMinimum(){
            Double min=this.withdrawals.get(0);
            for(Double amt:this.withdrawals)
                if(amt.compareTo(min)<0) min=amt;
            return min;
        }

        public Double getMaximum(){
            Double max=this.withdrawals.get(0);
            for(Double amt:this.withdrawals)
                if(amt.compareTo(max)>0) max=amt;
            return max;
        }


        public Double getAverage(){
            Double sum=new Double(0);
            for(Double amt:this.withdrawals)
                sum+=amt;
            return sum/this.withdrawals.size();
            //this method will fail if the withdrawals list is updated during the iteration
        }

        /*You can also combine the three into a single method and return an array of Double object coz the iteration is same.*/

    }

    /*now you iterate over your two array lists (This wont work if the two array lists - 'Users' and 'Withdrawals' are of different size) and store the withdrawal data associated with a user in the corresponding map value - Maps or Associative arrays are a very basic data structure so your professor should not have any problems with this*/

    private HashMap<Integer,UserWithdrawals> withdrawals_map=new HashMap<>();

    public Program1(ArrayList<Integer> Users, ArrayList<Double> Withdrawals){
        for(int i=0;i<Users.size();i++){
            Integer user_no=Users.get(i);
            Double withdrawal_amt=Withdrawals.get(i);
            if(this.withdrawals_map.get(user_no)==null){
                this.withdrawals_map.put(user_no,new UserWithdrawals());
            }
            this.withdrawals_map.get(user_no).add(withdrawal_amt);
        }
    }

    public UserWithdrawals getUserWithdrawalsData(Integer user_no){
        return this.withdrawals_map.get(user_no);
    }
}

答案 3 :(得分:0)

分而治之:) 是的,我知道这是一个用于算法技术的术语,在这种情况下我的意思是......使用小部件。

首先使用简单数组的min,max,avg:

double[] values = {2,3,4,5,6,7};

double min = values[0];
double max = values[0];
double sum = 0;

for (double value : values) {
     min = Math.min(value, min);
     max = Math.max(value, max);
     sum += value;
}

double avg = sum / values.length;

System.out.println("Min: " + min);
System.out.println("Max: " + max);
System.out.println("Avg: " + avg);

注意:由于您无法使用Java库进行分配,因此很容易使用自己的min / max函数版本(请阅读Math JavaDoc

现在您可以将此代码封装在一个函数中,您可以从返回另一个数组开始:

static double[] minMaxAvg(double[] values) {
    double min = values[0];
    double max = values[0];
    double sum = 0;

    for (double value : values) {
        min = Math.min(value, min);
        max = Math.max(value, max);
        sum += value;
    }

    double avg = sum / values.length;

    return new double[] {min, max, avg};
}

public static void main(String[] args) {
    double[] values = {2,3,4,5,6,7};
    double[] info = minMaxAvg(values);
    System.out.println("Min: " + info[0]);
    System.out.println("Max: " + info[1]);
    System.out.println("Avg: " + info[2]);
}

使用数组有点难看,所以如果你创建一个类来保存min,max,avg会更好。所以让我们稍微重构一下代码:

class ValueSummary {
    final double min;
    final double max;
    final double avg;

    static ValueSummary createFor(double[] values) {
        double min = values[0];
        double max = values[0];
        double sum = 0;

        for (double value : values) {
            min = Math.min(value, min);
            max = Math.max(value, max);
            sum += value;
        }

        double avg = sum / values.length;

        return new ValueSummary(min, max, avg);
    }

    ValueSummary(double min, double max, double avg) {
        this.min = min;
        this.max = max;
        this.avg = avg;
    }

    public String toString() {
        return "Min: " + min + "\nMax: " + max +"\nAvg: " + avg;
    }
}


public static void main(String[] args) {
    double[] values = {2,3,4,5,6,7};
    ValueSummary info = ValueSummary.createFor(values);
    System.out.println(info);
}

你没有在你的问题中指定它,但我假设你有一个每个用户的数组(也许每个提取是另一个数组)。 现在你有了底部部分,我们可以切换到top-down thinking

所以你的代码可能是这样的:

for (User aUser : users) {
     System.out.println("User: " + aUser);
     System.out.println(ValueSummary.createFor(withdrawalsOf(aUser)));
}

好的,但这只是想法,你仍然有问题将aUser与其提款联系起来。你有几个选择:

  1. 制作“表格”用户 - &gt;提取,这是你试图用两个数组做的。数组中的用户索引就像一个“用户ID”。当您了解Map时,您将看到可以使用更好的索引表示。
  2. 拥有Map或数组只是User-&gt; Withdrawls关系的优化,但您可以表示与对象的关系(即UserWithdrawls)
  3. 选项1:

    static class User {
        final String name;
        public User(String s) { name = s; }
    }
    public static void main(String[] args) {
        User[] users = { new User("John"), new User("Doe")};
        double[][] withdrawals = {
             new double[] { 1, 2, 3}, new double[] { 10,22, 30} 
        };
        for (int i = 0; i < users.length; i++) {
            System.out.println("User: " + users[i].name);
            System.out.println(ValueSummary.createFor(withdrawals[i]));
        }
    }
    

    选项2:

    static class User {
        final String name;
        public User(String s) { name = s; }
    }
    static class UserWithdrawls {
        final User user;
        final double[] withdrawals;
        final ValueSummary summary;
        UserWithdrawls(User user, double[] withdrawals) {
            this.user = user;
            this.withdrawals = withdrawals;
            this.summary = ValueSummary.createFor(withdrawals);
        }
    }
    public static void main(String[] args) {
        UserWithdrawls[] userWithdrawls = {
                new UserWithdrawls(new User("John"), new double[] { 1, 2, 3}),
                new UserWithdrawls(new User("Doe"), new double[] { 10, 22, 30})
        };
        for (UserWithdrawls uw : userWithdrawls) {
            System.out.println("User: " + uw.user.name);
            System.out.println(uw.summary);
        }
    }
    

    补充说明:如果您正在学习计算机科学,您将来会了解到计算max,min,avg的循环的复杂度为O(n)。如果值数组在内存中完全加载,则在三个不同的函数中执行max / min / avg(因此读取数组3次)仍然是具有更大常量的O(n)阶的算法。凭借当今计算机的强大功能,常数非常小,大多数情况下,在同一循环中计算min / max / avg无法获得任何收益。相比之下,您可以获得代码可读性,例如在Groovy中,minMaxAvg代码可以这样写:

     def values = [2,3,4,5,6,7];
     println values.min()
     println values.max()
     println values.sum() / values.size()
    

答案 4 :(得分:0)

  1. 使用c ++ STL Sort函数,根据第一列对O(log(n))中的2D数组进行排序。
  2. 遍历O(n)以计算平均值并更新MaxAverage。

    // Driver function to sort the 2D vector
    // on basis of a particular column
    
    bool sortcol( const vector<int>& v1, const vector<int>& v2 ) {
        return v1[0] < v2[0];
    }
    
    void sortMatrix()
    {
    // Initializing 2D vector "vect" with
    // values S_ID,MARKS
    vector< vector<int> > vect{{1,85}, {2,90}, {1,87}, {1,99}, {3,70}};
    
    // Number of rows
    int m = vect.size();
    
    // Number of columns
    int n = vect[0].size();
    
    // Use of "sort()" for sorting on basis
    // of 1st column
    sort(vect.begin(), vect.end(),sortcol);
    
    float maxAverage=-1;
    int id=1; // assuming it starts from 1.
    float sum=0;
    int s=0; // size of marks per student to calculate average
    for( int i=0; i<m; i++ )
    {
        sum+=vect[i][1];
        s=s+1;
        if( i+1!= m && vect[i+1][0] != vect[i][0] ){// gotten all the marks of this student
            maxAverage = maxAverage>sum/s? maxAverage:sum/s;
            id = vect[i][0];
            s=0;
            sum=0;
        }
    }
    cout<<"ID: "<<id<<"\tValue: "<<maxAverage<<endl;
    }
    

输出:

ID: 2   Value: 90.3333