简体   繁体   English

添加到随机生成的分数,以查看它们是否加起来存储在数组中的10

[英]Adding to randomly generated scores to see if they add to 10 which are stored in an array

I need some help writing a program for an intro java class I'm taking. 我需要一些帮助为正在学习的Java入门类编写程序。 There is a homework assignment that requires us to generate a score that is no higher than 9 and pair them with another "person" whose score adds up to 10 with another person. 有一项作业要求我们生成不高于9的分数,并将其与另一个“人”配对,该人的分数与另一个人的总和为10。 There are 20 contestants in this "game". 此“游戏”中有20位选手。 So far I created hypothetical rows and columns for the pairing of the 2 scores and nested 2 for loops and ended it off with an if to see if the rows and columns will add to 10. 到目前为止,我为2个得分的配对创建了假设的行和列,并为循环嵌套了2个,最后以if结束,以查看行和列是否会增加到10。

The program did compile, but when running, it doesn't seem to give me a solution. 该程序确实可以编译,但是在运行时,似乎没有给我解决方案。

public static void main(String[] args) { 
    int rows = 2; 
    int cols = 10; 
    int[][] scoreTotal = new int[rows][cols]; 

    for (int row = 0; row < rows; row++) { 
        int teamBlue = (int)(Math.random()* 10);

        for (int col = 0; col < cols; col++) { 
            int teamRed = (int)( Math.random()* 10); 

            if (scoreTotal[row][col] == 10) { 
                System.out.println(scoreTotal);
            }
        }
    }
}

Sorry if this is a very confusing or newbie question to be asking, but like I said i'm in an intro to java class. 抱歉,这是一个非常令人困惑的问题或新手要问的问题,但是就像我说的那样,我正在介绍Java类。

Often when getting assignments we try to complete it all in one go, but you can try to abstract the problem away to smaller "components". 通常,当您获得作业时,我们会尝试一次完成所有任务,但是您可以尝试将问题抽象为较小的“组件”。 Try to think of it as a recipe when cooking, you simply write the steps you need to take and then write out the code afterwards. 尝试将其视为烹饪时的食谱,您只需编写所需执行的步骤,然后再写出代码即可。

First, start off with your main method, you did that already 首先,从您的主要方法开始,您已经做到了

public static void main(String[] args) {
}

Next, you have one requirement that states 接下来,您有一个要求

generate a score that is no higher than 9 得分不高于9

So what you can do is create an array of "scores", and fill that with scores for each player (I used player instead of person since you mention "score" and "contestants"). 因此,您可以做的是创建一个“分数”数组,并为每个玩家添加分数(由于您提到“分数”和“参赛者”,因此我使用的是玩家而不是人)。

public static void main(String[] args) {
    // generate a score for each of the contestants
}

and pair them with another "person" whose score adds up to 10 with another person. 并将它们与另一个“人”配对,该人的得分与另一个人的总和为10。

public static void main(String[] args) {
    // generate a score for each of the contestants
    // if score of player1 and another player is equal to 10, save pair
}

The if statement is kind of cumbersome, so we can try to break it down. if语句有点麻烦,因此我们可以尝试将其分解。 To simplify things, try to think of only testing with one player to begin with. 为简化起见,请尝试只考虑对一个玩家进行测试。

public static void main(String[] args) {
    // generate a score for each of the contestants
    // take score of first player, s
    // compare s + x = 10, where x is score of other player
    // if x = 10 - s, save pair
}

Now we got something a bit more simple. 现在我们有了一些简单的东西。 Lets try putting in some code. 让我们尝试输入一些代码。

public static void main(String[] args) {
    int[] scores = new int[20];
    // generate a score for each of the contestants
    for (int i = 0; i < scores.length; ++i) {
        scores[i] = getRandomNumber();
    }
    // take score of first player, s
    int s = scores[0]; // the first player is at index 0
    // compare s + x = 10, where x is score of other player
    for (int i = 1; i < 20; ++i) {
        // note: We don't have to test against index 0 (that's the first player)
        //       so we start at index 1
        // if x = 10 - s
        int x = scores[i];
        if (x == 10 - s) {
            // save pair
        }
    }
}

