Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

333
Visualizações
Cola de prioridad en JavaScript, no puedo agregar más de un nodo
class PriorityQueue { constructor() { this.values = [] } enqueue(value, priority) { if(this.values.length === 0) { this.values.push({value: value, priority: priority}) return this.values; } this.values.push({value, priority}); this.bubbleUp(this.values); } bubbleUp(values) { let childIndex = values.length-1; let parentIndex; parentIndex = Math.floor((childIndex-1)/2); let childNode, parentNode, temp; console.log(parentIndex, childIndex); console.log(values[parentIndex].priority, values[childIndex].priority) while ((values[childIndex].priority) < (values[parentIndex].priority)) { childNode = values[childIndex]; parentNode = values[parentIndex]; temp = childNode; childNode = parentNode; parentNode = temp; values[childIndex] = childNode; values[parentIndex] = parentNode; childIndex = parentIndex; parentIndex = Math.floor((childIndex-1)/2); } return values; } }

Lo anterior es mi implementación de la cola de prioridad usando JavaScript. Estoy almacenando los datos en una matriz que contiene nodos que son objetos como este
{valor: "algo", prioridad: 1}

Cuando intento agregar el segundo nodo mediante el método de puesta en cola, aparece un error en la condición while .

 Uncaught TypeError: Cannot read properties of undefined (reading 'priority')

Puedo ver claramente los valores de prioridad de los nodos en la declaración anterior de console.log. No puedo entender por qué falla la condición del bucle con un error que dice que estoy tratando de leer las propiedades de undefined.

Cualquier ayuda será apreciada.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Mira esto,

 class Node { constructor(data, priority) { this.data = data; this.priority = priority; } } class PQ { constructor() { //Initialing the array heap and adding a dummy element at index 0 this.heap = []; } getMin() { //Accessing the min element at index 1 in the heap array return this.heap[0]; } enqueue(data, priority) { let newNode = new Node(data, priority); this.heap.push(newNode); let currentIndex = this.heap.length - 1; let parentIndex = Math.round(currentIndex / 2) - 1; while ( currentIndex > 0 && this.heap[parentIndex].priority > this.heap[currentIndex].priority ) { [this.heap[parentIndex], this.heap[currentIndex]] = [ this.heap[currentIndex], this.heap[parentIndex], ]; currentIndex = parentIndex; } } dequeue() { //Smallest element is at the index 1 in the heap array let smallest = this.heap[0]; if (this.heap.length === 1) { //If there are only two elements in the array, we directly splice out the first element this.heap.splice(0, 1); } //When there are more than two elements in the array, we put the right most element at the //first position and start comparing nodes with the child nodes if (this.heap.length >= 2) { this.heap[0] = this.heap[this.heap.length - 1]; this.heap.splice(this.heap.length - 1); if (this.heap.length === 2) { if (this.heap[0].priority > this.heap[1].priority) { [this.heap[0], this.heap[1]] = [this.heap[1], this.heap[0]]; } return smallest; } let current = 0; let leftChildIndex = current * 2 + 1; let rightChildIndex = current * 2 + 2; while ( this.heap[leftChildIndex] && this.heap[rightChildIndex] && (this.heap[current].priority > this.heap[leftChildIndex].priority || this.heap[current].priority > this.heap[rightChildIndex].priority) ) { if (this.heap[leftChildIndex].priority < this.heap[rightChildIndex].priority) { [this.heap[current], this.heap[leftChildIndex]] = [ this.heap[leftChildIndex], this.heap[current], ]; current = leftChildIndex; } else { [this.heap[current], this.heap[rightChildIndex]] = [ this.heap[rightChildIndex], this.heap[current] ]; current = rightChildIndex; } leftChildIndex = current * 2 + 1; rightChildIndex = current * 2 + 2; } } return smallest; } } const pq = new PQ(); pq.enqueue(3, 2); pq.enqueue(4, 5); pq.enqueue(31, 1); pq.enqueue(6, 3); console.log(pq.heap); console.log(pq.dequeue()); console.log(pq.dequeue()); console.log(pq.dequeue()); console.log(pq.dequeue());

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda