【问题标题】:How to store the result of each iteration of a for loop into an array in java如何将for循环的每次迭代的结果存储到java中的数组中
【发布时间】:2017-12-18 15:20:38
【问题描述】:

分数查找器(100 分)

Praveen 正在学校找一份计算机科学教师的工作。 他曾多次被不同学校拒绝,但这次他下定决心要得到这份工作。 他去找圣玛丽学校的校长。

校长说他的学校有评分和学分制度。 有 N 个科目,每个科目都有一个学分 Ci (1

A = 10, 
A(minus) = 9, 
B = 8, 
B(minus) = 7, 
C = 6, 
C(minus) = 5 

现在如果有 3 门科目分别为 4、3 和 2 学分,并且某个学生的成绩为 A(减), 分别在这 3 个科目中获得 B 和 C,那么他的分数将计算如下: 总分=每个科目的学分乘积和相应学分的总和。

= ( (9*4) + (3*8) + (2*6) ) = 72.

他希望 Praveen 说出可能的总分 通过为每个科目分配不同的成绩,给予学生 N 个科目的学分。

输入格式 您的函数包含一个参数 - N 个元素的一维整数数组 A,其中每个元素代表该主题的信用。 输入的第一行包含一个表示数组大小的整数 N。 接下来的 N 行输入,每行包含一个表示第 i 个主题的信用 Ci 的整数

Constraints
1 <= N <= 100
1 <= Ci <= 5

输出格式 您必须返回一个整数,表示可以给出的总分数。

Sample TestCase 1
Input

2
1
2
Output

16

现在我正在编写这样的代码

package javaapplication1;

import java.util.Scanner;

public class CandidateCode {
    private static void possibleCombination(int input) {
        int i=0;
        int[] a=new int[Grades.length];

        a[i]=input;
        System.out.println("the a is "+a[i]);
    }

    private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

    public static void main(String[] args) {
        int i=0,j,totalSummation=0;
        Scanner uInput = new Scanner(System.in);
        System.out.println("Enter length of Array:");
        int index = uInput.nextInt();
        int[] Credit = new int[index];
        for (i = 0; i <= Credit.length-1; i++) {
            Credit[i] = uInput.nextInt();
            System.out.println("credit is" + Credit[i]);
            for ( j = 0; j <= Grades.length - 1; j++) {
                totalSummation = +(Grades[j] * Credit[i]);
                possibleCombination(totalSummation);
                // System.out.println("total sum is " + totalSummation);
            }
        } 
    }
}

现在我想存储在每次迭代中计算的值... 意义为 首先迭代值是 10,9,8,7,6,5,4,3,2,1 迭代第二个值是 20,18,16,14,10,8,6,4,2

我想将第一次迭代的每个值与第二次迭代的所有值相加。 i,e 10+20, 10+18, 10+16, 10+14, 10+10, 10+8, 10+6, 10+4, 10+2 同样适用于 9,8,7,6,5,4,3,2,1

为了实现这一点,我需要存储每次迭代的值,但我被困在这里,请大家帮我解决这个问题,谢谢。

【问题讨论】:

  • 你有两个 for 循环。我了解您希望在第二次迭代中存储值。一种可能的解决方案是使用多维数组(array[][])。在第一个循环之前声明。在第一个循环中声明了第二个:每次迭代第二个循环将项目存储在第二个数组中。在每个第二个循环之后,您将此数组存储在第一个它将产生一个数组,其中包含表示您的第二个 for 循环的值的数组。编辑:阅读我的评论后,我不确定它是否容易理解,如果你愿意,我会做出更详细的回答
  • 我同意你 polu ..但挑战是通过使用一维数组来实现相同的目标:-(
  • 如果您提供更详细的解释,您会很高兴..此外,输出可以是 1 到 100 之间的任何值,所以我们需要一个可以工作并通过所有测试用例的代码
  • 好吧,我不明白这部分挑战。所以你想要学分*等级的总和?我们可以假设成绩和学分具有相同的基数吗?
  • 是的,大小相同

标签: java arrays


【解决方案1】:
    import java.io.*;
    import java.util.*;
    import java.util.stream.Collectors;
    public class Sample {
        public static void main(String args[] ) throws Exception {

            Scanner scan = new Scanner(System.in);
            int nValue = scan.nextInt();
            if(nValue<1 || nValue>100){
                System.out.println("Array Value cannot be less than 1 or greater than 100");
            }
            int[] inputCredits = new int[nValue];
            for( int i=0 ; i < nValue ; i++){
                inputCredits[i]=scan.nextInt();
                if(inputCredits[i]<1 || inputCredits[i]>5){
                    System.out.println("Credit Value cannot be less than 1 or greater than 5");
                }
            }
            List<Integer> list1 = Arrays.stream(inputCredits).boxed().collect(Collectors.toList());
            List<Integer> list2 = Arrays.asList(5,6,7,8,9,10);
//checked for basic constraints up till this point
//Next what we multiply all the inputted Credits with the possible grades and 
// store in the list where x input Credits will produce a list of x*6 entries 
// where first six entries are the possibilities for the first Credit, next 6 
// entries for the 2nd credit and so on, having this knowledge we loop through // the list to get all the possible scores 
            List<Integer> permutedList = list1.stream().flatMap(i -> list2.stream().map(j -> i*j)).collect(Collectors.toList());

            List<Integer> listForDistinctSet= new ArrayList<Integer>();
            for(int i=0; i<6 ; i++){
                listForDistinctSet.add(permutedList.get(i));
            }
            Set<Integer> distinctSet = new HashSet<Integer>();

            for(int j=6,k=j+6;k<=permutedList.size();j=k,k=k+6){
                Set<Integer> newSet = new HashSet<Integer>();
                for(int i=0; i<listForDistinctSet.size(); i++){

                    for(; j<k ; j++){
                        int sum = listForDistinctSet.get(i) + permutedList.get(j);
                        newSet.add(sum);
                    }
                    j=k-6;
                }
                distinctSet=newSet;
                listForDistinctSet = new ArrayList<>(distinctSet);
            }
            System.out.println(distinctSet.size());

       }
    }

【讨论】:

  • 您能解释一下这段代码的作用以及它如何解决 OPs 问题吗?
  • @udaya 非常感谢 kiran ..完美通过所有测试用例
  • @Al0x :将 cmets 添加到代码中以解释其作用
【解决方案2】:

如果您不想存储在多维数组中,则需要将每次迭代存储在单维数组中,如下所示。但此代码仅适用于两个学分。

public class CandidateCode {

        private static int possibleCombination(int input)
        {   int i=0;
            int[] a=new int[Grades.length];
             a[i]=input;
              return a[i];

        }
        private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5, 4, 
                           3, 2, 1};

        public static void main(String[] args) {
            int i=0,j,totalSummation=0;
            Scanner uInput = new Scanner(System.in);
            System.out.println("Enter length of Array:");
            int index = uInput.nextInt();             
            int[] Credit = new int[index];
            int[] creditarr = new int[10];
            int[] credit1 = new int[10];
            int[] credit2 = new int[10];
            for (i = 0; i <= Credit.length-1; i++) {
                Credit[i] = uInput.nextInt();

                System.out.println("credit is" + Credit[i]);
                for ( j = 0; j <= Grades.length - 1; j++) {
                    totalSummation = +(Grades[j] * Credit[i]);
                     creditarr[j]=possibleCombination(totalSummation);
                     if(Credit[i]==1) {
                     credit1[j]=creditarr[j];  
                     }
                     if(Credit[i]==2){
                     credit2[j]=creditarr[j];
                     }
                    }
                }

            for(int k=0;k<credit1.length;k++) {
                for(int l=0;l<credit2.length;l++) {
                    int final_no=credit1[k]+credit2[l];
                    System.out.println("final_no :"  +final_no);
                }
            }
            }

         }

这是你想要的吗?

我想下面的代码将是最好的解决方案。此代码将适用于您提到的学分数量。

public class Candidate {
 private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5};

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int i=0,score=0,totalsummation=0;
    Scanner uInput = new Scanner(System.in);
    System.out.println("Enter length of Array:");
    int arraylength = uInput.nextInt();             
    int[] credits= new int[arraylength];
    ArrayList<Integer> combination = new ArrayList<Integer>();
    for (i = 0; i <credits.length; i++) {
        credits[i] = uInput.nextInt();  
    }
    switch(credits.length) {
    case 1:
        for(int c1=10;c1>=5;c1--) {
            totalsummation = c1*credits[0];
            combination.add(totalsummation);
        }
        break;

    case 2:
        for(int g:Grades) {
            for(int c2=10;c2>=5;c2--) {
                totalsummation=g*credits[0]+c2*credits[1];
                combination.add(totalsummation);
            }
        }
        break;

    case 3:
            for(int g:Grades) {
            for(int c3=10;c3>=5;c3--) {
                totalsummation=g*credits[0]+c3*credits[1]+c3*credits[2];
                combination.add(totalsummation);
            }
        }
            break;
    case 4:
        for(int g:Grades) {
            for(int c4=10;c4>=5;c4--) {
                totalsummation=g*credits[0]+c4*credits[1]+c4*credits[2]+c4*credits[3];
                combination.add(totalsummation);    
            }
        }
        break;

    case 5:
        for(int g:Grades) {
            for(int c5=10;c5>=5;c5--) {
                totalsummation=g*credits[0]+c5*credits[1]+c5*credits[2]+c5*credits[3]+c5*credits[4];
                combination.add(totalsummation);
            }
        }
        break;

        default:
            System.out.println("Invalid Input");
    }



 ArrayList<Integer> distinctnos =(ArrayList<Integer>) combination.stream().distinct().collect(Collectors.toList());
     System.out.println(distinctnos.size());            }
}

