Calculate the Missing Value with Ohm’s Law [Edabit]

Edabit

Create a function that calculates the missing value of 3 inputs using Ohm’s law. The inputs are vr or i (aka: voltage, resistance and current).

Ohm’s law:

V = R * I

Return the missing value rounded to two decimal places.

Examples

ohmsLaw(12, 220, "") ➞ 0.05

ohmsLaw(230, "", 2) ➞ 115

ohmsLaw("", 220, 0.02) ➞ 4.4

ohmsLaw("", "", 10) ➞ "Invalid"

ohmsLaw(500, 50, 10) ➞ "Invalid"

Notes

  • Missing values will be ""
  • If there is more than one missing value, or no missing value, return "Invalid"
  • Only numbers will be given.

SUGGEST EDITTestsConsole

Solution:

function ohmsLaw(v, r, i) {
    let val;
    let valArr = [v, r, i].filter(val => val === "")
    if (valArr.length === 0 || valArr.length > 1) {
        return "Invalid";
    }
    if (v === "") {
        console.log(r, '*', i)
        val = r * i;
    } else if (r === "") {
        console.log(v, '/', i)
        val = v / i;
    } else {
        console.log(v, '/', r)
        val = v / r;
    }
    return Number(val.toFixed(2));
}

//V = R * I

Do All Bigrams Exist? [Edabit]

Edabit

You are given an input array of bigrams, and an array of words.

Write a function that returns true if every single bigram from this array can be found at least once in an array of words.

Examples

canFind(["at", "be", "th", "au"], ["beautiful", "the", "hat"]) ➞ true

canFind(["ay", "be", "ta", "cu"], ["maybe", "beta", "abet", "course"]) ➞ false
# "cu" does not exist in any of the words.

canFind(["th", "fo", "ma", "or"], ["the", "many", "for", "forest"]) ➞ true

canFind(["oo", "mi", "ki", "la"], ["milk", "chocolate", "cooks"]) ➞ false

Notes

  • bigram is string of two consecutive characters in the same word.
  • If the array of words is empty, return false.

Solution:

function canFind(bigrams, words) {
    let sentense = words.join(" ")
    return bigrams.length === bigrams.filter(bia => {
        return sentense.includes(bia)
    }).length
}

Sum of Missing Numbers [Edabit]

Edabit

Create a function that returns the sum of missing numbers.

Examples

sumMissingNumbers([1, 3, 5, 7, 10]) ➞ 29
// 2 + 4 + 6 + 8 + 9

sumMissingNumbers([10, 7, 5, 3, 1]) ➞ 29

sumMissingNumbers([10, 20, 30, 40, 50, 60]) ➞ 1575

Notes

The minimum and maximum value of the given array are the inclusive bounds of the numeric range to consider when searching for missing numbers.

Solution:

function sumMissingNumbers(arr) {
	let min = Math.min(...arr);
	let max = Math.max(...arr);
	let sum = 0;
	for(let i = min;i<max; i++){
		if(!arr.includes(i)){
			sum+=i;
		}
	}
	return sum;
}

Connecting Words [Edabit]

Edabit

Write a function that connects each previous word to the next word by the shared letters. Return the resulting string (removing duplicate characters in the overlap) and the minimum number of shared letters across all pairs of strings.

Examples

join(["oven", "envier", "erase", "serious"]) ➞ ["ovenvieraserious", 2]

join(["move", "over", "very"]) ➞ ["movery", 3]

join(["to", "ops", "psy", "syllable"]) ➞ ["topsyllable", 1]

// "to" and "ops" share "o" (1)
// "ops" and "psy" share "ps" (2)
// "psy" and "syllable" share "sy" (2)
// the minimum overlap is 1

join(["aaa", "bbb", "ccc", "ddd"]) ➞ ["aaabbbcccddd", 0]

Notes

More specifically, look at the overlap between the previous words ending letters and the next word’s beginning letters.

Solution:

function join(arr) {
	let len = 9999;
	let sol = "";
	for(let i = 0;i<arr.length-1;i++){
		let j;
		let flag = false;
		for(j = 0; j<arr[i].length;j++){
			if(arr[i+1].indexOf(arr[i].substr(j)) === 0){
				sol += (arr[i].substr(0,j));
				console.log(len, arr[i].substr(0,j), arr[i], arr[i+1],arr[i+1].indexOf(arr[i].substr(j)))
				len = Math.min(Math.abs(arr[i].length - arr[i].substr(0,j).length), len)
				flag = true;
				break;
			}
		}
		if(flag == false){
			sol += arr[i];
		}
		console.log(flag);
	}
	sol +=(arr.pop());
//	console.log([sol, len==9999?0:len])
	return [sol, len===9999?0:len];
}

