Ageing the Population…

Given an object of people and their ages, return how old the people would be after n years have passed. Use the absolute value of n.

Examples

afterNYears({
  "Joel" : 32,
  "Fred" : 44,
  "Reginald" : 65,
  "Susan" : 33,
  "Julian" : 13
}, 1) ➞ {
  "Joel" : 33,
  "Fred" : 45,
  "Reginald" : 66,
  "Susan" : 34,
  "Julian" : 14
}

afterNYears({
  "Baby" : 2,
  "Child" : 8,
  "Teenager" : 15,
  "Adult" : 25,
  "Elderly" : 71
}, 19) ➞ {
  "Baby" : 21,
  "Child" : 27,
  "Teenager" : 34,
  "Adult" : 44,
  "Elderly" : 90
}

afterNYears({
  "Genie" : 1000,
  "Joe" : 40
}, 5) ➞ {
  "Genie" : 1005,
  "Joe" : 45
}

Notes

  • Assume that everyone is immortal (it would be a bit grim if I told you to remove names once they reached 75).
  • n should be a positive number because last time I checked, people don’t tend to age backwards. Therefore, use the absolute value of n.

Solution:

function afterNYears(names, n) {
  for (key of Object.keys(names)) {
    names[key] += Math.abs(n);
  }
  return names;
}

 

The Million Dollar Fence

Edabit

Your task is to create a fence worth $1 million. You are given the price of the material (per character), meaning the length of the fence will change depending on the cost of the material.

Create a function which constructs this pricey pricey fence, using the letter "H" to build.

constructFence("$50,000") ➞ "HHHHHHHHHHHHHHHHHHHHHHHHHHHH"
// 20 fence posts were set up ($1,000,000 / $50,000 = 20)

Examples

constructFence("$50,000") ➞ "HHHHHHHHHHHHHHHHHHHHHHHHHHHH"

constructFence("$100,000") ➞ "HHHHHHHHHH"

constructFence("$1,000,000") ➞ "H"

Notes

You are ordered to spend all of your $1,000,000 budget…

Solution:

function constructFence(price) {
  let fenceCount = 1000000 / Number(price.replace(/[^0-9]/g, ""));
  return "H".repeat(fenceCount);
}

 

Ping Pong!

Edabit

A game of table tennis almost always sounds like Ping! followed by Pong! Therefore, you know that Player 2 has won if you hear Pong! as the last sound (since Player 1 didn’t return the ball back).

Given an array of Ping!, create a function that inserts Pong! in between each element. Also:

  • If win equals true, end the list with Pong!.
  • If win equals false, end with Ping! instead.

Examples

pingPong(["Ping!"], true) ➞ ["Ping!", "Pong!"]

pingPong(["Ping!", "Ping!"], false) ➞ ["Ping!", "Pong!", "Ping!"]

pingPong(["Ping!", "Ping!", "Ping!"], true) ➞ ["Ping!", "Pong!", "Ping!", "Pong!", "Ping!", "Pong!"]

Notes

  • You will always return the ball (i.e. the Pongs are yours).
  • Player 1 serves the ball and makes Ping!.
  • Return an array of strings.

Solution:

function pingPong(arr, win) {
  let len = win ? arr.length * 2 : arr.length * 2 - 1;
  let sol = [];
  for (let i = 0; i <len; i++) {
    if (i % 2 === 0) {
      sol.push("Ping!");
    } else {
      sol.push("Pong!");
    }
  }
  return sol;
}

 

Binary Search (Firecode.io)

Write a method that searches an Array of integers for a given integer using the
Binary Search Algorithm. If the input integer is found in the array, return true. Otherwise, return false.
You can assume that the given array of integers is already sorted
in ascending order.
Examples:

binarySearch({2,5,7,8,9},9) -> true

binarySearch({2,8,9,12},6) -> false

binarySearch({2},4) -> false

binarySearch({},9) -> false

   {} -> [Empty] Array

Solution:

function binarySearch(arr, n){
  let left = 0, right = arr.length-1;
  let mid = Math.round((left+right)/2);
  
  while(l<=r){
      if(arr[mid] ==n ||arr[left] ==n ||arr[right] ==n ){
          return true;
      }
    if(arr[mid]<n)
        left = mid+1;
    else
        right = mid-1;
    mid = Math.round((left+right)/2);
  }
  
  return false;
}

 

