depois de muitos erros meu código ficou assim, diferente do mostrado nas aulas, então decidi postar para talvez ajudar outras pessoas com dificuldade.
function adicionar() {
let nomeAmigo = document.getElementById('nome-amigo').value.trim();
if (nomeAmigo === '') {
alert('Por favor, insira um nome válido.');
document.getElementById('nome-amigo').value = '';
return;
}
let listaAmgs = document.getElementById('lista-amigos');
let novoItem = document.createElement('li');
novoItem.textContent = nomeAmigo;
listaAmgs.appendChild(novoItem);
document.getElementById('nome-amigo').value = '';
}
function shuffle(array) {
let a = array.slice();
for (let i = a.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function sortear() {
let listaAmgs = document.getElementById('lista-amigos');
let listaNomes = listaAmgs.getElementsByTagName('li');
let listaSorteio = document.getElementById('lista-sorteio');
listaNomes = Array.from(listaNomes).map(item => item.textContent);
if (listaNomes.length <= 2) {
alert('Adicione pelo menos três nomes antes de sortear!');
return;
}
// nomes idênticos podem causar ambiguidade na comparação; exigir nomes únicos
if (new Set(listaNomes).size !== listaNomes.length) {
alert('Existem nomes duplicados. Por favor, use nomes únicos para o sorteio.');
return;
}
// Gera uma permutação onde ninguém recebe o próprio nome (derangement)
let shuffled;
let tentativas = 0;
do {
shuffled = shuffle(listaNomes);
tentativas++;
if (tentativas > 1000) {
alert('Não foi possível sortear corretamente. Tente novamente.');
return;
}
} while (shuffled.some((v, i) => v === listaNomes[i]));
let amigosSorteados = {};
for (let i = 0; i < listaNomes.length; i++) {
amigosSorteados[listaNomes[i]] = shuffled[i];
}
listaSorteio.innerHTML = '';
for (let amigo in amigosSorteados) {
let itemSorteio = document.createElement('p');
itemSorteio.textContent = `${amigo} → ${amigosSorteados[amigo]}`;
listaSorteio.appendChild(itemSorteio);
}
}
function reiniciar() {
let reinicarSorteio = document.getElementById('lista-sorteio');
reinicarSorteio.innerHTML = '';
let listaAmgs = document.getElementById('lista-amigos');
listaAmgs.innerHTML = '';
}