Playing with Nested Objects [Edabit]

Edabit

Create a function that takes an object and returns an object of all entries having unique marks. If the marks are the same, take who is eldest.

Examples

getObject({
  "0": { age: 18, name: "john", marks: "400" },
  "1": { age: 17, name: "julie", marks: "400" },
  "2": { age: 16, name: "Robin", marks: "200" },
  "3": { age: 16, name: "Bella", marks: "300" }
}) ➞ {
  "0": { age: 18, name: "john", marks: "400" },
  "1": { age: 16, name: "Robin", marks: "200" },
  "2": { age: 16, name: "Bella", marks: "300" }
}

getObject({
  0: {age: 18, name: 'john', marks: '400'},
  1: {age: 17, name: 'julie', marks: '400'},
  2: {age: 16, name: 'Robin', marks: '200'},
  3: {age: 16, name: 'Bella', marks: '300'},
  4: {age: 16, name: 'john', marks: '250'},
  5: {age: 15, name: 'julie', marks: '250'}
}) ➞    {
  0: {age: 18, name: 'john', marks: '400'},
  1: {age: 16, name: 'Robin', marks: '200'},
  2: {age: 16, name: 'Bella', marks: '300'},
  3: {age: 16, name: 'john', marks: '250'}
}

Notes

Check the examples above for clarification.

Solution:

function getObject(args) {
	let vals = Object.entries(args)
	vals.sort((a,b)=>{
		return b[1]["marks"]-a[1]["marks"]
	});
	let sol = {};
	for(let i = 1; i<vals.length; i++){
		if(vals[i-1][1]["marks"] === vals[i][1]["marks"]){
			if(vals[i-1][1]["age"]>vals[i][1]["age"]){
				vals.splice(i,1);
			}else{
				vals.splice(i-1,1);
			}
		}	
	}
	vals.sort((a,b)=>{
		return parseInt(a[0]) - parseInt(b[0]);
	})
	vals.forEach((v,index)=> {
		sol[index] = v[1]
	})
//	console.log(sol)
	return sol;
}

Number of Apples Left [Edabit]

Edabit

A man has n number of apples. If he eats a percentage p of the apples (if apples are available), his children will share the remainder of the apples. Create a function to determine the number of whole apples his children got. If his children did not get any apples, return "The children didn't get any apples".

Examples

getNumberOfApples(10, "90%") ➞ 1

getNumberOfApples(25, "10%") ➞ 22

getNumberOfApples(0, "10%") ➞ "The children didn't get any apples"

Notes

p will always be given.

Solution:

function getNumberOfApples(n, p) {
	let finished = n * (parseInt(p)/100);
	let remaining = Math.floor(n-finished);
	return remaining?remaining:"The children didn't get any apples";
}

Numbers First, Letters Second [Edabit]

Edabit

Write a function that sorts array while keeping the array structure. Numbers should be first then letters both in ascending order.

Examples

numThenChar([
  [1, 2, 4, 3, "a", "b"],
  [6, "c", 5], [7, "d"],
  ["f", "e", 8]
]) ➞ [
  [1, 2, 3, 4, 5, 6],
  [7, 8, "a"],
  ["b", "c"], ["d", "e", "f"]
]

numThenChar([
  [1, 2, 4.4, "f", "a", "b"],
  [0], [0.5, "d","X",3,"s"],
  ["f", "e", 8],
  ["p","Y","Z"],
  [12,18]
]) ➞ [
  [0, 0.5, 1, 2, 3, 4.4],
  [8],
  [12, 18, "X", "Y", "Z"],
  ["a", "b", "d"],
  ["e", "f", "f"],
  ["p", "s"]
]

Notes

Test cases will contain integer and float numbers and single letters.

Solution:

function numThenChar(arr) {
	let lenArr = arr.map(a=>a.length);
	arr = arr.flat();
	let arrNum = arr.filter(num => !isNaN(num))
	let arrAlpha = arr.filter(num => isNaN(num))
	arrNum.sort((a,b)=> a-b)
	arrAlpha.sort()
	arr = [...arrNum, ...arrAlpha];
	//console.log(lenArr)
	let sol = [];
	for(let len of lenArr){
		let temp = []
		while(len){
			temp.push(arr.shift())
			len--;
		}
		sol.push(temp)
	}
	return sol;
}

