Counting dashes in sample data - java

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

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

Related

ArrayList queries in java

I am solving this problem on ArrayList in HackerRank. I completed the code but there's no stdout showing on the console.
Question:
You are given lines. In each line, there are zero or more integers. You need to answer a few queries where you need to tell the number located in the Yth position of Xth line.
The first line has an integer (n). In each of the next (n) lines there will be an integer denoting the number (d) of integers on that line and then there will be (d) space-separated integers. In the next line, there will be an integer denoting q number of queries. Each query will consist of two integers (x)and (y).
I am getting a number format exception at (int)number.
Problem statement - if the number is present at x row and y position, print it otherwise print ERROR!
Input:
5
5 41 77 74 22 44
1 12
4 37 34 36 52
0
3 20 22 33
5
1 3
3 4
3 1
4 3
5 5
Output:
74
52
37
ERROR!
ERROR!
My code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n = 0;
String []problem;
int queries = 0;
int number = 0;
ArrayList<List<String>> allProblems = new ArrayList<>();
List<String> problems = new ArrayList<>();
ArrayList<List<String>> allPos = new ArrayList<>();
List<String> pos = new ArrayList<>();
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
sc.nextLine();
for(int i=0;i<n;i++)
{
problem = sc.nextLine().split(" ");
problems = Arrays.asList(problem);
allProblems.add(problems);
}
queries = sc.nextInt();
sc.nextLine();
for(int i=0;i<queries;i++)
{
pos = Arrays.asList(sc.nextLine().split(" "));
allPos.add(pos);
}
for(int i=0;i<queries;i++)
{
int x = Integer.parseInt((allPos.get(i)).get(0));
int y = Integer.parseInt((allPos.get(i)).get(1));
if(y >= allProblems.get(i).size()-1)
{
System.out.println("ERROR!");
}
else
{
number = Integer.parseInt((allProblems.get(x)).get(y+1));
System.out.println(number);
}
}
sc.close();
}
}
Please, try to use the code below. I added the comments in places where I changed something
package tests;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Solution
{
public static void main(String[] args)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n = 0;
String[] problem;
int queries = 0;
int number = 0;
ArrayList<List<String>> allProblems = new ArrayList<>();
List<String> problems; // removed an implementation from here, it wasn't used
ArrayList<List<String>> allPos = new ArrayList<>();
List<String> pos; // removed an implementation from here, it wasn't used
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
sc.nextLine();
for (int i = 0; i < n; i++)
{
problem = sc.nextLine().split(" ");
problems = Arrays.asList(problem);
allProblems.add(problems);
}
queries = sc.nextInt();
sc.nextLine();
for (int i = 0; i < queries; i++)
{
pos = Arrays.asList(sc.nextLine().split(" "));
allPos.add(pos);
}
sc.close(); // I closed the scanner as soon as I ended read data
// defining the return values
for (int i = 0; i < queries; i++)
{
int x = Integer.parseInt((allPos.get(i)).get(0));
int y = Integer.parseInt((allPos.get(i)).get(1));
if (y > allProblems.get(x-1).size() - 1) // the equal mark was not needed
{
System.out.println("ERROR!");
} else
{
number = Integer.parseInt((allProblems.get(x-1)).get(y)); // (x-1) instead of X and Y instead of (y+1)
System.out.println(number);
}
}
}
}

How to reverse the word after getting a Capital letter at the end of the word in JAVA?

