Sum of Resistance in Parallel Circuits [Edabit]

Edabit

If two or more resistors are connected in parallel, the overall resistance of the circuit reduces. It is possible to calculate the total resistance of a parallel circuit by using this formula:

1/RTotal = 1/R1 + 1/R2 + 1/R3 ...

Create a function that takes an array of parallel resistance values, and calculates the total resistance of the circuit.

Worked Example

parallelResistance([6, 3, 6]) ➞ 1.5

// 1/RTotal = 1/6 + 1/3 + 1/6
// 1/RTotal = 2/3
// RTotal = 3/2 = 1.5

Examples

parallelResistance([6, 3]) ➞ 2

parallelResistance([10, 20, 10]) ➞ 4

parallelResistance([500, 500, 500]) ➞ 166.6
// Round to the nearest decimal place

Notes

  • Note that you should rearrange to return the Resistance Total, not 1 / Resistance Total.
  • Round to the nearest decimal place.
  • All inputs will be valid.

Solution:

1
2
3
4
5
function parallelResistance(arr) {
  return parseFloat(
    (1 / arr.reduce((acc, curr) => (acc += 1 / curr), 0)).toFixed(1)
  );
}

Calculate an Earned Run Average [Edabit]

Edabit

Create a function that returns an Earned Run Average (ERA). An ERA is calculated by multiplying 9 by the quotient of Earned Runs Allowed er divided by ip Innings Pitched.

In baseball statistics, innings are represented with a fractional part of .1 (1/3) or .2 (2/3) to represent the number of outs in an inning. A whole number or a number with a fractional part of .0 represents a full inning with three outs. Check the Resources tab for a deeper explanation.

Examples

era(22, 99) ➞ 2.00

era(23, 99.1) ➞ 2.08

era(24, 99.2) ➞ 2.17

Notes

  • ERA is represented with a scale of 22.08
  • For 1/3 and 2/3, use a scale of 2.

Solution:

1
2
3
function era(er, ip) {
	return ((er/ip)*9).toFixed(4).substr(0,4);
}

Majority Vote [Edabit]

Edabit

Create a function that returns the majority vote in an array. A majority vote is an element that occurs > N/2 times in an array (where N is the length of the array).

Examples

majorityVote(["A", "A", "B"]) ➞ "A"

majorityVote(["A", "A", "A", "B", "C", "A"]) ➞ "A"

majorityVote(["A", "B", "B", "A", "C", "C"]) ➞ null

Notes

  • The frequency of the majority element must be strictly greater than 1/2.
  • If there is no majority element, return null.
  • If the array is empty, return null.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function majorityVote(arr) {
  let obj = {};
  if (!arr.length) {
    return null;
  }
  let set = new Set(arr);
  if (set.size === 1) {
    return arr[0];
  }
  for (let vote of arr) {
    if (obj[vote]) {
      obj[vote] += 1;
    } else {
      obj[vote] = 1;
    }
  }
  let sol = Object.entries(obj).sort((a, b) => b[1] - a[1]);
  return sol[0][1] == sol[sol.length - 1][1] ? null : sol[0][0];
}

Multiplying Numbers in a String [Edabit]

Edabit

Given a string of numbers separated by a comma and space, return the product of the numbers.

Examples

multiplyNums("2, 3") ➞ 6

multiplyNums("1, 2, 3, 4") ➞ 24

multiplyNums("54, 75, 453, 0") ➞ 0

multiplyNums("10, -2") ➞ -20

Notes

Bonus: Try to complete this challenge in one line!

Solution:

1
2
3
function multiplyNums(nums) {
  return nums.split(",").reduce((acc, curr) => (acc *= parseInt(curr)), 1);
}

Spoonerisms [Edabit]

Edabit

A spoonerism is when the first letters / sounds of two words are transposed onto one another. Create a function that takes a two-word string and performs a spoonerism on the phrase.

Examples

spoonerise("history lecture") ➞ "listory hecture"

spoonerise("loud noises") ➞ "noud loises"

spoonerise("chow mein") ➞ "mow chein"

spoonerise("edabit rules!") ➞ "redabit ules!"

Notes

  • Only two words will be parsed into the function. Don’t worry about handling more than two.
  • You won’t always just have to swap the first letters, take care to notice which letters have been switched in the examples (notice the difference between vowel-starting and consonant-starting words).

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function spoonerise(phrase) {
  let [w1, w2] = phrase.split(" ");
  let i = 0;
  while (!"aeiou".includes(w1[i])) {
    i++;
  }
  let [prew1, postw1] = [w1.substr(0, i), w1.substr(i)];
  i = 0;
  while (!"aeiou".includes(w2[i])) {
    i++;
  }
  let [prew2, postw2] = [w2.substr(0, i), w2.substr(i)];
  return prew2 + postw1 + " " + prew1 + postw2;
}

pigLatin 3.0 [Edabit]

Edabit

Write a function that converts a sentence into pig latin.

Rules for converting to pig latin:

  • For words that begin with a vowel (a, e, i, o, u), add “way”.
  • Otherwise, move all letters before the first vowel to the end and add “ay”.
  • For simplicity, no punctuation will be present in the inputs.

Examples

pigLatinSentence("this is pig latin") ➞ "isthay isway igpay atinlay"

pigLatinSentence("wall street journal") ➞ "allway eetstray ournaljay"

Notes

All letters will be in lowercase.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function pigLatinSentence(sentence) {
  let arr = sentence.split(" ");
  let sol = arr.map((word) => {
    if ("aeiouAEIOU".includes(word[0])) {
      return word + "way";
    } else {
      let i = 0;
      while (!"aeiouAEIOU".includes(word[i])) {
        i++;
      }
      return word.substr(i) + word.substr(0, i) + "ay";
    }
  });
  return sol.join(" ");
}

