Java 2阵列最小最大平均值?

Java 2阵列最小最大平均值?,java,Java,如何创建循环以生成两个数组列表的最小值、最大值和平均值,到目前为止,我只为单个数组列表生成了最小值、最大值和平均值以及总和 这是2个阵列用户[]和取款[]: 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 这是我尝试过的,因为我对以下两个阵列一无所知: double min = 0.0;

如何创建循环以生成两个数组列表的最小值、最大值和平均值,到目前为止,我只为单个数组列表生成了最小值、最大值和平均值以及总和

这是2个阵列用户[]和取款[]:

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
这是我尝试过的,因为我对以下两个阵列一无所知:

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;
}
double min=0.0;
双最大值=0.0;
双和=0.0;
双平均值=0.0;
对于(int i=0;i max){
最大值=取款[j];
}  
如果(取款[用户[i]]
如何根据每个用户的取款次数打印最小值、最大值、平均值

我已经计算了每个用户的取款次数


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

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


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

为什么不尝试查看Commons数学库中的代码?或者更好,用它代替重新发明轮子

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

我认为最好将每个用户的详细信息存储在一个单独的数据结构中,如下面名为
UserDrawals
的类

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);
    }
}
公共类程序1{
公共静态类用户撤回{
私有LinkedList撤回=新建LinkedList();
公共作废增加(双倍金额){
本.取款.增加(金额);
}
公共双getMinimum(){
Double min=此.drawings.get(0);
对于(双倍金额:本次提款)
如果(金额比较到(最小)0)最大=金额;
返回最大值;
}
公共双平均值(){
双倍和=新的双倍(0);
对于(双倍金额:本次提款)
总和+=金额;
return sum/this.drawings.size();
//如果在迭代期间更新取款列表,此方法将失败
}
/*您还可以将这三种方法组合成一个方法,并返回一个双对象数组,因为迭代是相同的*/
}
/*现在,您迭代两个数组列表(如果两个数组列表-‘用户’和‘取款’的大小不同,这将不起作用),并将与用户关联的取款数据存储在相应的映射值中-映射或关联数组是一个非常基本的数据结构,因此您的教授对此应该没有任何问题*/
私有HashMap撤回\u map=new HashMap();
公共程序1(ArrayList用户、ArrayList取款){
对于(inti=0;i分而治之:)
是的,我知道这是一个用于算法技术的术语,在这种情况下我的意思是…处理小部件

首先是简单阵列的最小值、最大值、平均值:

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库来完成作业,因此可以轻松完成自己版本的最小/最大函数(请阅读)

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

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)));
}
 def values = [2,3,4,5,6,7];
 println values.min()
 println values.max()
 println values.sum() / values.size()
好的,但这只是一个想法,您仍然存在将aUser与其取款关联起来的问题。您在这里有几个选项:

  • 创建一个“表”用户->取款,这就是您试图使用这两个数组所做的。数组中的用户索引就像一个“用户id”。当您了解Map时,您将看到您可以为索引使用更好的表示形式
  • 拥有一个映射或数组只是对关系User->drawrits的优化,但您可以用一个对象(即userdrawrits)表示该关系
  • 选项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]));
        }
    }
    
    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代码可以这样编写:

    for (User aUser : users) {
         System.out.println("User: " + aUser);
         System.out.println(ValueSummary.createFor(withdrawalsOf(aUser)));
    }
    
     def values = [2,3,4,5,6,7];
     println values.min()
     println values.max()
     println values.sum() / values.size()
    
    < L>按第一列对O(log(n))中的二维数组进行排序,使用C++ STL排序函数。
  • 在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;
    }
    

    是的,我想使用两种方法minvalue和maxvalue,然后调用它,但我应该从“零开始”创建这些min-max avg func,当我学习alice,这是java 1或更高版本时,这意味着什么?lol O.ojava有内置的数学函数-我想老师可能只是说你必须自己编写,而不是使用现有的方法。这就是他说的,所以我可以使用数学?请记住,学生应该从头开始编写代码,而不是尽可能使用Java的可用库功能。“我建议的解决方案a中没有一个要求您使用任何预构建类,那么您的问题是什么?@Durandal,我想创建第二个for循环,但用户是Int,取款是double,所以我不断收到错误…:(你能给我举一个例子,说明在执行此操作时,通常如何查看2个数组,这样我就可以了解