The problem
Given a string "abc" and assuming that every letter within the string has a price equal to its place within the alphabet, our string may have a price of 1 + 2 + 3 = 6. Which means that: a = 1, b = 2, c = 3 ....z = 26.
You may be given an inventory of strings and your activity might be to return the values of the strings as defined above multiplied by the place of that string within the record. For our goal, place begins with 1.
nameValue ["abc","abc abc"] ought to return [6,24] due to [ 6 * 1, 12 * 2 ]. Be aware how areas are ignored.
"abc" has a price of 6, whereas "abc abc" has a price of 12. Now, the worth at place 1 is multiplied by 1 whereas the worth at place 2 is multiplied by 2.
Enter will solely include lowercase characters and areas.
The answer in Java code
Possibility 1:
class Resolution{
public static int [] nameValue(String [] arr){
String alpha = "abcdefghijklmnopqrstuvwxyz";
int[] out = new int[arr.length];
for (int i=0; i<arr.size; i++) {
int depend = 0;
for (int j=0; j<arr[i].size(); j++) {
int val = alpha.indexOf(arr[i].charAt(j));
if (val>-1) depend+=(val+1);
}
out[i] = depend*(i+1);
}
return out;
}
}
Possibility 2:
class Resolution{
public static int [] nameValue(String [] arr){
int[] consequence = new int[arr.length];
for (int i = 0; i < arr.size; i++){
consequence[i] = arr[i].chars().filter(e -> e != ' ').map(e -> e - 96).sum() * (i+1);
}
return consequence;
}
}
Possibility 3:
import static java.util.stream.IntStream.rangeClosed;
interface Resolution {
static int[] nameValue(String[] arr) {
return rangeClosed(1, arr.size)
.map(i -> i * arr[i - 1].chars().scale back(0, (s, c) -> s + Math.max(c - 96, 0)))
.toArray();
}
}
Check instances to validate our resolution
import org.junit.Check;
import static org.junit.Assert.assertArrayEquals;
import org.junit.runners.JUnit4;
import java.util.*;
public class SolutionTest{
personal static Random random = new Random();
personal static int [] ba56(String [] arr){
int temp = 0;
int [] res = new int[arr.length];
for(int i = 0;i<arr.size;++i){
for(char ch : arr[i].toCharArray())
if(Character. isLowerCase(ch))
temp += (int)ch - 96;
res[i] = temp*(i+1);
temp = 0;
}
return res;
}
personal static int random(int l, int u){
return random.nextInt(u-l)+l;
}
@Check
public void basicTests(){
assertArrayEquals(new int[]{6,24},Resolution.nameValue(new String[]{"abc","abc abc"}));
assertArrayEquals(new int[]{351,282,330},Resolution.nameValue(new String[]{"abcdefghijklmnopqrstuvwxyz","stamford bridge","haskellers"}));
}
@Check
public void randomTests(){
String abc = " abcdefghijklmnopqrstuvwxyzabc";
for(int okay=0;okay<100;okay++){
int arrLen = random(1,10), i = 0;
String [] arr = new String[arrLen];
whereas (i < arrLen){
String st = "";
int len = random(5,15);
for (int j = 0; j < len; ++j)
st += abc.charAt(random(0,27));
arr[i] = st;
i++;
}
assertArrayEquals(ba56(arr),Resolution.nameValue(arr));
}
}
}