JSFiddle - React, Tailwind, and code Playground
by Ishank Dubey
JavaScript
function solution(N, S, T) {
// write your code in JavaScript (Node.js 6.4.0)
var ships = S.split(",");
var targetArray = T.split(","), totalHits=0, totalSunk=0;
shipeCoCollection = [];
for (let i = 0; i < ships.length; i++) {
var cordinateArray = [];
var localArr = ships[i].split(" ");
if(localArr && localArr.length>1){
if (localArr[0].charAt(0) == localArr[1].charAt(0)) {
let aChar = localArr[0].charAt(1);
while (aChar <= localArr[1].charAt(1)) {
cordinateArray.push(localArr[0].charAt(0) + "" + aChar);
aChar = String.fromCharCode(aChar.charCodeAt(0) + 1);
}
} else if (localArr[0].charAt(1) == localArr[1].charAt(1)) {
let aNum = parseInt(localArr[0].charAt(0));
while (aNum <= localArr[1].charAt(0)) {
cordinateArray.push(aNum + "" + localArr[0].charAt(1));
aNum = aNum + 1;
}
} else {
cordinateArray.push(localArr[0]);
cordinateArray.push(localArr[1]);
cordinateArray.push(localArr[0].charAt(0) + "" + String.fromCharCode(localArr[0].charAt(1).charCodeAt(0) + 1));
cordinateArray.push(parseInt(localArr[0].charAt(0)) + 1 + "" + localArr[0].charAt(1));
}
}else{
if(localArr && localArr.length==1)
cordinateArray.push(localArr[0]);
}
shipeCoCollection.push(cordinateArray);
}
for (let i = 0; i < shipeCoCollection.length; i++) {
let anArray = shipeCoCollection[i],
matches = 0,
hits = 0,
sunk = 0;
for (let j = 0; j < targetArray.length; j++){
if(anArray.indexOf(targetArray[j])!=-1){
matches++;
}
}
if(matches==anArray.length){
totalSunk++;
}{
if(matches)
totalHits++;
}
}
return totalHits+"H"+","+totalSunk+"S"
}
console.log(solution("", "1B 2C,2D 4D,1A,1A 1B", "1A,1B,1C"));