Counting double digits in a character list - java

I am writing a groovy program. I have an output like below
red 5green 5blue 10white 15
I want to sum up the digits in the output. The sum would be 35
I wrote the below logic however the program returned 17 which is right as the below logic takes into account digits.
can you please guide me as to how I make the program understand two digit numbers? so that i get the right sum?
for (int i =0; i < output.length(); i++)
{
{
sum=sum+Character.getNumericValue(grps.charAt(i))
}
}
Thanks

Since you tagged for [groovy] too:
You could "findAll" number-strings in the string with a regexp /\d+/, turn all of them into numbers, and finally sum() them. e.g.
def sumNumberStrings(s) {
s.findAll(/\d+/)*.toLong().sum()
}
assert 35==sumNumberStrings("red 5green 5blue 10white 15")

I would use a regular expression to replace all non-digits with a space, trim() that to remove any leading and trailing and white-spaces and then split on (optionally consecutive) white-space; like,
String output = "red 5green 5blue 10white 15";
int sum = 0;
for (String token : output.replaceAll("\\D+", " ").trim().split("\\s+")) {
sum += Integer.parseInt(token);
}
System.out.println(sum);
Outputs (as requested)
35
Another option would be a Pattern to find all sequences of one or more digits and group them, then use a loop to parse and add to the sum. Like,
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(output);
while (m.find()) {
sum += Integer.parseInt(m.group(1));
}
System.out.println(sum);
Which will also give you 35.

Apparently I can't write code in comment, but just to follow on with the answer you could take it a bit further and using slashing strings, drop the semicolons and the System.out.
String output = "red 5green 5blue 10white 15"
int sum = 0
for (String token : output.replaceAll(/\D+/, " ").trim().split(/\s+/)) {
sum += Integer.parseInt(token)
}
println(sum)

A simple algorithm that does not require usage of regular expressions or other complicated features would be something like this:
String output = "red 5green 5blue 10white 15";
// The result
int sum = 0;
// Sum of the current number
int thisSum = 0;
for (char c : output.toCharArray()) {
// Iterate through characters
if (Character.isDigit(c)) {
// The current character is a digit so update thisSum so it includes the next digit.
int digitValue = c - '0';
thisSum = thisSum * 10 + digitValue;
} else {
// This character is not a digit, so add the last number and set thisSum
// to zero to prepare for the next number.
sum += thisSum;
thisSum = 0;
}
}
// If the string ends with a number, ensure it is included in the sum.
sum += thisSum;
System.out.println(sum);
This works with numbers of any number of digits.

Related

how count the number of digits of telephone numbers?

easy for usual numbers, but telephone numbers can start with 01-...., as an example, 01234
is basically 1234 for java, right?
So I can't divide by 10 recursively to find out how many digits there are.
is there any different way to find out how many digits there are ?
thanks in advance.
ps.: no regex if possible
Assume that the phone number is a string,
String pn = "049-4912394129" // that's a random value
then you could iterate in that string and check if a character is indeed a number
int count = 0;
for(char c : pn.toCharArray()){
if(Character.isDigit(c))
count++;
}
As you phone number is an int, you don't need to bother with regex and every locale phone number patterns.
Simply convert your intphone number to a String. Then you can easily get the string length.
int myIntNumber = 1234;
String myStringNumber = String.valueOf(myIntNumber);
int length = myStringNumber.length();
If you are talking about a number that represented by a String object then:
public int getNumberOfDigits(phoneNumber) {
int count = 0;
for (int i = 0, i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
count++;
}
}
System.out.println("Number of digits: " + count);
return count;
}
If you are talking about a number that represented by an int then simply
convert it to String before using it like so:
String phoneNumber = String.valueOf(phoneNumberInInt);
I assumed you DO want to count the zeros as a digit because you are not summarizing the value of them, so they do have a meaning when you talk about how many digits are there.
this could easily be done with a lambda
"049-4912394129".codePoints().filter( Character::isDigit ).count(); // 13

How to print a number pattern

So I got this task to do :
(Display patterns) Write a method to display a pattern as follows:
The method header is:
public static void displayPattern(int n)
Basically , I understood "HOW" to do the excerice, and even coded it on my own and got 99% of the code right.
I know that I need to do 2 loops, one that prints the whitespaces and each time declines by 1 and the other that prints the number after the whitespace and inclines by 1.
Here is my method:
public static void printPattern(int n) {
int m =1;
int k=1;
while (m-1-1 <=n) {
int numberOfWhiteSpaces = n -1;
for (int i = numberOfWhiteSpaces; i >= 0; i--) {
System.out.print(" ");
}
for (k=m; k>0; k--) {
System.out.print( k + "");
}
System.out.println();
m++;
n--;
}
}
Let's say i call
printPattern(3);
My only problem that the output is like this :
1
21
321
No white spaces between the numbers, and yes, I tried to change this:
System.out.print( k + "");
to this:
System.out.print( k + " ");
The result? :
I have been on this problem for 2 hours straight, couldn't get it right.
Might use some help, thanks guys.
This happens because you did not count the number of spaces correctly: your code assumes that you need one space in the prefix portion of the string for each number that you print. However, when you switch to k + " ", prefix would require two spaces, not one, per number printed (assuming single-digit numbers). Therefore, when you switch to k + " " in the second loop, you need to also switch to System.out.print(" "); (two space) in the first loop.
This will fix the problem for single-digit numbers. Generalizing to multi-digit numbers would require more work: you would need to count the number of digits on the last line, then count the number of digits on the current line, and print the required number of prefix spaces to compensate for the difference.

