SHARE
TWEET

js

tereshchenko_art Feb 17th, 2020 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function removePersonByName(personsArray, name) {
  2.   return personsArray.filter((person) => person.name !== name);
  3. }
  4.  
  5. function findNeighbour(person, restOfPersons) {
  6.   const { close } = person;
  7.   close.sort();
  8.  
  9.   for (let i = 0; i < close.length; i++) {
  10.     const key = close[i]; // We can use first element as a key since we
  11.     // sort array of string alphabetically
  12.     const closestPerson = restOfPersons.find(((p) => p.name === key));
  13.  
  14.     if (closestPerson) {
  15.       return closestPerson;
  16.     }
  17.   }
  18.  
  19.   return false; // return first element if there is no closes left
  20. }
  21.  
  22. function placeGuests(arr) {
  23.   const result = [];
  24.   let restOfPeople = [...arr]; // Clone an array in order to not mutate input
  25.   let currentElement = arr[0];
  26.  
  27.  
  28.   for (let i = 0; i < arr.length; i++) {
  29.     if (i === 0) {
  30.       // We know that array is sorted by name so we have to skip the first step and pop ;
  31.       restOfPeople = removePersonByName(restOfPeople, currentElement.name);
  32.  
  33.       result.push(currentElement);
  34.       currentElement = arr[1]; // forcibly run algorithm top a next step
  35.     }
  36.  
  37.     const closest = findNeighbour(currentElement, restOfPeople);
  38.     if (closest) {
  39.       result.push(closest);
  40.       restOfPeople = removePersonByName(restOfPeople, closest.name);
  41.       currentElement = closest;
  42.     }
  43.   }
  44.  
  45.   return result;
  46. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top