How to find a missing integer in a chain of random non-repeating integers in a range

I'm having problems, even starting to think about how to do this.

I need to find the missing number in a string of random numbers that do not have separators.

Here is an example: 14036587109. In this example, the missing number 2, range 0-10(inclusive).

How can I write a JavaScript / Node.JS program to solve this problem?

The part I cannot understand is how the program divides the numbers; In the above example, as if the program knew that the number 10(to the last number) is not a number 1and 0.

+4
source share
3 answers

, : ( @samgak ), , . , . , :

; , , 0-999, , 2, 1.

, .

, , , ; , , , , ; 357 :

... 1235789 ... 2435768 ...
      357         357
     23          43
    123         243
     235         435
       578         576
        78          76
        789         768

357 , 23, 123, 235, 578, 78 789. 43, 243, 435, 576, 76 768.

, , .

, 3, 4,... . , , , , , , . ( , , .) .


, , , , , . , : , , , , .


, . - , , - , , - ... , , .

. 0-5000, , . ( , , ) , , , , , x 3- ... , , .

+4

/:

, . startRange endRange, .

, , , .

, , .

const str = "14036587109"; // input

const numsLeft = str.split("").map(num => parseInt(num)); // array of numbers

const startRange = 0;
const endRange = 10;

for(let i = startRange; i <= endRange ; i++) {
    
    // check if number can be formed given the numbers left in numsLeft
    const numFound = findNum(numsLeft, i);

    if(!numFound) {
        console.log("MISSING: " + i); // prints 2 
        break;
    }
}

function findNum(numsLeft, i) {
    
    // array of digits
    const numsToFind = String(i).split("").map(num => parseInt(num)); 
    
    // default is true, if all digits are found in numsLeft
    let found = true; 

    numsToFind.forEach(num => {

        // find digit in numsLeft
        const numFoundIndex = numsLeft.indexOf(num); 

        if(numFoundIndex < 0) { 

            // digit was not found in numsLeft
            found = false;
            return;

        } else {

            // digit was found; delete digit from numsLeft
            numsLeft.splice(numFoundIndex, 1); 
        }

    });

    return found;
}
Hide result
+2
var input = '10436587109';
var range = [10,9,8,7,6,5,4,3,2,1,0];
var expr1 = new RegExp(range.join('|'),'g');
var expr2 = new RegExp('[0-9]','g');

var a = input.match(expr1).map(Number).concat(input.match(expr2).map(Number));
var x = range.filter(function(i){ return a.indexOf(i)===-1; });
-1
source

Source: https://habr.com/ru/post/1690488/


All Articles