Which Generation Are You? [Edabit]

Edabit

Try finding your ancestors and offspring with code.

Create a function that takes a number x and a character y ("m" for male, "f" for female), and returns the name of an ancestor (m/f) or descendant (m/f).

  • If the number is negative, return the related ancestor.
  • If positive, return the related descendant.
  • You are generation 0. In the case of 0 (male or female), return "me!".

Examples

generation(2, "f") ➞ "granddaughter"

generation(-3, "m") ➞ "great grandfather"

generation(1, "f") ➞ "daughter"

Notes

Check the Resources tab for helpful hints.

GenerationMaleFemale
-3great grandfathergreat grandmother
-2grandfathergrandmother
-1fathermother
0me!me!
1sondaughter
2grandsongranddaughter
3great grandsongreat granddaughter

Solution:

const gen = {
	"-3": ["great grandfather",	"great grandmother"],
	"-2": ["grandfather","grandmother"],
	"-1":["father",	"mother"],
	"0": ["me!", "me!"],
	"1":["son",	"daughter"],
	"2"	:["grandson","granddaughter"],
	"3" :["great grandson","great granddaughter"]
}
function generation(x, y) {
	return y=="m"?gen[x][0]:gen[x][1];
}

Imaginary Coding Interview [Edabit]

Edabit

Create a function to check if a candidate is qualified in an imaginary coding interview of an imaginary tech startup.

The criteria for a candidate to be qualified in the coding interview is:

  1. The candidate should have complete all the questions.
  2. The maximum time given to complete the interview is 120 minutes.
  3. The maximum time given for very easy questions is 5 minutes each.
  4. The maximum time given for easy questions is 10 minutes each.
  5. The maximum time given for medium questions is 15 minutes each.
  6. The maximum time given for hard questions is 20 minutes each.

If all the above conditions are satisfied, return "qualified", else return "disqualified".

You will be given an array of time taken by a candidate to solve a particular question and the total time taken by the candidate to complete the interview.

Given an array, in a true condition will always be in the format [very easy, very easy, easy, easy, medium, medium, hard, hard].

The maximum time to complete the interview includes a buffer time of 20 minutes.

Examples

interview([5, 5, 10, 10, 15, 15, 20, 20], 120) ➞ "qualified"

interview([2, 3, 8, 6, 5, 12, 10, 18], 64) ➞  "qualified"

interview([5, 5, 10, 10, 25, 15, 20, 20], 120) ➞ "disqualified"
// Exceeded the time limit for a medium question.

interview([5, 5, 10, 10, 15, 15, 20], 120) ➞ "disqualified"
// Did not complete all the questions.

interview([5, 5, 10, 10, 15, 15, 20, 20], 130) ➞ "disqualified"
// Solved all the questions in their respected time limits but exceeded the total time limit of the interview.

Notes

Try to solve the problem using only array methods.

Solution:

function interview(arr, tot) {
  if (tot > 120 || arr.length !== 8) return "disqualified";
  for (let i in arr) {
    if (i >= 0 && i <= 1) {
      if (arr[i] > 5) {
        return "disqualified";
      }
    } else if (i >= 2 && i <= 3) {
      if (arr[i] > 10) {
        return "disqualified";
      }
    } else if (i >= 4 && i <= 5) {
      if (arr[i] > 15) {
        return "disqualified";
      }
    } else {
      if (arr[i] > 20) {
        return "disqualified";
      }
    }
  }
  return "qualified";
}

Most Common Last Vowel [Edabit]

Edabit

Create a function that takes in a sentence as input and returns the most common last vowel in the sentence as a single character string.

Examples

commonLastVowel("Hello World!") ➞ "o"

commonLastVowel("Watch the characters dance!") ➞ "e"

commonLastVowel("OOI UUI EEI AAI") ➞ "i"

Notes

  • There will only be one common last vowel in each sentence.
  • If the word has one vowel, treat the vowel as the last one even if it is at the start of the word.
  • The question asks you to compile all of the last vowels of each word and returns the vowel in the list which appears most often.
  • y won’t count as a vowel.
  • Return outputs in lowercase.

Solution:

function commonLastVowel(str) {
  return str
    .toLowerCase()
    .replace(/[^aeiou]/g, "")
    .split("")
    .pop();
}