Thursday, February 29, 2024
HomeSoftware EngineeringGet the Consonant Worth in Java

# Get the Consonant Worth in Java

## The problem#

Given a lowercase string that has alphabetic characters solely and no areas, return the very best worth of consonant substrings. Consonants are any letters of the alphabet besides `"aeiou"`.

We will assign the next values: `a = 1, b = 2, c = 3, .... z = 26`.

For instance, for the phrase “zodiacs”, let’s cross out the vowels. We get: “z o d ia cs”

``````-- The consonant substrings are: "z", "d" and "cs" and the values are z = 26, d = 4 and cs = 3 + 19 = 22. The very best is 26.
remedy("zodiacs") = 26

For the phrase "power", remedy("power") = 57
-- The consonant substrings are: "str" and "ngth" with values "str" = 19 + 20 + 18 = 57 and "ngth" = 14 + 7 + 20 + 8 = 49. The very best is 57.
``````

## The answer in Java code#

Possibility 1:

``````import java.util.stream.*;
import java.util.*;

public class ConsonantValue {
public static int remedy(closing String s) {
return  Arrays.stream(s.cut up("[aeiou]+"))
.mapToInt(t->t.chars().sum()-t.size()*96)
.max()
.getAsInt();
}
}
``````

Possibility 2:

``````public class ConsonantValue {
public static int remedy(closing String s) {
int sum = 0, maxsum = 0;
char[] arr = s.toCharArray();
for (char c : arr) {
if ("aeiou".indexOf(c)>=0) sum = 0;
else {
sum += c-'a'+1;
maxsum = Math.max(sum, maxsum);
}
}
return maxsum;
}
}
``````

Possibility 3:

``````class ConsonantValue {
static int remedy(String s) {
int max = 0;
for (var sil : s.replaceAll("[aeiou]", " ").cut up(" ")) {
int worth = sil.chars().map(c -> c - 96).sum();
if (max < worth) max = worth;
}
return max;
}
}
``````

## Check instances to validate our resolution#

``````import org.junit.Check;

public class SampleTest {
@Check
public void basicTests() {
Tester.doTest("zodiac", 26);
Tester.doTest("chruschtschov", 80);
Tester.doTest("khrushchev", 38);
Tester.doTest("power", 57);
Tester.doTest("catchphrase", 73);
Tester.doTest("twelfthstreet", 103);
Tester.doTest("mischtschenkoana", 80);
}
}
``````
RELATED ARTICLES