public static int getRandomNumber() {
   // todo: generate a random score between 0 and 9 and return it
   return 4;
}

You seemed to know how to use the for loop in your original code. 您似乎知道如何在原始代码中使用for循环。 What you didn't do was assigning a value in the array. 您没有做的就是在数组中分配一个值。 The scores[i] = x; scores[i] = x; (where x is an int) takes care of that, similar to assigning an int for instance, int a = 0 . (其中x是一个int)负责处理这一问题,类似于分配一个int,例如int a = 0 I used a method for generating a score that returns an int , since the implementation of how to get a random value is "not interesting" (so we abstract it away). 我使用了一种生成返回int的得分的方法,因为实现随机值的实现方式“没有意思”(因此我们将其抽象化了)。 So the for loop sets a score value for each index of the array. 因此,for循环为数组的每个索引设置一个得分值。

Next, since the scores array have all the scores for the contestants, we need to pair them. 接下来,由于scores数组包含了所有参赛者的分数,因此我们需要将它们配对。 Using some simple math, we construct an if statement that checks if the first player and a second player has scores that sum up to 10. 通过一些简单的数学运算,我们构造了一个if语句,该语句检查第一个玩家和第二个玩家的得分总和是否为10。

Next we need to save the pairs of contestants. 接下来,我们需要保存成对的参赛者。 You were on the right path of creating a two-dimensional array, one for holding the players, and the other dimension for the "teams". 您在创建二维数组的正确道路上,一个二维数组用于容纳玩家,另一个二维数组用于“团队”。 When filling this array, the 2D array can look something like this 填充此数组时,二维数组可能看起来像这样

        | players |
        |  0    1 |
 -------+----+----+
 team 0 |  0 |  1 |
 team 1 |  3 |  7 |
 team 2 |  8 |  9 |
 -------+----+----+

ie we team up player 0 with 1, player 3 with player 7, and player 8 with player 9. We notice from this that the team index (0-2) is not related to the actual players, so we can conclude that we need a separate index for the teams. 也就是说,我们将玩家0与1,玩家3与玩家7,以及玩家8与玩家9组合在一起。由此我们注意到,团队索引(0-2)与实际的玩家无关,因此我们可以得出结论,我们需要团队的单独索引。

public static void main(String[] args) {
    // generate a score for each of the contestants
    // create the team array, 10 teams each with 2 participants
    // for every player: take score of player, s
    // compare s + x = 10, where x is score of every other contestant
        // if x = 10 - s
            // assign the current team to player s and player x
            // increment team integer (assign next team)
}

So using similar code to yours, we construct the teams array and assign the first team with our player, before we continue with the rest of the teams. 因此,使用与您的代码相似的代码,我们构造了teams数组并为我们的玩家分配了第一个团队,然后再继续其余团队。

// create the team array, 10 teams, each with 2 participants
int[][] teams = new int[10][2];
// assign the first team to player 3 and player 7
teams[0][0] = 3;
teams[0][1] = 7;

This is just an example, where Team 0 is assigned two team members, one at index 0 and one at index 1, to player 3 , and player 7 . 这只是一个示例,其中为团队0分配了两个团队成员,一个在索引0,一个在索引1,分别分配给玩家3和玩家7

This is great. 这很棒。 We can now pair up one player with anyone of the other players. 现在,我们可以将一个玩家与其他任何玩家配对。 From this, we know that we need a counter for the "current team", since each contestant doesn't have to have a teammate in this round, and when one team is assigned, we should assign the next one. 由此,我们知道我们需要一个“当前团队”的计数器,因为每个参赛者在本轮比赛中不必拥有队友,并且在分配了一个团队时,我们应该分配下一个。

public static void main(String[] args) {
    int[] scores = new int[20];
    // generate a score for each of the contestants
    // ... same as before
    // create the team array, 10 teams each with 2 participants
    int[][] pairs = new int[10][2];
    // create a team integer
    int currentTeam = 0;
    // for every player: take score of player, s
    for (int i = 0; i < 20; ++i) {
        // todo: test if player i is already in teams array and continue; if it is
        int s = scores[i];
        for (int j = i + 1; j < 20; ++j) {
            // compare s + x = 10, where x is score of every other contestant
            int x = scores[j];
            // if x = 10 - s
            if (x == 10 - s) {
                // assign the current team to player i and player j
                pair[currentTeam][0] = i;
                pair[currentTeam][1] = j;
                // increment team integer (assign next team)
                ++currentTeam;
            }
        }
    }
}