The Sweetest Ice Cream

Edabit

Create a function which takes an array of instances from the class IceCream and returns the sweetness value of the sweetest icecream.

Sweetness is calculated from the flavor and number of sprinkles. Each sprinkle has a sweetness value of 1, and the sweetness values for the flavors are as follows:

Flavours Sweetness Value
Plain 0
Vanilla 5
ChocolateChip 5
Strawberry 10
Chocolate 10
  • You’ll be given instance properties in the order flavornumSprinkles.

Examples

ice1 = IceCream('Chocolate', 13)         // value of 23
ice2 = IceCream('Vanilla', 0)           // value of 5
ice3 = IceCream('Strawberry', 7)        // value of 17
ice4 = IceCream('Plain', 18)             // value of 18
ice5 = IceCream('ChocolateChip', 3)      // value of 8

sweetestIcecream([ice1, ice2, ice3, ice4, ice5]) ➞ 23

sweetestIcecream([ice3, ice1]) ➞ 23

sweetestIcecream([ice3, ice5]) ➞ 17

Notes

Remember to only return the sweetness value.

Solution:

function sweetestIcecream(arr) {
  const sweetnessValue = {
    Plain: 0,
    Vanilla: 5,
    ChocolateChip: 5,
    Strawberry: 10,
    Chocolate: 10
  };
  let maxSweet = 0;
  for (item of arr) {
    const { flavor, numSprinkles } = item;
    console.log(sweetnessValue[flavor] + numSprinkles);
    if (sweetnessValue[flavor] + numSprinkles > maxSweet) {
      maxSweet = sweetnessValue[flavor] + numSprinkles;
    }
  }
  return maxSweet;
}

 

Recursion: Fibonacci Numbers

Edabit

Fibonacci numbers are created in the following way:

F(0) = 0
F(1) = 1
...
F(n) = F(n-2) + F(n-1)

Write a function that calculates the nth Fibonacci number.

Examples

fib(0) ➞ 0

fib(1) ➞ 1

fib(2) ➞ 1

fib(8) ➞ 21

Note: We need to solve it with recursion but TBH I am so bad at recursion that I avoided using it 🤷‍♂️

I mean it works so why not 🤭

Solution:

function fib(n) {
  let fibNum = [0, 1, 1, 2, 3, 5, 8, 13, 21];
  if (fibNum[n] != undefined) {
    return fibNum[n];
  }
  while (fibNum.length <= n) {
    let len = fibNum.length;
    fibNum.push(fibNum[len - 2] + fibNum[len - 1]);
  }
  return fibNum[n];
}

 

Malthusian Catastrophe

Edabit

A man named Thomas Malthus described what is now called a Malthusian Catastrophe. According to him, food production grows by a fixed amount, but population grows by a percentage. So, the food supply would soon be insufficient for the population.

Your job is to find out when that will occur. For this challenge, assume 1 population needs 1 unit of food production. Food production & population both start at 100. The year starts at 0.

The catastrophe happens when the population is larger than food production.

The function will pass: foodGrowth – an integer – Food production increase per year; and popMult – a floating-point number – The population growth multiplier per year.

Examples

malthusian(4255, 1.41) ➞ 20;
// { foodProd: 85,200, pop: 96,467.77..., year: 20 }

malthusian(9433, 1.09) ➞ 107;
// { foodProd: 1,009,431, pop: 1,010,730.28..., year: 107 }

malthusian(5879, 1.77) ➞ 12;
// { foodProd: 70,648, pop: 94,553.84..., year: 12 }

Notes

Return the year that the overtake happens, not the next year.

Make sure you don’t make the mistake of adding a year, then calculating the changes to food & population. That way, you miss year 0.

If the population & food production are equal, that is not a catastrophe.

Solution:

function malthusian(foodGrowth, popMult) {
  let food = 100,
    pop = 100,
    year = 0;
  while (food >= pop) {
    food += foodGrowth;
    pop *= popMult;
    year++;
  }
  return year;
}

 

Game of Thrones: Character Titles

Edabit

Write a function that takes a string and returns a string with the correct case for character titles in the Game of Thrones series.

  • The words andtheof and in should be lowercase.
  • All other words should have the first character as uppercase and the rest lowercase.

