No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Playground: implementa el metodo Delete

13/29

Aportes 20

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

o inicia sesión.

Mi solución
No retorno undefined ya que por defecto este se retorna si no halla el dato.
El código esta comentado para mejor entendimiento de lo que hace.

  delete(key) {
    //* obtengo el hash del address
    const address = this.hashMethod(key)
    //* Obtengo el bucket donde debo buscar el espacio a eliminar
    const currentBucket = this.data[address]

    if (currentBucket) {
      //* recorriendo el espacio
      for (let i = 0; i < currentBucket.length; i++) {
        if (currentBucket[i][0] === key) {
          //* guardo el espacio para retornarlo luego
          let deletedSpace = currentBucket[i]
          //* elimino el espacio
          delete currentBucket[i]
          //* elimino el espacio vacio para que los demas espacios recorran
          currentBucket.splice(i, 1)
          return deletedSpace
        }
      }
    }
  }

Me costó pero aquí aporto mi solución,


import { HashTable } from "./hashTable";

export class Solution extends HashTable {
  constructor(size) {
    super()
    this.data = new Array(size);
  }

  delete(key){
    // Tu código aquí 👈
    const address = this.hashMethod(key);
    const currentBucket = this.data[address];
    let itemDeleted
    if (currentBucket) {
      for (let i = 0; i < currentBucket.length; i++) {
        if (currentBucket[i][0] === key) {
          const index = i
          itemDeleted = currentBucket[i]
          if (currentBucket.length > 1) {
            for (let i = index; i < currentBucket.length - 1; i++) {
              this.data[address][0] = this.data[address][i + 1];
            }
            delete this.data[address][currentBucket.length - 1]
            console.log("Se ha eliminado el elemento");
            return itemDeleted
          } else {
            delete this.data[address];
            console.log("Se ha liberado el Address");
            return itemDeleted
          }
        }
      }
    }
    console.log("No se encontro ningun elemento a borrar");
    return undefined
  }
}

Estuve viendo el curso de complejidad algorítmica, así que me esforcé por hacer sin usar dos ciclos 😄

    delete(key) {
        const address = this.hashMethod(key);
        const currentBucket = this.data[address];

        if (currentBucket) {
            for (let i = 0; i < currentBucket.length; i++) {
                let backup = [];
                var elementForReturn;
                if (currentBucket[i][0] === key) {
                    elementForReturn = [...this.data[address][i]];
                    delete this.data[address][i];
                } else {
                    if (true) {
                        backup.push(currentBucket[i]);
                    }
                }
                if (this.data.length > backup.length && i+1 == currentBucket.length ) {
                    this.data[address] = backup;
                    console.log(elementForReturn);
                    return elementForReturn;
                }
                
            }
        }

        return undefined;

    }

Uffff, aquí mi solución:

<import { HashTable } from "./hashTable";

export class Solution extends HashTable {
  constructor(size) {
    super()
    this.data = new Array(size);
  }

