DEV Community

Discussion on: Daily Challenge #287 - 16+18=214

Collapse
 
willsmart profile image
willsmart

A quickie in Typescript
Each digit is enumerated in turn by skimming off the ones digit off each number (using num%10, then dividing the number by 10) until there are no more digits.
The accumulated sum is simply a string with each sum added to its left-hand side.

function piecewiseAdd(addendA: number, addendB: number): number {
  let sumString = '';
  while (addendA || addendB) {
    sumString = (addendA % 10) + (addendB % 10) + sumString;
    addendA = Math.floor(addendA / 10);
    addendB = Math.floor(addendB / 10);
  }
  return +sumString;
}

Testn

> piecewiseAdd(0,0)
< 0
> piecewiseAdd(1222, 30277)
< 31499
> piecewiseAdd(1236, 30889)
< 31101115
> piecewiseAdd(49999, 49999)
< 818181818
Collapse
 
qm3ster profile image
Mihail Malo • Edited

You already did the skimming, but you could also avoid stringification altogether: dev.to/qm3ster/comment/14en6

Collapse
 
willsmart profile image
willsmart

Thanks, that's a fair point. Here's the tweaked code:

function piecewiseAdd_numeric(addendA: number, addendB: number) : number {
  let sum = 0, cursor = 1;
  while (addendA || addendB) {
    const digitSum = (addendA % 10) + (addendB % 10);
    sum += cursor * digitSum;
    cursor *= digitSum < 10 ? 10 : 100;
    addendA = Math.floor(addendA / 10);
    addendB = Math.floor(addendB / 10);
  }
  return sum;
}

Benchmark here -- numeric method has it by a nose most of the time you run it, sometimes a bit more. For smaller inputs they're pretty much even.

In C or Rust or something closer to the metal Mihail's post is definitely the way to go (imo).
In JS strings are pretty quick and numbers are surprisingly slow to deal with (there's no support for integers, etc) and I find the language doesn't really reward that kind of close-knit optimization, so I felt it wasn't worth the additional complication.

Thread Thread
 
qm3ster profile image
Mihail Malo

I wonder what the result with asm.js would be.
There are some claims that in the process of implementing asm.js V8 in particular just optimized normal code to the speed of corresponding asm.js, but some extra assertions might still help?