简体   繁体   English

找出一个值在二维数组中出现的次数,并将该数字存储在另一个一维数组中

[英]Find how many times a value appears in a 2D array and store that number in another 1D array

I have searched so many questions on stack overflow and google results on how to do specifically what I want to do, but none of them seem to apply to what I am trying to do.我已经搜索了很多关于堆栈溢出的问题和关于如何专门做我想做的事情的谷歌结果,但它们似乎都不适用于我想做的事情。

I just need to simply make a for loop to cycle through a 2D array's rows that were filled from a file and find instances where the row has a Y , however, the rows also have a number from 1-24 .我只需要简单地创建一个 for 循环来循环遍历从文件填充的 2D 数组的行,并找到该行具有Y的实例,但是,这些行也有一个从1-24的数字。 Rows look like: Team# Y/N and I need to just count how many times a team has Y in its row, and store it to print later.行看起来像: Team# Y/N ,我只需要计算一个团队在其行中有多少次Y ,并将其存储起来以便以后打印。 Example:例子:

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

I need to find out how to iterate through this 2D array of data and find how many times each team had a Y in its row and then store it to the right team.我需要找出如何遍历这个二维数据数组,并找出每个团队在其行中有多少次Y ,然后将其存储到正确的团队。

Algorithm算法

  1. Iterate over each row of the 2D Array遍历二维数组的每一行
  2. Count how many columns match "Y"计算有多少列匹配“Y”
  3. Store the value as wanted根据需要存储值

Knowing the string will increase in lenght each iteration it's useful to use StringBuilder class which allows better work with dynamic Strings.知道字符串每次迭代都会增加长度,因此使用StringBuilder class 非常有用,它可以更好地处理动态字符串。 And for counting the matches we can use the benefits of the Stream class, filter the values and then the count will be the wanted value.为了计算匹配,我们可以使用Stream class 的好处,过滤值,然后计数将是想要的值。

As we are working with functions you must work with Java 8 or greater:当我们使用功能时,您必须使用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());
    }
}

You can use streams for this purpose:您可以为此目的使用

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()));

Output: Output:

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

You can use a single TreeMap to accumulate team scores.您可以使用单个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());

Output: Output:

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

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

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