Mencionar que mi código funcionaba perfecto en la vista, pero no podía pasar la ultima prueba: "should assign a bed with the correct number after delete other patient"
ya que esta prueba esperaba que la lista de camas se "desordenara", es decir, mi código mantenía la 'singly linked list' ordenada por numero de cama como 1,2 3, (manera ascendente) independientemente si se agregaban o quitaban pacientes.
Así que para cumplir con esa validación (que para mi punto de vista está de más) tuve que agregar un método '_updateOrder()' y una propiedad llamada 'order', para poder hacer un sort y entregar la lista con el numero de camas ordenadas como la prueba lo esperada (2,3,1) donde la 1 fue la ultima que cambió de paciente.... anyway, here my code:
Si tenemos solamente 3 camas y las camas están ocupadas, solamente podremos asignar una nueva cuando alguna de las 3 se desocupe. PERO, cada cama es única por lo que sí se libera la cama 2, la cama 1 y 3 deben seguir ocupadas (para que mover a los pobres pacientes de camas). Entonces, debemos de asignar a el próximo paciente la cama 2 y se empieza a cambiar el orden, de empezar con: 1,2,3 ahora tenemos 1,3,2 dependiendo como se vayan recuperando los pacientes hehe
import{Node}from"./Node";exportclassPatientList{constructor(beds){this.head=null;this.tail=null;this.bedsAvailable=Array.from({length: beds });for(let i =0; i < beds; i++){this.bedsAvailable[i]= i +1;}}addPatient(name, age){if(this.bedsAvailable.length===0){thrownewError("No hay camas disponibles");}const newPatient =newNode(name, age,this.bedsAvailable[0]);this.bedsAvailable.shift();if(!this.head){this.head= newPatient;this.tail= newPatient;}else{this.tail.next= newPatient;this.tail= newPatient;}}removePatient(name){if(!this.head){thrownewError("Paciente no encontrado");}let current =this.head;let prev =null;while(current){if(current.name=== name){if(!prev){this.head= current.next;}else{ prev.next= current.next;}this.bedsAvailable.push(current.bedNumber);return;} prev = current; current = current.next;}thrownewError("Paciente no encontrado");}getPatient(name){let current =this.head;while(current){if(current.name=== name){return{name: current.name,age: current.age,bedNumber: current.bedNumber,};} current = current.next;}thrownewError("Paciente no encontrado");}getPatientList(){const patients =[];let current =this.head;while(current){ patients.push({name: current.name,age: current.age,bedNumber: current.bedNumber,}); current = current.next;}return patients;}getAvailableBeds(){returnthis.bedsAvailable.length;}}
Aqui esta mi solución. Este tema de singly linked list es un poco abstracto pero creo que llegué a una solución sencilla de entender:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Node.js
exportclassNode{constructor(name, age, bedNumber){// Tu código aquí 👈🏻this.name= name;this.age= age;this.bedNumber= bedNumber;this.next=null;}}
exercise.js
import{Node}from"./Node";exportclassPatientList{constructor(beds){// Tu código aquí 👈🏻this.head=null;this.tail=null;this.length=0;this.beds=newArray();for(let i =1; i <= beds; i++){this.beds.push(i);}}addPatient(name, age){// Tu código aquí 👈🏻if(this.beds.length===0)thrownewError("No hay camas disponibles");const newPatient =newNode(name, age,this.beds[0]);this.beds.shift();if(!this.head){this.head= newPatient;this.tail= newPatient;}else{this.tail.next= newPatient;this.tail= newPatient;}this.length++;}removePatient(name){// Tu código aquí 👈🏻if(!this.head)thrownewError("Paciente no encontrado");if(this.head.name=== name){this.beds.push(this.head.bedNumber);this.head=this.head.next;this.length--;return;}let currentNode =this.head;while(currentNode.next){if(currentNode.next.name=== name){this.beds.push(currentNode.next.bedNumber); currentNode.next= currentNode.next.next;this.length--;return;} currentNode = currentNode.next;}thrownewError("Paciente no encontrado");}getPatient(name){// Tu código aquí 👈🏻if(!this.head)thrownewError("Paciente no encontrado");let currentNode =this.head;while(currentNode){if(currentNode.name=== name){return{name: currentNode.name,age: currentNode.age,bedNumber: currentNode.bedNumber}} currentNode = currentNode.next;}thrownewError("Paciente no encontrado");}getPatientList(){// Tu código aquí 👈🏻const list =newArray();let currentNode =this.head;while(currentNode){ list.push({name: currentNode.name,age: currentNode.age,bedNumber: currentNode.bedNumber}) currentNode = currentNode.next;}return list;}getAvailableBeds(){// Tu código aquí 👈🏻returnthis.beds.length;}}
Mi aporte 🧐
exportclassNode{constructor(name, age, bedNumber){this.name= name
this.age= age
this.bedNumber= bedNumber
this.next=null}}
Pues yo tengo mi solución aunque mi lista nunca se desordena y asigna al paciente a la prime cama disponible de la lista y nunca la desordena, porque así como no se pueden mover los pacientes de camas, las camas tampoco deberías de moverlas de sus lugares, creo que es mas lógico
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
exercise.js
import{Node}from"./Node";exportclassPatientList{constructor(beds){// Tu código aquí 👈🏻this.beds= beds;this.firstBed=null;this.lastBed=null;for(let i =1; i <=this.beds; i++){const newBed =newNode('',0, i);if(!this.firstBed){this.firstBed= newBed;this.lastBed= newBed;}else{this.lastBed.next= newBed;this.lastBed= newBed;}}}addPatient(name, age){// Tu código aquí 👈🏻let cNode =this.firstBed;for(let i =1; i <=this.beds; i++){if(cNode.available){ cNode.name= name; cNode.age= age; cNode.available=false;return;} cNode = cNode.next;}thrownewError('No hay camas disponibles');}removePatient(name){// Tu código aquí 👈🏻let cNode =this.firstBed;for(let i =1; i <=this.beds; i++){if(cNode.name=== name){ cNode.name=''; cNode.age=0; cNode.available=true;return;} cNode = cNode.next;}thrownewError('Paciente no encontrado');}getPatient(name){// Tu código aquí 👈🏻let cNode =this.firstBed;for(let i =1; i <=this.beds; i++){if(cNode.name=== name){const{ name, age, bedNumber }= cNode;return{ name, age, bedNumber };} cNode = cNode.next;}thrownewError('Paciente no encontrado');}getPatientList(){// Tu código aquí 👈🏻let listPatients =[]let cNode =this.firstBed;for(let i =1; i <=this.beds; i++){if(!cNode.available){const{ name, age, bedNumber }= cNode; listPatients.push({ name, age, bedNumber })} cNode = cNode.next;}return listPatients;}getAvailableBeds(){// Tu código aquí 👈🏻let bedsAvailable =0;let cNode =this.firstBed;for(let i =1; i <=this.beds; i++){if(cNode.available){ bedsAvailable++;} cNode = cNode.next;}return bedsAvailable;}}
node.js
exportclassNode{constructor(name, age, bedNumber){// Tu código aquí 👈🏻this.name= name;this.age= age;this.bedNumber= bedNumber;this.available=true;this.next=null;}}
import{Node}from"./Node";exportclassPatientList{constructor(beds){this.head=null;this.tail=null;this.length=0;this.beds=newArray(beds).fill("available");}addPatient(name, age){if(this.getAvailableBeds()===0)thrownewError("No hay camas disponibles");const index =this.beds.indexOf("available");this.beds[index]="notAvailable";const newNode =newNode(name, age, index +1);if(!this.head){this.head= newNode;this.tail= newNode;}else{this.tail.next= newNode;this.tail= newNode;}this.length++;}removePatient(name){if(!this.head){returnnull;}if(this.head.name=== name){this.beds[0]="available";this.head=this.head.next;this.length--;return;}let currentNode =this.head;while(currentNode.next){if(currentNode.next.name=== name){this.beds[currentNode.bedNumber-1]="available"; currentNode.next= currentNode.next.next;this.length--;return;} currentNode = currentNode.next;}thrownewError("Paciente no encontrado");}getPatient(name){let currentNode =this.head;while(currentNode){if(currentNode.name=== name){return{name: currentNode.name,age: currentNode.age,bedNumber: currentNode.bedNumber};} currentNode = currentNode.next;}thrownewError("Paciente no encontrado");}getPatientList(){const values =[];let currentNode =this.head;for(let i =0; i <this.length; i++){ values.push({name: currentNode.name,age: currentNode.age,bedNumber: currentNode.bedNumber}); currentNode = currentNode.next;}return values;}getAvailableBeds(){returnthis.beds.reduce((acum, bed)=>{if(bed ==="available") acum++;return acum;},0);}}
Solución… 😄
.
Siento que me compliqué demasiado 😅.. fue muy entretenido el reto.
.
No entendí bien el "agrega un nuevo paciente a la lista, asignándole la próxima cama disponible". Hice una lista ordenada de camas donde marcaba las camas como disponible y no disponible, y asignaba el paciente a la primera cama disponible.
.
Adjunto la solución del playground y la lista anteriormente mencionada que me parece una mejora interesante del reto.
.
.
Node.js:
exportclassNode{constructor(name, age, bedNumber){this.name= name
this.age= age
this.bedNumber= bedNumber
this.next=null}}
.
exercise.js:
import{Node}from"./Node";exportclassPatientList{constructor(beds){this.head=null;this.tail=null;this.availableBeds=Array.from({length: beds },(_, i)=> i +1);}addPatient(name, age){if(this.availableBeds.length===0){thrownewError("No hay camas disponibles");}const newPatient =newNode( name, age,this.availableBeds[0]);this.availableBeds.shift();if(!this.head){this.head= newPatient;this.tail= newPatient;}this.tail.next= newPatient;this.tail= newPatient;}removePatient(name){if(!this.head){thrownewError("Paciente no encontrado");}let actual =this.head;let previous =null;while(actual){if(actual.name=== name){if(!previous){this.head= actual.next;}else{ previous.next= actual.next;}this.availableBeds.push(actual.bedNumber);return;} previous = actual; actual = actual.next;}thrownewError("Paciente no encontrado");}getPatient(name){let actual =this.head;while(actual){if(actual.name=== name){return{name: actual.name,age: actual.age,bedNumber: actual.bedNumber,};} actual = actual.next;}thrownewError("Paciente no encontrado");}getPatientList(){const patients =[];let actual =this.head;while(actual){ patients.push({name: actual.name,age: actual.age,bedNumber: actual.bedNumber,}); actual = actual.next;}return patients;}getAvailableBeds(){returnthis.availableBeds.length;}}
.
Lista mejorada:
import{Node}from"./Node";exportclassPatientList{constructor(beds){this.beds= beds;this.head=null;this.tail=null;this.length=0;this.bedList=this.initBeds();this.nextAvailableBed=this.findAvailableBed();}initBeds(){let allBeds =[];for(let i =1; i <=this.beds; i++){ allBeds.push({number: i,available:true});}return allBeds;}findAvailableBed(){returnthis.bedList.find(bed=> bed.available)?.number ||undefined;}markBed(){this.bedList.forEach(bed=>{if(bed.number===this.nextAvailableBed){ bed.available=false;}});this.length++;this.nextAvailableBed=this.findAvailableBed();}unmarkBed(num){this.bedList.forEach(bed=>{if(bed.number=== num){ bed.available=true;}});this.length--;this.nextAvailableBed=this.findAvailableBed();}addPatient(name, age){if(!this.nextAvailableBed){thrownewError("No hay camas disponibles");}let newPatient =newNode( name, age,this.nextAvailableBed);if(!this.head){this.head= newPatient;this.tail= newPatient;this.markBed();returnthis;}let actual =this.head;while(actual.next){if(actual.next.bedNumber>this.nextAvailableBed){ newPatient.next= actual.next; actual.next= newPatient;this.markBed();returnthis;} actual = actual.next;} actual.next= newPatient;this.tail= actual.next;this.markBed();}removePatient(name){if(!this.head){returnnull;}if(this.head.name=== name){this.unmarkBed(this.head.bedNumber)this.head=this.head.next;returnthis;}let actual =this.head;while(actual.next){if(actual.next.name=== name){if(!actual.next.next){this.unmarkBed(actual.next.bedNumber);this.tail= actual; actual.next=null;returnthis;}this.unmarkBed(actual.next.bedNumber); actual.next= actual.next.next;returnthis;} actual = actual.next;}thrownewError("Paciente no encontrado");}getPatient(name){let actual =this.head;while(actual){if(actual.name=== name){return{name: actual.name,age: actual.age,bedNumber: actual.bedNumber};} actual = actual.next;}thrownewError("Paciente no encontrado");}getPatientList(){let actual =this.head;let list =[];while(actual){ list.push({name: actual.name,age: actual.age,bedNumber: actual.bedNumber}); actual = actual.next;}return list;}getAvailableBeds(){returnthis.bedList.filter(bed=> bed.available).length;}}
Es un ejercicio muy bueno, y su estructura de datos se puede usar en muchos casos diferentes como "gestionar datos de un usuario" .
Dejo mi Solucion con muchos detalles ya que lo uso para repasar lo basico :
.
.
.
.
.
.
.
.
.
.
.
.
.
.
//Node.jsexportclassNode{constructor(name, age, bedNumber){this.name= name
this.age= age
this.bedNumber= bedNumber
this.next=null}}
//exercise.jsimport{Node}from"./Node";exportclassPatientList{constructor(beds){this.head=nullthis.tail=nullthis.beds=Array(beds).fill(true)this.length=0}addPatient(name, age){//verifica si hay camas disponibles en el hospital//this.beds para obtener una Arr de camas ocupadas y luego verificar su longitudif(this.beds.filter(bed=> bed).length===0){thrownewError("No hay camas disponibles")}//Si hay camas disponibles//encuentra el índice de la primera cama disponible utilizando el método findIndexconst availableBed =this.beds.findIndex(bed=> bed)//Luego, marca esa cama como ocupadathis.beds[availableBed]=false//nuevo objeto Node que representa al paciente con el nombre, la edad y el número de cama proporcionadosconst newPatient =newNode(name, age, availableBed +1)//Si la cola de pacientes está vacía, la cabeza y la cola auntan al mismo pacienteif(!this.tail){this.head= newPatient
this.tail= newPatient
}else{//De lo contrario, se agrega el nuevo paciente al final de la cola y se actualiza el puntero de la colathis.tail.next= newPatient
this.tail= newPatient
}this.length++}removePatient(name){//si la lista de pacientes está vacíaif(!this.head){returnnull;}//Si es el primer paciente en la listaif(this.head.name=== name){//se elimina de la lista actualizando el puntero de la cabeza al siguiente paciente en la listathis.head=this.head.next;//se libera la cama ocupadathis.beds[0]=true//actualisamosthis.length--;return;}//posicionamos el puntero, en el primer elemento de la lista let currentPatient =this.head;//Si el primer paciente no tiene el mismo nombre que el proporcionado, la función recorre la lista de pacienteswhile(currentPatient.next){//Si encuentra un paciente con el mismo nombre, lo eliminaif(currentPatient.next.name=== name){//desocupo la camathis.beds[currentPatient.bedNumber-1]=true//acomodo el siguiente puntero currentPatient.next= currentPatient.next.next;this.length--;return;}//si no entra al IF, apunto al siguiente pasicnete, para compara nombres currentPatient = currentPatient.next;}//si no se encuentra en toda la lista sale el errorthrownewError("Paciente no encontrado")}getPatient(name){let currentPatient =this.head;//recorre la lista de pacientes,mientras que el siguiente no sea nullwhile(currentPatient.next){//Si encuentra un paciente con el mismo nombre, devuelve un objetoif(currentPatient.name=== name){return{name: currentPatient.name,age: currentPatient.age,bedNumber: currentPatient.bedNumber}}//apunto al siguiente, para seguir recorrientod toda la lista, con el While currentPatient = currentPatient.next;}//si no encuentra el nombre, sale errorthrownewError("Paciente no encontrado")}getPatientList(){//en este Arr, voy a poner los pacienteslet array =[]//apunto al primere paciente para recorre toda la listalet currentPatient =this.head//recorre la lista de pacientes,mientras que no sea nullwhile(currentPatient){//Para cada paciente en la lista, agrega un objeto en el Arr array.push({name: currentPatient.name,age: currentPatient.age,bedNumber: currentPatient.bedNumber})//apunto al siguiente, para seguir recorrientod toda la lista, con el While currentPatient = currentPatient.next;}return array
}getAvailableBeds(){//método filter en el Arr "this.beds" para obtener un Arr de camas disponiblereturnthis.beds.filter(value=> value).length}}
Mi solución:
.
.
.
.
.
.
.
.
Node.js
exportclassNode{constructor(name, age, bedNumber){this.name= name
this.age= age
this.bedNumber= bedNumber
this.next=null}}
exportclassPatientList{constructor(beds){this.head=null;this.tail=null;this.beds= beds;this.availableBeds= beds;}addPatient(name, age){if(this.availableBeds<=0){thrownewError("No hay camas disponibles");}const patient ={ name, age,bedNumber:this.beds-this.availableBeds+1,};const node =newNode(patient);if(!this.head){this.head= node;this.tail= node;}else{this.tail.next= node;this.tail= node;}this.availableBeds--;}removePatient(name){let current =this.head;let prev =null;while(current){if(current.data.name=== name){if(!prev){// si es el primer nodothis.head= current.next;if(!this.head){// si era el último nodothis.tail=null;}}else{ prev.next= current.next;if(!current.next){// si era el último nodothis.tail= prev;}}this.availableBeds++;return;} prev = current; current = current.next;}thrownewError("Paciente no encontrado");}getPatient(name){let current =this.head;while(current){if(current.data.name=== name){return current.data;} current = current.next;}thrownewError("Paciente no encontrado");}getPatientList(){const list =[];let current =this.head;while(current){ list.push(current.data); current = current.next;}return list;}getAvailableBeds(){returnthis.availableBeds;}}
Hola, dejo mi solución,
.
.
.
.
.
.
.
.
.
.
.
Solo tengo un detallito, me regresa el error Should throw error if patient not found aunque si estoy regresando el mensaje de error, alguno de ustedes visualiza ¿que es lo que tengo mal al momento de enviar el error de paciente no encontrado?
Muchas gracias de antemano por su ayuda 🌸✨💻
exportclassNode{constructor(name, age, bedNumber){// Tu código aquí 👈🏻this.name= name;this.age= age;this.bedNumber= bedNumber;this.next=null;}}exportclassPatientList{constructor(beds){// Tu código aquí 👈🏻this.beds = beds;this.head=null;this.tail=null;this.length=0;this.availableBeds= beds;this.availableBedsArray=[];for(let i =1; i <= beds; i++){this.availableBedsArray.push(i);}}addPatient(name, age){// Tu código aquí 👈🏻if(this.availableBedsArray.length===0){thrownewError(`No hay camas disponibles`)};const newNode =newNode(name, age,this.availableBedsArray[0]);this.availableBedsArray.shift();if(!this.head){this.head= newNode;this.tail= newNode;}else{this.tail.next= newNode;this.tail= newNode;}this.length++;this.availableBeds--;}removePatient(name){// Tu código aquí 👈🏻if(this.head===null){thrownewError("Paciente no encontrado");}if(this.head.name=== name){this.availableBedsArray.push(this.head.bedNumber);this.head=this.head.next;this.length--;this.availableBeds--;return;}let currentNode =this.head;while(currentNode.next){if(currentNode.next.name=== name){this.availableBedsArray.push(this.head.bedNumber); currentNode.next= currentNode.next.next;this.length--;this.availableBeds--;return;} currentNode = currentNode.next;}if(this.head===null){thrownewError("Paciente no encontrado");}}getPatient(name){if(this.head===null){thrownewError("Paciente no encontrado");}// Tu código aquí 👈🏻let currentNode =this.head;let findPatient =false;for(let i =0; i <this.length; i++){if(i ===0&& currentNode?.name === name){ findPatient =true;return{name: currentNode.name,age: currentNode.age,bedNumber: currentNode.bedNumber,};}else{ currentNode = currentNode.next;if(currentNode?.name === name){ findPatient =true;return{name: currentNode.name,age: currentNode.age,bedNumber: currentNode.bedNumber,};}}}if(!findPatient){thrownewError("Paciente no encontrado")}returnnull;}getPatientList(){// Tu código aquí 👈🏻let currentNode =this.head;let currentNodeArray =[];for(let i =0; i <this.length; i++){if(i ===0){ currentNodeArray.push({name: currentNode.name,age: currentNode.age,bedNumber: currentNode.bedNumber,});}else{ currentNode = currentNode.next; currentNodeArray.push({name: currentNode.name,age: currentNode.age,bedNumber: currentNode.bedNumber,})}}return currentNodeArray;}getAvailableBeds(){// Tu código aquí 👈🏻returnthis.availableBedsArray.length;}}
Que lio me estaba armando con el control del array de numeros de habitacion por poner la restauracion de la habitacion que queda libre en orden incorrecto xDDDD
Creo que ahora si.
,
,
,
,
,
,
,
,
,
,
,
,
,
,
import{Node}from"./Node";exportclassPatientList{constructor(totalBeds){this.head=null;this.totalBeds= totalBeds;this.bedsAvailable=[];for(let i =1; i <=this.totalBeds; i++){this.bedsAvailable.push(i);}this.nextBedNumber=1;}addPatient(name, age){if(this.totalBeds===0){thrownewError("No hay camas disponibles");}this.bedsAvailable.sort();const newPatient ={ name, age,bedNumber:this.bedsAvailable[0],next:null,};this.bedsAvailable.shift();if(this.head===null){this.head= newPatient;}else{let current =this.head;while(current.next!==null){ current = current.next;} current.next= newPatient;}this.nextBedNumber++;this.totalBeds--;}removePatient(name){if(this.head===null){thrownewError("Paciente no encontrado");}if(this.head.name=== name){this.totalBeds++;this.bedsAvailable.push(this.head.bedNumber);this.head=this.head.next;return;}let previous =this.head;let current =this.head.next;while(current !==null){if(current.name=== name){this.totalBeds++; previous.next= current.next;return;} previous = current; current = current.next;}thrownewError("Paciente no encontrado");}getPatient(name){let current =this.head;while(current !==null){if(current.name=== name){return{name: current.name,age: current.age,bedNumber: current.bedNumber,};} current = current.next;}thrownewError("Paciente no encontrado");}getPatientList(){const patientList =[];let current =this.head;while(current !==null){ patientList.push({name: current.name,age: current.age,bedNumber: current.bedNumber,}); current = current.next;}return patientList;}getAvailableBeds(){returnthis.totalBeds;}}