0

如何创建一个循环来为 2 个数组列表生成最小值、最大值、平均值,到目前为止,我只为单个数组列表生成了最小值、最大值和平均值。

这些是 2 个数组 User[] 和 Withdrawals[]:

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 的可用库功能。

4

5 回答 5

0

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

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

于 2012-08-11T14:46:55.613 回答
0

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

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 实例。

于 2012-08-11T15:46:40.517 回答
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);
    }
}
于 2012-08-11T18:19:57.577 回答
0

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

首先有一个简单数组的最小值,最大值,平均值:

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]);
}

使用数组有点难读,所以如果你创建一个类来保存最小值、最大值、平均值会更好。所以让我们稍微重构一下代码:

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);
}

您没有在问题中指定它,但我假设您为每个用户都有一个数组(也许每次取款都是另一个数组)。现在你有了底部部分,我们可以切换到自上而下的思维

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

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

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

  1. 制作一个“表格”用户-> 取款,这就是您要对这两个数组执行的操作。数组中的用户索引就像一个“用户 ID”。当您了解 Map 时,您会发现可以为索引使用更好的表示。
  2. 拥有 Map 或数组只是关系 User->Withdrawls 的优化,但您可以用对象表示该关系(即 UserWithdrawls)

选项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()
于 2012-08-11T18:32:51.717 回答
0
  1. 使用 c++ STL 排序函数,根据第一列对 O(log(n)) 中的二维数组进行排序。
  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
于 2019-09-21T09:23:54.950 回答