In: Computer Science
Split the Number
IN JAVASCRIPT
Programming challenge description:
You are given a number N and a pattern. The pattern consists of
lowercase latin letters and one operation "+" or "-". The challenge
is to split the number and evaluate it according to this pattern
e.g.
1232 ab+cd -> a:1, b:2, c:3, d:2 -> 12+32 -> 44
Input:
Your program should read lines from standard input. Each line contains the number and the pattern separated by a single whitespace. The number will be in range [100, 1000000000]. All test cases contain valid expressions (no leading zeros).
Output:
Print out the result of the pattern evaluation.
Test 1
Test InputDownload Test 1 Input
3413289830 a-bcdefghij
Expected OutputDownload Test 1 Input
-413289827
Test 2
Test InputDownload Test 2 Input
776 a+bc
Expected OutputDownload Test 2 Input
83
Solution:
//importing the readline module to allow taking standart input
const readline = require ('readline').createInterface ({
input: process.stdin,
output: process.stdout,
});
//prompting user to enter the requrired input
readline.question ('Enter the number and pattern: ',
//the entered value is stored in 'input' variable.
input => {
//Step 1. Split the input by specifying whitespace character as the delimeter
var splittedInput = input.split (' ');
//the number is in the 0th index of splitted string
var number = splittedInput[0];
//the pattern is on the 1st index of splitted string
var pattern = splittedInput[1];
//decalring the digits array to store the digits of number
var digits = [];
//while loop to extract the digits and add them in the digits array
while (number != 0) {
digit = number % 10;
digits.push (digit);
//Math.floor is used to make sure that number remains in integer form
number = Math.floor (number / 10);
}
//reversing the digits array to get the actual order of digits.
digits.reverse ();
//declaring a variable to store final expression
var expression = '';
//variable to count the number of digits traversed
var count = 0;
//for loop to traverse the expression received from user input
//and set the final expression
for (let i = 0; i < pattern.length; i++) {
//if the element is + or - , add them to expression
if (pattern[i] == '+' || pattern[i] == '-') expression += pattern[i];
//else add the digit to the expression and increase the count variable
else {
expression += digits[count];
count++;
}
}
//evaluate the final expression using the inbuilt eval() function
var result = eval (expression);
// print the final result
console.log ("Result is: "+result);
//close the input stream
readline.close();
});
Screenshot of code for better understanding:
Sample Output:
After reading the input from standard input, we split it using the string.split() function to extract the number and the pattern. Then we extract the individual digits of number in array. After this, we loop through the expression to make our final expression replacing letter with the digits and then evaluate it using the eval function of javascript.