Making a Box 2.0! [Edabit]

Edabit

This is based on Helen Yu’s Making a Box challenge. This challenge is the same execpt that instead of an array of strings, your function should output a matrix of characters.

Examples

charBox(1) ➞ [
  ["#"]
]

charBox(4) ➞ [
  ["#", "#", "#", "#"],
  ["#", " ", " ", "#"],
  ["#", " ", " ", "#"],
  ["#", "#", "#", "#"]
]

charBox(2) ➞ [
  ["#", "#"],
  ["#", "#"]
]

Notes

As an added bonus, try making charBox(0) output [[]] and make any strings, non-integers, and negative numbers output -1.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function charBox(size) {
  let sol = [];
  if (size == 1) {
    return [["#"]];
  }
  let first = Array.from({ length: size }, () => "#");
  let mid = Array.from({ length: size - 2 }, () => " ");
  mid.unshift("#");
  mid.push("#");
  for (let i = 0; i < size; i++) {
    if (i == 0 || i == size - 1) {
      sol.push(first);
    } else {
      sol.push(mid);
    }
  }
  if (isNaN(parseInt(size)) || size < 0 || Math.round(size) !== size) {
    return -1;
  }
  return size == 0 ? [[]] : sol;
}

Name Count Equality [Edabit]

Edabit

Create a function that counts the embedded names in the string and determines the equality. The names are embedded in a string of mixed special symbols and characters. The names to be counted to are adjoined with the ampersand symbol & and as the second parameter. See the following examples for more details.

Examples

equalCount("Peter!@#$Paul&*#Peter!--@|#$Paul#$Peter@|Paul$%^^Peter++Paul%$%^Peter++Paul#$#$#Peter@|Paul", "Peter&Paul")
➞ {"Peter":6, "Paul": 6, "equality": true}

equalCount("Elliot!@#$Sam!--@|#$Elliot@|Sam++Elliot$%^Elliot@|Sam!@#Elliot!@#$Sam!--@|#$Elliot", "Sam&Elliot")
➞ {"Sam": 4, "Elliot": 6, "equality": false, "difference": 2}
// "difference" key is added to the object if count is not equal.

equalCount("Tim!@#$Kit&&*#Tim!--@|#$Kit#$%Tim@|Kit$%^^Tim++Kit%$%^Tim++Kit#$#$#Tim@|Kit", "Ken&Tom")
➞ {"Ken": 0, "Tom": 0, "equality": true}

Notes

Make sure to return the result as an object with the corresponding keys seen in the above examples and the difference key when needed.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function equalCount(str, names) {
  let strArr = str.replace(/[^a-zA-Z]/g, "").match(/[A-Z][a-z]+/g);
  let obj = {};
  for (let name of strArr) {
    if (obj[name]) {
      obj[name] += 1;
    } else {
      obj[name] = 1;
    }
  }
  //   console.log(obj);
  let [name1, name2] = names.split("&");
  //   console.log(name1, name2);
  let key = obj[name1] === obj[name2] ? "equality" : "difference";
  let sol = {
    [name1]: obj[name1] ? obj[name1] : 0,
    [name2]: obj[name2] ? obj[name2] : 0,
  };

  return key == "equality"
    ? { ...sol, equality: true }
    : {
        ...sol,
        equality: false,
        difference: Math.abs(obj[name1] - obj[name2]),
      };
}

Combine Two Objects Into One, Summing Like Values [Edabit]

Edabit

Take two objects with similar key values and combine them into a new object summing any values that belong to the same category.

There’s a married couple, Hank and his spouse Sheila. Hank works at a power plant making $70,000 a year, and Sheila is a teacher making $40,000 a year. They both earn rental income from separate rental properties, Hank will get $12,000 and Sheila $10,000. The new object will show their separate income but combine the rental income because it fits the same category.

const user1 = {
  powerPlant: 70000,
  rental: 12000
}

const user2 = {
  teaching: 40000,
  rental: 10000
}

becomes ➞ {
  powerPlant: 70000,
  teaching: 40000,
  rental: 22000   // The rental income is added together.
}

Arguments

  • user1Income (Object) ⁠— an income object for user1
  • user2Income (Object) ⁠— an income object for user2
  • returns: A new object with like values combined

Challenges

  1. They won’t have the same number of key-value pairs.
  2. The return object must return the values ordered from lowest to highest so your answers can match the test answers.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function combine(user1Income, user2Income) {
  let sol = { ...user1Income };
  Object.keys(user2Income).forEach((key) => {
    if (sol[key]) {
      sol[key] += user2Income[key];
    } else {
      sol[key] = user2Income[key];
    }
  });
  let temp = Object.keys(sol).map((key) => [key, sol[key]]);
  temp.sort((a, b) => a[1] - b[1]);
  sol = {};
  temp.forEach((arr) => {
    sol = { ...sol, [arr[0]]: arr[1] };
  });
  return sol;
}

Find First Character That Repeats [Edabit]

Edabit

Create a function that takes a string and returns the first character that repeats. If there is no repeat of a character, return "-1".

Examples

firstRepeat("legolas") ➞ "l"

firstRepeat("Gandalf") ➞ "a"

firstRepeat("Balrog") ➞ "-1"

firstRepeat("Isildur") ➞ "-1"
// Case sensitive "I" not equal to "i"

Notes

Tests are case sensitive.

Solution:

function firstRepeat(chars) {
	let obj={};
	for(let ch of [...chars]){
		if(obj[ch]){
			return ch;
		}else{
			obj[ch]=1;
		}
	}
	return "-1";
}