  delete(key){
    const address = this.hashMethod(key);
    const currentBucket = this.data[address];
    if (currentBucket) {
      for (let i = 0; i < currentBucket.length; i++) {
        if (currentBucket[i][0] === key) {
          const item = currentBucket[i];
          for (let j = i; j < currentBucket.length; j++){
            currentBucket[j] = currentBucket[j+1];
          }
          if (currentBucket.length > 1) {
            delete currentBucket[currentBucket.length - 1];
            currentBucket.length--;
          } else {
            delete this.data[address];
          }
          return item;
        }
      }
    }> 

JAjajaja, en la clase anterior ya había colocado la respuesta sin saber.

  delete(key) {
    const address = this.hashMethod(key);
    const currentBucket = this.data[address];
    if (currentBucket) {
      for (let i = 0; i < currentBucket.length; i++) {
        if (currentBucket[i][0] === key) {
          const deleted = currentBucket[i];
          currentBucket.splice(i, 1);
          return deleted;
        }
      }
    }
    return undefined;
  }

Solución

import { HashTable } from "./hashTable";

export class Solution extends HashTable {
  constructor(size) {
    super()
    this.data = new Array(size);
  }

  delete(key){
    // Tu código aquí 👈
    const address = this.hashMethod(key);
    const currentBucket = this.data[address];

    if (currentBucket) {
      for (let i = 0; i < currentBucket.length; i++) {
        if (currentBucket[i][0] === key) {
          let deletedKey = currentBucket[i];
          delete currentBucket[i];
          currentBucket.splice(i, 1);
          return deletedKey;
        }
      }
    }

    return undefined;   
  }
}

Mi humilde aporte a la comunidad… 😃

delete(key) {
// Tu código aquí 👈
const hashKey = this.hashMethod(key);
let item;

if (this.data[hashKey].length) {
for (let i = 0; i < this.data[hashKey].length; i++) {
if (this.data[hashKey][i][0] === key) {
item = this.data[hashKey][i];
this.data[hashKey].splice(i, 1);
return item;
}
}
} else {
return undefined;
}
}

import { HashTable } from "./hashTable";

export class Solution extends HashTable {
  constructor(size) {
    super()
    this.data = new Array(size);
  }

  delete(key){
    const address = this.hashMethod(key);
    let found = false;
    for (let i = 0; i < this.data[address].length; i++) {
      if (found) {
        this.data[address][i - 1] = this.data[address][i];
      }
      if (this.data[address][i][0] === key) {
        found = this.data[address][i];
        delete this.data[address][i];
      }
    }
    if (found) {
      this.data[address].pop();
      return found;
    } else {
      return undefined;
    }
  }
}

Les comparto mi solución:

  delete(key) {
    const address = this.hashMethod(key);
    const currentBucket = this.data[address];
    if (currentBucket) {
      let deletedValue = currentBucket.filter(item => item[0] === key).flat(1);
      if (currentBucket.length === 1) {
        this.data[address] = [];
      } else {
        let newValue = currentBucket.filter(item => item[0] !== key);
        this.data[address] = newValue;
      }
      return deletedValue;
    }
    return undefined;
  }

best solution v2

delete(key) {
    const address = this.hashMethod(key);
    const currentBucket = this.data[address];
    if(currentBucket && currentBucket.length != 0) {
      if(currentBucket.length > 1){
        for(let i =0; i< currentBucket.length; i++) {
          if(currentBucket[i][0] === key) {
            let newbucket = currentBucket.filter(item => item[0] != key);
            if(newbucket.length>0){
              this.data[address] = newbucket;
            }else {
              delete this.data[address];
            }
            return this.data[address];
          }
        }
      }else{
        delete this.data[address];
        return currentBucket;
      }
    }

    return undefined;
  }

the best solution

import { HashTable } from "./hashTable";

export class Solution extends HashTable {
  constructor(size) {
    super()
    this.data = new Array(size);
  }

  delete(key) {
    const address = this.hashMethod(key);
    const currentBucket = this.data[address];
    if (currentBucket && currentBucket.length != 0) {
      if (currentBucket.length > 1) {
        for (let i = 0; i < currentBucket.length; i++) {
          if (currentBucket[i][0] === key) {
            let newbucket = [];
            for (let j = 0; j < currentBucket.length; j++) {
              if (currentBucket[j][0] != key) {
                newbucket.push(currentBucket[j])
              }
            }
            if (newbucket.length > 0) {
              this.data[address] = newbucket;
            } else {
              delete this.data[address];
            }
            return this.data[address];
          }
        }
      } else {
        delete this.data[address];
        return currentBucket;
      }
    }

    return undefined;
  }
}

Comparto mi solucion utilice splice para no hacer ciclos dentro de ciclos

delete(key) {
        const address = this.hashMethod(key);
        const currentBucket = this.data[address];
        if (currentBucket) {
            for (let i = 0; i < currentBucket.length; i++) {
                if (currentBucket[i][0] === key) {
                    let value = this.data[address][i];
                    //Elimina el espacio y reordena el arreglo
                    currentBucket.splice(i, 1)
                    //Retorna el valor eliminado
                    return value;
                }
            }
        }
        return undefined;
    }

Estuvo interesante gracias al get pude copiar una estructura parecida para tener el currentBucket para después solo eliminarlo

<code> 
delete(key){
    const address = this.hashMethod(key)
    const currentBucket = this.data[address];
    if (currentBucket) {
      for (let i = 0; i < currentBucket.length; i++) {
        if (currentBucket[i][0] === key) {
          const deleteBucket = [...currentBucket[i]]
          currentBucket.splice(i,1)
          return deleteBucket;
        }
      }
    }
    return undefined;
  }
</code>

Saludos, acá les dejo mi aporte. Lo resolví usando los conceptos que hemos visto desde el inicio del curso.
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽
👇🏽

delete(key){
    const address = this.hashMethod(key)
    const currentBucket = this.data[address]
    let bucketToDelete
    if (currentBucket) {
      for (let i = 0; i < currentBucket.length; i++) {
        //console.log(currentBucket[i][0])
        if (currentBucket[i][0] === key) {
          bucketToDelete = currentBucket[i]
          let position = i
          if(position === currentBucket.length-1){
            currentBucket.pop()
          } else if(position === 0){
            currentBucket.shift()
          } else {
             for (let i = position ; i <= currentBucket.length - 1; i++) {
                    currentBucket[i] = currentBucket[i + 1];
                        }
                currentBucket.pop()
            console.log(currentBucket,"<")
          }
        }
      }
      return bucketToDelete
    }

Mi solución

export class Solution extends HashTable {
  constructor(size) {
    super()
    this.data = new Array(size);
  }

  delete(key){
    // Tu código aquí 👈
    const address = this.hashMethod(key);

    if (this.data[address]) {
      const currentBucket = this.data[address];
      const idxKeyBucket = currentBucket.findIndex(([lKey]) => lKey === key);

      if (idxKeyBucket !== -1) {
        const itemDeleted = currentBucket.splice(idxKeyBucket, 1);
        return itemDeleted[0];
      }
    }

    return undefined;
  }
}

🦦

  delete(key) {
    let currentHash = this.hashMethod(key);
    if (this.data[currentHash]) {
      for (let i = 0; i < this.data[currentHash].length; i++) {
        if (this.data[currentHash][i][0] === key) {
          let deleted = this.data[currentHash][i];
          delete this.data[currentHash][i];
          this.data[currentHash][i] = this.data[currentHash][i + 1];
          delete this.data[currentHash][i + 1];
          return deleted;
        }
      }
    } return undefined;
  }

Casi lo logro, solo que al final no se de donde salio la funcion .splice creo que es algo queno hemos visto hasta ahora en JS o al menos no lo recuerdo. Pero al menos me siento contento de que casi lo logro.

Mi solución aprovechandome de los metodos de los arrays jejeje

delete(key) {
    const address = this.hashMethod(key);
    const current = this.data[address];
    if (!current) return undefined;
    if (current.length === 1) {
      const item = this.data[address][0];
      delete this.data[address];
      return item;
    }

    const index = current.findIndex((bucket) => bucket[0] === key);
    const item = current[index];
    for (let i = index; i < current.length - 1; i++) {
      current[i] = current[i + 1];
    }
    current.pop();
    return item;
  }

Mi solucion… Un pequeño cambio en el metodo get

delete(key){
    // Tu código aquí 👈
    const address = this.hashMethod(key);
    const currentBucket = this.data[address];
    if (currentBucket) {
      for (let i = 0; i < currentBucket.length; i++) {
        if (currentBucket[i][0] === key) {
          const deletedItem = currentBucket[i]
          currentBucket.splice(i, 1);

          return deletedItem;
        }
      }
    }

Realmente no entiendo porque ponen este tipo de ejercicios sin antes explicar las propiedades.
Como esperan que los que recien van empezando vayan a la documentación especificamente por una propiedad si ni siquiera saben de su existencia…
No es como que todos tengamos todo el tiempo del mundo para leer la documentacion completa 😦(

undefined