I am doing this function in which a number is passed as a parameter; If it has any repeated digits, then it looks for the next largest number that does not have the same digits.
Ex:
proximoNumero(2002)
->return 2013
Ex:
proximoNumero(1001)
->return 1023
Ex:
proximoNumero(899)
->return 901
function proximoNumero(numero){
numero = (numero+1).toString().split('')
for(let i=0; i<numero.length-1; i++){
for(let j=i+1; j<numero.length; j++){
if(numero[i] === numero[j]){
console.log(`${numero} se repite ${numero[i]}`);
proximoNumero(Number(numero.join('')))
}
}
}
return numero.join('')
}
console.log(proximoNumero(1001));
my function is doing something similar but I don't understand why once it is called recursively with a number without repeated characters it returns the first number that is passed to it by parameter
You are missing a return when making the recursive call that breaks (exits) the double loop:
@Pablo-Lozano's answer is the most accurate.
I thought it might be useful ( perhaps for other users ) to give a solution without using recursion.
To achieve this we can do the following:
[...
${number}] ===> array
)array.some((val, idx, arr) => arr.lastIndexOf(val) != idx) ===> bool
)while (bool) number++
)return number
).Example:
Example using
RegExp
:A different alternative would be to check with a regex if there are repeated numbers, if there are repeated we add one:
This way we always work with numbers, we don't do any explicit conversion. Using @Marcos's regex, which is better because it doesn't look for a full math, it would be simply: