A
A
Alexander Petrenko2018-03-15 15:53:40
JavaScript
Alexander Petrenko, 2018-03-15 15:53:40

How to add 2 adjacent numbers in 1 line, with the condition that they are the same?

How to add 2 adjacent numbers in 1 line, with the condition that they are the same. For example, the line 111111 should turn into line 222 and then into 42.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2018-03-15
@Gelisore

function collapse(digits) {
    if (typeof digits !== 'string') {
        digits = '' + digits;
    }

    var result = '';

    for (var i = 0; i < digits.length; i++) {
        if (digits[i] === digits[i+1]) {
            result += (parseInt(digits[i]) + parseInt(digits[i+1]));
            i++;
        } else {
            result += digits[i];
        }
    }

    if (digits.length === result.length) {
        return result;
    } else {
        return collapse(result);
    }
}

var test = 111111;

console.log(collapse(test));

A
Aves, 2018-03-15
@Aves

function collapse(src) {
  var res = String.prototype.replace.call(src, /(\d)\1/g, (s, p) => p * 2);
  return res == src ? res : collapse(res)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question