Skip to content

Instantly share code, notes, and snippets.

@1cadumagalhaes
Last active June 23, 2021 17:53
Show Gist options
  • Save 1cadumagalhaes/818519e3957468e592b283d3837be192 to your computer and use it in GitHub Desktop.
Save 1cadumagalhaes/818519e3957468e592b283d3837be192 to your computer and use it in GitHub Desktop.
Sorteio

Para executar:

node sorteio -s=[sorteios] -n=[numeros] -min=[minimo] -max=[maximo]

Por padrão sorteios = 1, numeros = 6, min=1 e max=60.

Para instruções:

node sorteio -h
const { argv } = process;
function main(argv) {
argv = argv.slice(2);
if (argv[0] == 'help' || argv[0] == '-h') {
console.log('Execute "node sorteio -s=[sorteios] -n=[numeros] -min=[min] -max=[max], -r=[1 ou 0]"')
return;
}
args = {};
argv.forEach(a => {
let [k, v] = a.replace('-', '').split('=');
args[k] = v;
})
let { s, n, min, max, r } = args;
//[s, n, min, max] = argv; //pela posição do array
[sorteios, numeros, min, max, repeat] = [+s || 1, +n || 6, min != undefined ? +min : 1, +max || 60, !!r || false]
console.log({ sorteios, numeros, min, max, repeat })
joga(sorteios, numeros, min, max, repeat);
}
function random(min = 1, max = 60) {
return Math.floor(
Math.random() * (max - min + 1) + min
);
}
function joga(sorteios = 1, numeros = 6, min = 1, max = 60, repeat = false) {
//console.log(`${sorteios} sorteios de ${numeros} numeros\n------------------------`);
let resultado = [];
for (let i = 1; i <= sorteios; i++) {
let atual = sorteio(numeros, min, max, repeat);
resultado.push(atual);
}
console.table(resultado);
}
function sorteio(numeros = 6, min = 1, max = 60, repeat = false) {
let resultado = [];
if (max < numeros) repeat = true
while (resultado.length < numeros) {
let r = random(min, max);
if (repeat || !resultado.includes(r)) resultado.push(r);
}
return resultado;
}
main(argv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment