Anagram Sum
Joey had neatly arranged some words using plastic alphabets corresponding to the integers zero through nine. But as he went to show his project to his dad, he tripped and all his alphabets got jumbled up. Can you find the sum of all the words he had arranged, so he gets an A for effort?
Input Format
The first line contains the jumbled string, S There can be multiple instances of each integer word in S. You can assume are no extra letters in the string.
eg.ehfrzeevteeonoir
Output Format
An integer which has the sum of all integers in the jumbled string S.
eg. ans=9(zerooonethreefive=0135=0+1+3+5)
code in cpp
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AnagramSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
scanner.close();
Map<Character, Integer> charToNum = createCharToNumMapping();
int sum = 0;
for (char c : s.toCharArray()) {
if (charToNum.containsKey(c)) {
sum += charToNum.get(c);
}
}
System.out.println("Sum of the integers in the jumbled string: " + sum);
}
private static Map<Character, Integer> createCharToNumMapping() {
Map<Character, Integer> charToNum = new HashMap<>();
charToNum.put('z', 0);
charToNum.put('o', 1);
charToNum.put('t', 2);
charToNum.put('h', 3);
charToNum.put('f', 4);
charToNum.put('i', 5);
charToNum.put('s', 6);
charToNum.put('e', 7);
charToNum.put('g', 8);
charToNum.put('n', 9);
return charToNum;
}
}
1 Like
can you please provide the code in cpp or explain how the code works exactly