Crack Alphabets fight problem in JavaScript

Web DevelopmentJavascriptFront End Technology

Problem

Consider a situation where armies of two bunch of alphabets are fighting each other. The soldiers of both and their weight are as follows −

TeamA

Soldier
Weight
A
1
B
2
C
3
D
4

TeamB

Soldier
Weight
W
1
X
2
Y
3
Z
4

Other than the soldiers, there are bombs as well in the arena denoted by ‘!’, and a bomb kills soldiers placed at its adjacent sides.

For instance: ‘A!BC’ will result in ‘C’ and ‘!!CC!!’ will result in ‘’.

Our function should need to find out when all the bombs in the arena explode which team wins or if both the teams end up with the same weight.

For example, if the input to the function is −

Input

const str = '!WX!YZ!DC!BA!';

Output

const output = 'Tie';

Output Explanation

Because after all the bombs explode both the teams will end up with the same score.

Example

Following is the code −

 Live Demo

const str = '!WX!YZ!DC!BA!';
const stringFight = (str) => {
   const map = {
      'D': 4,'C': 3,'B': 2,'A': 1,
      'Z': -4,'Y': -3,'X': -2,'W': -1
   };
   const arr = [];
   const arr1 = str.split('');
      for(let i=0;i<str.length;i++){

      if(arr1[i-1] !== '!' && arr1[i] !== '!' && arr1[i+1] !== '!'){
         arr.push(arr1[i]);
      };
   };
      const sum = arr.reduce((a, b) => a + (map[b] ? map[b] : 0), 0);
      if(sum < 0){
         return 'Team B';
      if(sum < 0){
         return 'Team B';
      }else if(sum > 0){
         return 'Team A';
      }else{
         return 'Tie';
      };
   };
console.log(stringFight(str));

Output

Tie
raja
Published on 22-Apr-2021 11:38:28
Advertisements