Examples

correctTitle("jOn SnoW, kINg IN thE noRth.")
➞ "Jon Snow, King in the North."

correctTitle("sansa stark, lady of winterfell.")
➞ "Sansa Stark, Lady of Winterfell."

correctTitle("TYRION LANNISTER, HAND OF THE QUEEN.")
➞ "Tyrion Lannister, Hand of the Queen."

Notes

  • Punctuation and spaces must remain in their original positions.
  • Hyphenated words are considered separate words.
  • Be careful with words that contain andtheof or in.
  • See the Resources tab for more info on the various JavaScript string methods.

Solution:

function correctTitle(str) {
  str = str.toLowerCase();
  str = str
    .split(" ")
    .map(word =>
      ["and", "the", "of", "in"].includes(word)
        ? word
        : word[0].toUpperCase() + word.slice(1)
    )
    .join(" ");
  return str
    .split("-")
    .map(word =>
      ["and", "the", "of", "in"].includes(word)
        ? word
        : word[0].toUpperCase() + word.slice(1)
    )
    .join("-");
}

 

Sort by Factor Length

Edabit

A numbers factor length is simply its total number of factors.

For instance:

3: 1, 3
// 3's factor length = 2

8: 1, 2, 4, 8
// 8's factor length = 4

36 : 1, 2, 3, 4, 6, 9, 12, 18, 36
// 36's factor length = 9

Create a function that sorts an array by factor length in descending order. If multiple numbers have the same factor length, sort these numbers in descending order, with the largest first.

In the example below, since 13 and 7 both have only 2 factors, we put 13 ahead of 7.

factorSort([9, 7, 13, 12]) ➞ [12, 9, 13, 7]
// 12 : 6, 9: 3, 13: 2, 7: 2

Examples

factorSort([1, 2, 31, 4]) ➞ [4, 31, 2, 1]

factorSort([5, 7, 9]) ➞ [9, 7, 5]

factorSort([15, 8, 2, 3]) ➞ [15, 8, 3, 2]

Notes

Descending order: numbers with a higher factor length go before numbers with a lower factor length.

Solution:

function factorSort(nums) {
  let numFactObj = {};
  for (num of nums) {
    numFactObj[num] = 0;
    for (let i = 1; i <= num; i++) {
      if (num % i === 0) {
        numFactObj[num] += 1;
      }
    }
  }
  let tempObj = [];
  for (key of Object.keys(numFactObj)) {
    tempObj.push({ num: key, freq: numFactObj[key] });
  }
  let sortedObj = tempObj.sort((a, b) => b.freq - a.freq);
  let finalSol = [];
  let set = new Set();
  for (item of sortedObj) {
    set.add(item.freq);
  }

  for (item of set) {
    // console.log(
    //   tempObj
    //     .filter(obj => obj.freq === item)
    //     .map(obj => Number(obj.num))
    //     .sort((a, b) => b - a)
    // );
    finalSol = finalSol.concat(
      tempObj
        .filter(obj => obj.freq === item)
        .map(obj => Number(obj.num))
        .sort((a, b) => b - a)
    );
  }

  return finalSol;
}

 

The Frugal Gentleman

Edabit

Atticus has been invited to a dinner party, and he decides to purchase a bottle of wine. However, he has little knowledge of how to choose a good bottle. Being a very frugal gentleman (yet disliking looking like a cheapskate), he decides to use a very simple rule. In any selection of two or more wines, he will always buy the second-cheapest.

Given an array of wine objects, write a function that returns the name of the wine he will buy for the party. If given an empty array, return null. If given an array of only one, Atticus will buy that wine.

Examples

chosenWine([
  { name: "Wine A", price: 8.99 },
  { name: "Wine 32", price: 13.99 },
  { name: "Wine 9", price: 10.99 }
]) ➞ "Wine 9"

chosenWine([{ name: "Wine A", price: 8.99 }]) ➞ "Wine A"

chosenWine([]) ➞ null

Notes

All wines will be different prices, so there is no confusion in the ordering.

Solution:

function chosenWine(wines) {
  if (wines.length === 0) return null;
  if (wines.length === 1) return wines[0].name;
  return wines.sort((a, b) => a.price - b.price)[1].name;
}