Skip to content

Instantly share code, notes, and snippets.

@SackeyDavid
Created September 19, 2021 01:51
Show Gist options
  • Save SackeyDavid/11701048859f47b7b98fbcc69631a033 to your computer and use it in GitHub Desktop.
Save SackeyDavid/11701048859f47b7b98fbcc69631a033 to your computer and use it in GitHub Desktop.
Turing Coding Challenge Practise Test
// console.log("Hello, World!");
var calPoints = function(ops) {
result = null;
output = [];
checks = true;
// check constraints
// check if operations length constraints is met
if(!(ops.length >= 1 || ops.length <= 1000))
{
checks = false;
}
// check if operations constraints is met
for (var i = 0; i < ops.length; i++) {
if(!((ops[i]*1 >= (-3*104) || ops[i]*1 <= (3*104)) || ops[i] == '+' ||
ops[i] == 'C' || ops[i] == 'D'))
{
checks = false;
}
}
// check if '+' contraint is met
for (var i = 0; i < ops.length; i++) {
if((ops[i] == '+') && (i <= 1))
{
console.log('constraints 3')
checks = false;
}
}
// check if 'C', 'D' contraint is meet
for (var i = 0; i < ops.length; i++) {
if((ops[i] == 'C' || ops[i] == 'D') && (i < 1))
{
checks = false;
}
}
if(checks) {
output[0] = parseInt(ops[0]);
for (var i = 1; i < ops.length; i++) {
// if score is a number
if(ops[i] !== 'D' && ops[i] !== 'C' && ops[i] !== '+')
{
// add score to output
output.push(parseInt(ops[i]));
}
if(ops[i] == 'C')
{
// remove the previous score
output.splice(output.length - 1, 1);
}
if(ops[i] == 'D')
{
// add double the previous score
output.push(parseInt(output[output.length - 1]*2));
}
if(ops[i] == '+')
{
// add the sum of the two previous score
output.push(output[output.length -1] + output[output.length - 2]);
}
}
}
var sum = function(arr) {
var s = 0;
for (var i = 0; i < arr.length; i++) {
s+= arr[i];
}
return s;
}
return sum(output);
}
var ops = '5 2 C D +'.split(" ")
console.log(calPoints(ops))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment