![](/img/trans.png)
[英]Finding Min/Max/Avg When Benchmarking Sorting Algorithms - Java
[英]Java 2 array min max avg?
我如何创建一个循环以生成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的可用库功能。
快速n脏:对第二个数组使用第二个for循环,但不要再次重新初始化min,max等。
清洁方法将是使一个类包含最小值,最大值等,并提供一个传递此结果对象和数组的方法。 然后,该方法扫描数组并更新结果对象的最小值,最大值等。为每个数组调用该方法。
您为什么不尝试查看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实例。
我认为最好将每个用户的详细信息存储在单独的数据结构中,例如以下名为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);
}
}
分而治之:)是的,我知道这是一种用于算法技术的术语,在这种情况下,我的意思是...处理小零件。
首先具有一个简单数组的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]);
}
使用数组有点难看,所以最好创建一个类来保存最小值,最大值和平均值。 因此,让我们重构一下代码:
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:
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)。 如果values数组已完全加载到内存中,则使用三个不同的函数(因此读取数组3次)进行max / min / avg仍然是O(n)阶的算法,具有较大的常数。 凭借当今计算机的强大功能,常数是如此之小,以致在大多数情况下,您无法在同一循环中通过计算最小值/最大值/平均值来获得任何收益。 相反,您可以获得代码的可读性,例如,在Groovy中,minMaxAvg代码可以这样编写:
def values = [2,3,4,5,6,7];
println values.min()
println values.max()
println values.sum() / values.size()
遍历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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.