Maximum repeating sequence instead of longest repeating sequence

I am trying to get the most repeated sequence of characters in a string.
For example :
Input:
s = "abccbaabccba"
Output:
2
I have used dynamic programming to figure out the repeating sequence, but this returns the longest repeating character sequence. For example:
Input:
s = "abcabcabcabc"
Output:
2
2(abcabc,abcabc) instead of 4(abc,abc,abc,abc)
Here is the part of the code where I'm filling the DP table and extracting repeating sequence. Can anyone suggest how I can get the most repeating sequence?
//Run through the string and fill the DP table.
char[] chars = s.toCharArray();
for(int i = 1; i <= length; i++){
for(int j = 1; j <= length; j++){
if( chars[i-1] == chars[j-1] && Math.abs(i-j) > table[i-1][j-1]){
table[i][j] = table[i-1][j-1] + 1;
if(table[i][j] > max_length_sub){
max_length_sub = table[i][j];
array_index = Math.min(i, j);
}
}else{
table[i][j] = 0;
}
}
}
//Check if there was a repeating sequence and return the number of times it occurred.
if( max_length_sub > 0 ){
String temp = s;
String subSeq = "";
for(int i = (array_index - max_length_sub); i< max_length_sub; i++){
subSeq = subSeq + s.charAt(i);
}
System.out.println( subSeq );
Pattern pattern = Pattern.compile(subSeq);
Matcher matcher = pattern.matcher(s);
int count = 0;
while (matcher.find())
count++;
// To find left overs - doesn't seem to matter
String[] splits = temp.split(subSeq);
if (splits.length == 0){
return count;
}else{
return 0;
}
}
Simple and dump, the the smallest sequence to be considered is a pair of characters (*):
loop over the whole String an get every consecutive pair of characters, like using a for and substring to get the characters;
count the occurrence of that pair in the String, create a method countOccurrences() using indexof(String, int) or regular expressions; and
store the greatest count, use one variable maxCount outside the loop and an if to check if the actual count is greater (or Math.max())
(*) if "abc" occurs 5 times, than "ab" (and "bc") will occur at least 5 times too - so it is enough to search just for "ab" and "bc", not need to check "abc"
Edit without leftovers, see comments, summary:
check if the first character is repeated over the whole string, if not
check if the 2 initial characters are repeated all over, if not
check if the 3 ...
at least 2 counters/loops needed: one for the number of characters to test, second for the position being tested. Some arithmetic could be used to improve performance: the length of the string must be divisible by the number of repeated characters without remainder.

How do you get the numerical value from a string of digits?

I need to add certain parts of the numerical string.
for example like.
036000291453
I want to add the numbers in the odd numbered position so like
0+6+0+2+1+5 and have that equal 14.
I tried the charAt(0)+charAt(2) etc, but it returns the digit at those characters instead of adding them. Thanks for your help.
Use charAt to get to get the char (ASCII) value, and then transform it into the corresponding int value with charAt(i) - '0'. '0' will become 0, '1' will become 1, etc.
Note that this will also transform characters that are not numbers without giving you any errors, thus Character.getNumericValue(charAt(i)) should be a safer alternative.
String s = "036000291453";
int total = 0;
for(int i=0; i<s.length(); i+=2) {
total = total + Character.getNumericValue(s.charAt(i));
}
System.out.println(total);
You can use Character.digit() method
public static void main(String[] args) {
String s = "036000291453";
int value = Character.digit(s.charAt(1), 10);
System.out.println(value);
}
Below code loops through any number that is a String and prints out the sum of the odd numbers at the end
String number = "036000291453";
int sum = 0;
for (int i = 0; i < number.length(); i += 2) {
sum += Character.getNumericValue(number.charAt(i));
}
System.out.println("The sum of odd integers in this number is: " + sum);
I tried the charAt(0)+charAt(2) etc, but it returns the digit at those
characters instead of adding them.
Character.getNumericValue(string.charAt(0));

Java - Adding Asterisks between a user inputted string

I'm working on a class assignment with a few individual parts, which I have all done with the exception of this one. I need to get a string input from the user and create a loop (preferably a for loop) that inserts asterisks between each character. I'm completely stumped on this one so if someone could just give me some help to get started it would be appreciated.
Edit: I've come up with this so far
} else if (choice.equalsIgnoreCase("C")) {
System.out.print("Enter text here: ");
String orig = input.nextLine();
// To use for asterisk insertion
int x = 1;
int y = 2;
for (int length = orig.length(); length > 0;) {
orig = orig.substring(0,x) + "*" + orig.substring(y);
x = x + 2;
y = y + 2;
}
}
It compiles just fine but when I test it and enter some text it comes up with
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
You could use a for loop on the characters of the String (see below), but I would just do this:
str = str.replaceAll("(?<=.)(?=.)", "*");
The regex in the search parameter matches the point between any two characters, achieved by using a look-behind and a look-ahead, each asserting that there's a character there.
If you must use a loop, the simplest code is probably:
String result = input.isEmpty() ? "" : input.substring(0, 1);
for (int i = 1; i < input.length(); i++)
result += "*" + input.charAt(i);
The somewhat complicated first line caters for the edge case of the user entering a blank. The for loop already caters for blank input, because the terminating condition will always be false for blank, so it won't iterate at all.

Categories

Resources