Suppose you have a String and a CAPITAL letter in that indicates ending of a word. For example, if you have wElovEcakE where E, E and K indicates end of the words wE, lovE and cakE respectively. You need to reverse each word (as you know where it ends). Don’t reverse the String as a whole. To illustrate, if we give wElovEcakE as input output should be EwEvolEkac. See wE became Ew, lovE became Evol and so on....
And the way i tried to approach with ..
import java.util.Scanner;
public class Alternative {
public static void main(String[]args) {
Scanner robo=new Scanner (System.in);
System.out.println("Enter a word ");
String word=robo.nextLine();
char[] array=word.toCharArray();
for(int i =0;i<array.length;i++){
int count =0;
for(int j=0;j<=("EMPTY");j++) // here i am trying to operate a loop where it will work up to the Capital letter.
count ++;
}
//Code incomplete
}
}
}
Above i have mentioned "EMPTY" in the condition part ... i want to operate a loop where my loop will work up to the capital letter , then i will count all the letter that i have counted up to capital letter then last step will be like i will make another loop where i will reverse all the letter where condition for the loop will <=count ;Example:lovE (counted 4 letters i will reverse four times back).
Can you guys help me to write the condition at "EMPTY" part if you think that my approach is correct ..
Can you guys help me to solve the problem in any other way ?
test if this works for you:
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
String textInvert = "";
int indexAnt = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
String wordSplit = word.substring(indexAnt, i + 1);
for (int j = wordSplit.length() - 1; j >= 0; j--)
textInvert += wordSplit.charAt(j);
indexAnt = i + 1;
}
}
System.out.println(textInvert);
Here is my solution with Regex pattern
String[] in = "wElovEcakE".replaceAll("([A-z]+?[A-Z])","$1,").replaceAll(",$","").split(",");
String out = "";
for(String current: in){
StringBuilder temp = new StringBuilder();
temp.append(current);
out+=temp.reverse();
}
System.out.println(out);
Result:
EwEvolEkac
Here is a solution that makes use of the StringBuilder class to hold and reverse each found word.
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word:");
String word = robo.nextLine();
robo.close();
String upperCase = word.toUpperCase(); //used to find uppercase letters
StringBuilder builder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char nextChar = word.charAt(i);
builder.append(nextChar);
if (nextChar == upperCase.charAt(i)) {
String subWord = builder.reverse().toString();
System.out.print(subWord); //It's not clear what to do with the found words
builder = new StringBuilder();
}
}
System.out.println();
Example
Enter a word:
makEmorEpiE
EkamEromEip
You can try this solution:
String textInvert = "wElovEcakE";
String revertText = textInvert
.chars().mapToObj(c -> (char) c)
.reduce(new LinkedList<>(Arrays.asList(new StringBuilder())), (a, v) -> {
a.getLast().append(v);
if (Character.isUpperCase(v)) {
a.add(new StringBuilder());
}
return a;
}, (a1, a2) -> a1)
.stream()
.map(s -> s.reverse())
.reduce(StringBuilder::append)
.map(StringBuilder::toString)
.get();
System.out.println(revertText);
public class Alternative {
public static void main(String[] args) {
Scanner robo = new Scanner(System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
char[] array = word.toCharArray();
int count = -1;
for (int i = 0; i < array.length; i++) {
if (Character.isUpperCase(array[i])) { //find the upper case letters in the word
for (int j = i; j > count; j--) //loop through the letters until the last count variable value is encountered
System.out.print(array[j]); //print the reversed values
count = i; //assign the last encountered uppercase letter's index value to count variable
}
}
}
}

Scanner - Matrix of char in Java

I just started learning this language and I have a problem trying to create a Matrix of type char from user input.
For example I want to read this as my input:
3 // this is an int n that will give me a square matrix[n][n]
.#.
###
.#.
For this example, this is what I have:
//...
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
char[][] matrix = new char[n][n]
for(int i = 0; i < n; i++){
matrix = stdin.nextLine();
}
Obviously this is wrong, and I know that. I'm just not seeing a way to correctly read this input.
If anyone could help me I would appreciate it.
ps: if possible, keep it simple, because like I said, I just started learning java :)
First, you need to add stdin.nextLine(); after reading n to skip the new line character.
Second, this is what you need inside your loop:
matrix[i] = stdin.nextLine().toCharArray();
This reads next line and converts it to an array of chars.
This is a runnable version of your question with output
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.Arrays;
import java.util.Scanner;
public class MainNoFXML extends Application {
#Override
public void start(Stage stage) {
System.out.println("Enter Matrix Size:");
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
char[][] matrix = new char[n][n];
stdin.nextLine();
for(int i = 0; i < n; i++) {
System.out.println("Enter "+n+" Number of Chars");
System.arraycopy(stdin.nextLine().toCharArray(), 0, matrix[i], 0, n);
}
System.out.println("\nYour Matrix:");
for(int i = 0; i < n; i++)
System.out.println(Arrays.toString(matrix[i]));
}
public static void main(String[] args) { launch(args); }
}
Output:
Enter Matrix Size:
3
Enter 3 Number of Chars
.#.
Enter 3 Number of Chars
###
Enter 3 Number of Chars
.#.
Your Matrix:
[., #, .]
[#, #, #]
[., #, .]
First of all, thank you for all your answers.
I emailed my teacher and this was the solution he gave to me, if anyone is wondering:
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
stdin.nextLine();
char[][] matrix = new char[n][n]
for(int i = 0; i < n; i++){
String line = stdin.nextLine();
for(int j = 0; i < n; j++){
matrix[i][j] = line.charAt(j);
}
}
see code sample:
public class MatInput {
public static void main(String[] args) {
int matX = 3;
int matY = 3;
String matrix [][]=new String[matX ][matY];
Scanner input = new Scanner(System.in);
System.out.println("enter the strings for the Matrix");
for(int row=0;row<matX;row++){
for(int col=0;col<matY;col++){
matrix[row][col]=input.nextLine();
}
System.out.println("");
}
for(int r=0;r<matrix.length; r++) {
for (int c=0; c<matrix [r].length; c++) {
System.out.print(matrix [r][c] + " ");
}
System.out.println("");
}
input.close();
}
}

Alphabetizing strings and reversed strings?

For this program, I need to have the user input strings, which will then be put into an array along with their reversed counterparts. The entire array would then be alphabetized. So it should work like this:
Input: strawberry banana, apple, grapes
Output: apple, ananab, banana, elppa, grapes, separg, strawberry, yrrebwarts
I have the code for this, and it works to some degree. However, it only alphabetizes the reversed and the normal but separately. So it ends up looking like this:
Output: ananab, elppa, separg, yrrebwarts, apple, banana, grapes, strawberry
As you can see it is alphabetizing the words to some degree, but not how it should be. Here is my code:
import java.util.Scanner;
public class WordGame {
public static void main(String[] args) {
String reverseInput = " "; //creates an empty string where the reverse will be stored before putting it into the array
String[] wordArray = new String[1000]; //creates an array that allows for 500 words, and 500 reverses of said words
int s = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the words you would like to reverse. To finish entering words enter a blank line:");
String userInput = sc.nextLine(); //allows for user to input words
int length = userInput.length();
int i = 0;
while (!userInput.equals("")){ //runs until the user enters a blank line
reverseInput = " ";
for(i = length - 1; i >= 0; i--)
reverseInput += userInput.charAt(i);
wordArray[s] = userInput; //reverses user inputted strings by taking the last letter and putting it in front, repeating until the whole word is reversed
wordArray[s + 1] = reverseInput;
s += 2;
userInput = sc.nextLine();
length = userInput.length();
}
for(int j = 0; j < s-1; j++){ //beginning of alphabetical sorting
for(int k = 0; k < s-1-j; k++){
int l = 0;
while((int)wordArray[k].charAt(l) == (int)wordArray[k+1].charAt(l))
l++;
if ((int)wordArray[k].charAt(l) > (int)wordArray[k+1].charAt(l)){
String holder = wordArray[k];
wordArray[k] = wordArray[k+1];
wordArray[k+1] = holder;
}
}
}
for(i = 0; i < wordArray.length; i++){
if (wordArray[i]!= null){
System.out.print(wordArray[i] + " "); //prints out contents of array
}
}
}
}
I am not sure what the issue is. Any help would be much appreciated. Thanks!
As far as I can see you put an extra blank in front of your "reverseInput" with reverseInput = " ";
Because your reverse string won't start with a char you think (it starts with a blank) the result is not what you really want. Try to delete the blank and retry you code.
There are definitely easier ways to do this, depending on if you want to use Java's built in classes for this kind of thing. I just wrote this up, it accomplishes the sort with reversed Strings that you want.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
public static void main(String args[]) {
ArrayList<String> values = new ArrayList<String>();
values.add("strawberry");
values.add("banana");
values.add("apple");
values.add("grapes");
Solution s = new Solution();
values = s.sortList(values);
int itemCt = 1;
for (String item : values) {
System.out.println(itemCt + ": " + item);
itemCt++;
}
}
public ArrayList<String> sortList(List<String> strings) {
ArrayList<String> combinedList = new ArrayList<String>();
for (String str : strings) {
combinedList.add(str);
combinedList.add(new StringBuilder(str).reverse().toString());
}
Collections.sort(combinedList);
return combinedList;
}
}

Split scanner input and typecast into array of strings

I'm trying to use Java to solve a simple challenge but I have unsuccessful and I can't find an answer. The idea is that the user enters a string of text, and the program returns the longest word in that string. I can use Scanner to accept the input from the user, and then the .split() method to split the string at the spaces with .split(" ") but I can't figure out how to store the split sentence in an array that I can iterate through to find the longest word. I always get a console output that looks like this:
[Ljava.lang.String;#401a7a05
I have commented out the code that I think should find the longest word so as to focus on the problem of being unable to use Scanner input to create an array of Strings. My code at the moment is:
import java.util.*;
import java.io.*;
class longestWord {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
//for (int i = 0; i <= b.length(); i++) {
// if (longest < b[i].length()) {
// longest = b[i].length();
// word = b[i];
// }
//}
//System.out.println(word);
System.out.println(c);
}
}
That's because you are iterating over the string, not the array, and trying to output the entire array. Change your for loop to use c instead:
for (int i = 0; i < c.length; i++) //In an array, length is a property, not a function
{
if (longest < c[i].length())
{
longest = c[i].length();
word = c[i];
}
}
That should fix your first output. Then you want to change how you output your array, change that to something like this:
System.out.println(Arrays.toString(c));
Which will display the array like so:
[word1, word2, word3, word4]
So you want to get the input as a string and automatically make it an array? You can do that simply by calling the split function after nextLine on the scanner:
String[] wordArray = n.nextLine().split(" ");
there are many mistakes in you code. such a
you were
iterating over string not on array.
if (longest < b[i].length()) as b is your string not array of string
try this it will work it will print the longest word and its size as well.
class Test {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
for (int i = 0; i < c.length; i++) {
if (longest < c[i].length()) {
longest = c[i].length();
word = c[i];
}
}
System.out.println(word);
System.out.println(longest);
}
}

Categories