dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
1.9 KiB
1.9 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 69bc6cb30c1d112a2e110a06 | Challenge 249: String Math | 28 | challenge-249 |
--description--
Given a string with numbers and other characters, perform math on the numbers based on the count of non-digit characters between the numbers.
- If the count of characters separating two numbers is even, use addition.
- If it's odd, use subtraction.
- Consecutive digits form a single number.
- Operations are applied left to right.
- Ignore leading and trailing characters that aren't digits.
For example, given "3ab10c8", return 5. Add 3 and 10 to get 13 because there's an even number of characters between them. Then subtract 8 from 13 because there's an odd number of characters between the result and 8.
--hints--
doMath("3ab10c8") should return 5.
assert.equal(doMath("3ab10c8"), 5);
doMath("6MINUS4") should return 2.
assert.equal(doMath("6MINUS4"), 2);
doMath("9plus3") should return 12.
assert.equal(doMath("9plus3"), 12);
doMath("5fkwo#10i#%.<>15P=@20!#B/25") should return 15.
assert.equal(doMath("5fkwo#10i#%.<>15P=@20!#B/25"), 15);
doMath("a.67,1$lk6ldf34@#LD@]2d32d2'2l3,@l3L#@2gh35s09if=df#$t9sm49t0df3$^%[vc;:0:4mt") should return 67.
assert.equal(doMath("a.67,1$lk6ldf34@#LD@]2d32d2'2l3,@l3L#@2gh35s09if=df#$t9sm49t0df3$^%[vc;:0:4mt"), 67);
--seed--
--seed-contents--
function doMath(str) {
return str;
}
--solutions--
function doMath(str) {
const tokens = str.match(/(\d+)|(\D+)/g);
let result = null;
let pendingOp = null;
for (const token of tokens) {
if (/^\d+$/.test(token)) {
if (result === null) {
result = parseInt(token);
} else {
result = pendingOp === 'add' ? result + parseInt(token) : result - parseInt(token);
}
} else {
pendingOp = token.length % 2 === 0 ? 'add' : 'subtract';
}
}
return result;
}