- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Crack Alphabets fight problem in JavaScript
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 −
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
- Related Articles
- Number to alphabets in JavaScript
- Indexing numbers to alphabets in JavaScript
- Sorting alphabets within a string in JavaScript
- Decreasing order sort of alphabets in JavaScript
- Converting alphabets to Greek letters in JavaScript
- Reversing alphabets in a string using JavaScript
- Snail Trail Problem in JavaScript
- Recursive Staircase problem in JavaScript
- Distributing Bananas Problem in JavaScript
- The Fight
- Boss Fight in Python
- Replace alphabets with nth forward alphabet in JavaScript
- Recursion problem Snail Trail in JavaScript
- Expressive words problem case in JavaScript
- 2 Key keyboard problem in JavaScript

Advertisements