Note that the second for loop starts from i + 1 , since we already tested the players with lower indexes. 请注意,第二个for循环从i + 1开始,因为我们已经用较低的索引测试了播放器。

Also; 也; You don't mention it, but there's a "hidden" constraint in this problem that each pair is exclusive, so one contestant can only participate one time. 您没有提及它,但是在这个问题中有一个“隐藏”的约束条件,即每一对都是排他的,因此一个参赛者只能参加一次。 You should add a third for loop that checks if the teams array contains the player already. 您应该添加第三个for循环,以检查teams数组是否已包含玩家。

So, by breaking down the problem we managed to get some code that may or not work, but the logic is there anyways created by reasoning, and that's always important when solving problems! 因此,通过分解问题,我们设法获得了一些可能有效或无效的代码,但是无论如何,逻辑都是通过推理创建的,这在解决问题时始终很重要!

As it stands now, one can not easily help you except for writing out the program for you, as you did not submit any code, so instead of plainly doing the homework for you, here are some pointers: First, break down the problem. 就目前而言,除了为您编写程序(因为您没有提交任何代码)之外,您无法轻松地为您提供帮助,因此,这里有一些指示信息,而不是简单地为您做功课:首先,解决问题。 Read the problem carefully and then identify what you have to do. 仔细阅读问题,然后确定您必须做什么。 In doing so, you should arrive at several steps that can be turned into code. 这样做时,您应该到达可以转化为代码的几个步骤。

  1. Create twenty integers containing random numbers from 0-9 (or 1 to 9, the question doesn't really specify) and put them in an array. 创建二十个包含0-9(或1到9,这个问题实际上没有指定)的随机数的整数,并将它们放入数组中。
  2. For each score, find another score so the sum of them is 10 and store them as a pair. 对于每个分数,找到另一个分数,使它们的总和为10,并成对存储。 Again, it isn't really specified how you should store these pairs. 同样,并没有真正指定如何存储这些对。
  3. After finding all pairs, output them and any left-over scores that didn't get any matches. 找到所有对之后,输出它们以及没有任何匹配项的剩余分数。

So your in the loops: 因此,您在循环中:

for (int row = 0; row < rows; row++) { 
    int teamBlue = (int)(Math.random()* 10);// teamBlue never used

    for (int col = 0; col < cols; col++) { 
        int teamRed = (int)( Math.random()* 10);// teamBlue never used 

        if (scoreTotal[row][col] == 10) {
            // scoreTotal[row][col] never modified
            // never reached because scoreTotal[row][col] == 0 by default
            System.out.println(scoreTotal);
        }
    }
}

In other words your 2D array is full of 0's: 换句话说,您的2D数组充满了0:

{ {0 0 0 0 0 0 0 0 0 0}
  {0 0 0 0 0 0 0 0 0 0} }

Since you didn't do anything with the scores. 由于您没有对分数做任何事情。 You could: 你可以:

public static void main(String[] args) { 
    int rows = 2; 
    int cols = 10; 
    int[][] scoreTotal = new int[rows][cols]; 

    for (int row = 0; row < rows; row++) { 
        for (int col = 0; col < cols; col++) { 
            int randScore = (int)(Math.random()* 9) + 1;// in case you want a 1-9
            scoreTotal[row][col] = randScore
        }
    }
}

This way you have a 2D array of scores: 通过这种方式,您可以获得2D分数数组:

           { {1 2 3 4 5 6 7 8 9 2}    // row == 0, 1st player random scores
             {1 2 3 4 3 5 6 7 8 9} }  // row == 1, 2nd player random scores
//col index:  0 1 2 3 4 5 6 7 8 9
//eg. scoreTotal[2][4] would be 3

Now you can do anything you want with the scores. 现在,您可以对分数进行任何操作。 The pairing would depend on whether you want pair that only add up to 10 or some other rules. 配对将取决于您是否希望配对最多只添加10条规则或其他规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM