【问题标题】:Counting dashes in sample data计算样本数据中的破折号
【发布时间】:2017-03-23 18:41:47
【问题描述】:

我正在执行一项任务,在该任务中,我被告知要检查样本数据中的“-”,当在数据中找到 - 并且散列中有相邻的破折号时,这仅计算 1 次出现,例如在这个样本数据中,答案是 4。

我首先创建了一个 2D 数组来填充它,然后我打算检查数组中的破折号,但我对如何实际计算出现次数有点困惑,如果有任何帮助,将不胜感激。

这是我目前所拥有的;

Scanner input = new Scanner(System.in);
            int a = input.nextInt(); //no. of rows
            int b = input.nextInt(); //no. of columns

            String arr[][] = new String[a][b]; //array of strings of 10 x 20
            for(int i = 0; i<a; i++){
                for(int j = 0; j<b; j++){
                    arr[i][j] = input.next();
                }
            }
            //for test purposes
            for(String[] s : arr){
                for(String e : s){
                    System.out.print(e);
                }
            }

这是示例输入:

 10 20
    #################---
    ##-###############--
    #---################
    ##-#################
    ########---#########
    #######-----########
    ########---#########
    ##################--
    #################---
    ##################-#

【问题讨论】:

  • 所以基本上你什么工作都没做,还指望我们做你的功课?
  • 听起来像。但是是一个有趣的谜题;这是肯定的。
  • 创建一个occurences 变量并在每次找到破折号时将其加1。
  • 目前还不清楚所显示数据的计数是 4。
  • 它正在计算块中的破折号数量,从左上到右相邻。

标签: java multidimensional-array java.util.scanner


【解决方案1】:

使用正则表达式的最简单方法。将每一行视为字符串,修剪字符串,然后在字符串中只允许 20 个字符(基于您的列数)。

其他方法可能是使用 DSL 算法。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test {
    public static void main(String... args) throws Exception {
        Scanner input = new Scanner(System.in);
        int a = input.nextInt(); // no. of rows
        int b = input.nextInt(); // no. of columns
        Pattern pattern = Pattern.compile("#(--+)#");
        int count = 0;
        for (int i = 0; i < a; i++) {
            String temp = input.next().trim();
            if (temp.length() > b) {
                temp.substring(0, b);
            }
            Matcher matcher = pattern.matcher(temp);
            if (matcher.find()) {
                count++;
            }
        }
        System.out.println(count);
    }
}

【讨论】:

  • 这很有意义,我正在考虑使用 RegEx 作为检查模式的一种方式,但我不知道如何实现它,但您以一种简单易懂的方式完成了它.这解决了我的问题,谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-12-08
  • 2013-03-11
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 2016-06-06
  • 2020-09-05
  • 1970-01-01
相关资源
最近更新 更多