简体   繁体   中英

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 . 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. 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.

Algorithm

  1. Iterate over each row of the 2D Array
  2. Count how many columns match "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. 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.

As we are working with functions you must work with Java 8 or greater:

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:

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.

// 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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