Huzzah Huzzah -4 years ago 116
Java Question

Counting dashes in sample data

I'm doing a task in which I am told to check for the '-'s in sample data, when a - is found in the data and there are adjacent dashes within the hashes, this only counts for 1 occurrence, e.g. in this sample data the answer would be 4.

I started by creating a 2D array to populate it then I was going to check for the dashes in the array but I am a bit puzzled as to how I would go about actually counting the occurrences, Any help would be appreciated.

Here's what I have so far;

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


Here's the sample input:

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

Answer Source

Simplest way to use regex. Consider each row as string, trim string and then allow only 20 characters in string(based on your column count).

Other approaches could be to use DSL algos.

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);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download