arrays - Java: Assign values to alphabet and determine value of a string -
so trying solve problem in java below. give me idea of how approach this? can think of using bunch of confusing for-loops split arr, go through alphabet, , go through each string, , confused strings versus chars. advice great.
--
suppose letter 'a' worth 1, 'b' worth 2, , forth, 'z' worth 26. value of word sum of letter values in it. given array arr of words composed of capital letters, return value of watch largest value. may assume arr has length @ least 1.
{"aaa","bbb","ccc"} => 9
{"aaaa","b","c"} => 4
{"z"} => 26
{"",""} => 0
--
here have tried far i'm lost:
public static int largestvalue(string[] arr){ string alphabet = "abcdefghijklmnopqrstuvwxyz"; int largest = 0; int wordtotal=0; (int = 0; < arr.length; i++){ string[] parts = arr[i].split(""); if (wordtotal < largest){ //i don't think in right place largest = 0; } (int j = 0; j < alphabet.length(); j++){ for(int k = 0; k <parts.length; k++){ if ( alphabet.charat(j) == parts[k].charat(0) ){ wordtotal = 0; wordtotal += alphabet.indexof(alphabet.charat(j))+1; } } } } return largest; }
i start breaking problem parts, first step summing 1 string
. calculate sum
can iterate characters, test if character between 'a'
, 'z'
(although requirements input guaranteed valid), subtract 'a'
(a char
literal) character , add sum
. like,
static int sumstring(final string str) { int sum = 0; (char ch : str.tochararray()) { if (ch >= 'a' && ch <= 'z') { // <-- validate input sum += 1 + ch - 'a'; // <-- 'a' - 'a' == 0, 'b' - 'a' == 1, etc. } } return sum; }
then can iterate array of string
(s) maximum sum; like
static int maxstring(string[] arr) { int max = sumstring(arr[0]); (int = 1; < arr.length; i++) { max = math.max(max, sumstring(arr[i])); } return max; }
or java 8+
static int maxstring(string[] arr) { return stream.of(arr).maptoint(x -> sumstring(x)).max().getasint(); }
and, finally, validate entire operation like
public static void main(string[] args) { string[][] strings = { { "aaa", "bbb", "ccc" }, { "aaaa", "b", "c" }, { "z" }, { "", "" } }; (string[] arr : strings) { system.out.printf("%s => %d%n", arrays.tostring(arr), maxstring(arr)); } }
and get
[aaa, bbb, ccc] => 9 [aaaa, b, c] => 4 [z] => 26 [, ] => 0