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

问题描述 投票:0回答:3

我在堆栈溢出和谷歌结果上搜索了很多关于如何具体做我想做的事情的问题,但它们似乎都不适用于我想做的事情。

我只需要简单地创建一个 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
3个回答
2
投票

算法

  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 * table[0].length);
        for (String[] row : table) {
            scores.append(Arrays.stream(row)
                .filter(str -> str.equalsIgnoreCase("Y"))
                .count()
            ).append('\n');
        }
        System.out.println(scores.toString());
    }
}

0
投票

您可以使用streams来实现此目的:

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

0
投票

您可以使用单个

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
© www.soinside.com 2019 - 2024. All rights reserved.