【问题标题】:Find how many times a value appears in a 2D array and store that number in another 1D array找出一个值在二维数组中出现的次数,并将该数字存储在另一个一维数组中
【发布时间】:2021-07-06 12:07:43
【问题描述】:

我已经搜索了很多关于堆栈溢出的问题和关于如何具体做我想做的谷歌结果,但似乎没有一个适用于我正在尝试做的事情。

我只需要简单地创建一个 for 循环来循环遍历从文件填充的 2D 数组的行,并找到该行具有 Y 的实例,但是,这些行也具有来自 1-24 的数字。行看起来像:Team# Y/N,我只需要计算一个团队在其行中有多少次Y,并将其存储起来以便稍后打印。示例:

Team 1 had a count of 3
Team 5 had a count of 4

我需要找出如何遍历这个二维数据数组,并找出每个团队在其行中有多少次 Y,然后将其存储到正确的团队。

【问题讨论】:

    标签: java arrays loops for-loop multidimensional-array


    【解决方案1】:

    算法

    1. 遍历二维数组的每一行
    2. 计算与“Y”匹配的列数
    3. 根据需要存储值

    知道字符串每次迭代都会增加长度,使用StringBuilder 类很有用,它可以更好地处理动态字符串。为了计算匹配,我们可以利用 Stream 类的好处,过滤值,然后计数将是想要的值。

    当我们使用函数时,您必须使用 Java 8 或更高版本:

    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            String[][] table = {
                    {"1", "Y", "N", "Y"},
                    {"2", "Y", "Y", "Y"},
                    {"2", "N", "N", "Y"}};
    
            StringBuilder scores = new StringBuilder(table.length * 3);
            for (String[] row : table) {
                scores.append(Arrays.stream(row)
                    .filter(str -> str.equalsIgnoreCase("Y"))
                    .count()
                ).append('\n');
            }
            System.out.println(scores.toString());
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以为此目的使用

      String[][] table = {
              {"1", "N", "Y", "N", "Y"},
              {"2", "N", "Y", "Y", "Y"},
              {"3", "N", "N", "N", "Y"}};
      
      List<Map.Entry<String, Long>> counts = Arrays
              // iterate through the rows of a 2D array
              .stream(table)
              // Map.Entry<Integer,Long>
              .map(row -> Map.entry(
                      // team#
                      row[0],
                      // count of 'Y' in this row
                      Arrays.stream(row).filter(str -> str.equals("Y")).count()))
              // store in the list of map entries
              .collect(Collectors.toList());
      
      // output
      counts.forEach(e -> System.out.println(
              "Team " + e.getKey() + " had a count of " + e.getValue()));
      

      输出:

      Team 1 had a count of 2
      Team 2 had a count of 3
      Team 3 had a count of 1
      

      【讨论】:

        【解决方案3】:

        您可以使用单个TreeMap 来累积团队分数。

        // original table
        String[][] table = {
                {"1", "N", "Y", "Y", "Y", "N"},
                {"2", "N", "Y", "N", "Y", "Y"},
                {"3", "N", "N", "N", "Y", "N"}};
        // map of team scores
        Map<String, Integer> scores = new TreeMap<>();
        // iterate over the rows of the table
        for (String[] row : table) {
            // first element - team number
            String team = row[0];
            // team score
            int score = 0;
            // iterate over the next elements of the row
            for (int i = 1; i < row.length; i++)
                // if this element is 'Y', increase the score
                if (row[i].equals("Y")) score++;
            // put this key-value pair to the map
            scores.put(team, score);
        }
        // output
        for (Map.Entry<String, Integer> score : scores.entrySet())
            System.out.println("Team " + score.getKey()
                    + " had a count of " + score.getValue());
        

        输出:

        Team 1 had a count of 3
        Team 2 had a count of 3
        Team 3 had a count of 1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-11-11
          • 1970-01-01
          • 2022-11-30
          • 2023-04-02
          • 2018-04-22
          • 1970-01-01
          • 1970-01-01
          • 2021-06-04
          相关资源
          最近更新 更多