希望这能回答你的问题。

【讨论】:

  • 谢谢 Dora,这就是我想要的,现在我需要从这里过滤掉不同的值,即为每个主题分配学分的方式的总排列 r 数
  • 但是对于 1 2 3 或更多,这段代码对于处理 3+ 值是有效的
  • 根据您的解决方案,我们还需要 5 个数组,这不是一个好的做法,我们是否可以为任何信用值独立工作的最佳解决方案
  • 是的。我同意这不是最佳解决方案,但您只想在单维数组中编写程序而不是使用多维数组,这就是我给出该解决方案的原因。您也可以将所有迭代保存在一个数组中并执行您想要的操作,但我不想让您感到困惑,这就是为什么我为每个学分编写了 2 个单独的数组。此外,我不确定为什么要分别获取数组的大小和分别获得积分。.您可以从用户那里获取单个输入..您的程序中不需要积分数组?是否必须以上述格式获取输入?
  • 我已经用新代码更新了上面的答案。你可以检查一下。如果这不是强制性的,您仍然可以避免使用 credit 数组来获取输入。请注意,这里您不会在 creditarr 数组中拥有所有迭代值。您的数组将只有最终值。
【解决方案3】:

好的,按照我们在 cmets 中的讨论:您不需要两个 for 循环。

for i = 0; i < array.size(); i++ {
    sum += grade[i]*credit[i]
 }

对于通用的编码风格,我们深表歉意。是你想要的吗?

【讨论】:

  • 循环前初始化sum为0,同时遍历两个数组,求和
  • sum += 等级[i]*credit[i];你只需要不求和两次和一个分号
  • 我想存储第一次迭代的值,即 10,9,8,7,6,5,4,3,2,1 现在我想将这些值存储在一个数组中......现在第二次迭代,我现在有 20,18,16,14,12,10,8,6,4,2……现在下一个任务是加法 取 10 并加上第二次迭代的所有值values..取 9 并加上第二次迭代的所有值
  • 请添加缺少的( ) 和缺少的初始化。尺寸就是长度。你知道这是一道java题吗?
  • @Clijsters 我知道,谢谢。但是在我看来,问题与java无关,也与解决方案无关。这就是为什么我的答案是关于算法,而不是 java。如果是 java 错误或 java 中的一些不被理解的东西,我会写 java.lang. ;)
猜你喜欢
  • 2013-11-17
  • 1970-01-01
  • 2022-12-04
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 2015-03-19
相关资源
最近更新 更多