Remove the Last Vowel [Edabit]

Edabit

Write a function that removes the last vowel in each word in a sentence.

Examples

removeLastVowel("Those who dare to fail miserably can achieve greatly.")
➞ "Thos wh dar t fal miserbly cn achiev gretly."

removeLastVowel("Love is a serious mental disease.")
➞ "Lov s  serios mentl diseas"

removeLastVowel("Get busy living or get busy dying.")
➞ "Gt bsy livng r gt bsy dyng"

Notes

Vowels are: a, e, i, o, u (both upper and lowercase).

Solution:

function removeLastVowel(str) {
  let strArr = str.split(" ").map((word) => {
    let sol = "",
      flag = false;
    for (let i = word.length - 1; i >= 0; i--) {
      if ("aeiouAEIOU".includes(word[i]) && !flag) {
        sol += "";
        flag = true;
      } else {
        sol += word[i];
      }
    }
    return sol.split("").reverse().join("");
  });
  return strArr.join(" ");
}

Switching Between Pencils [Edabit]

Edabit

When coloring a striped pattern, you may start by coloring each square sequentially, meaning you spend time needing to switch coloring pencils.

Create a function where given an array of colors cols, return how long it takes to color the whole pattern. Note the following times:

  • It takes 1 second to switch between pencils.
  • It takes 2 seconds to color a square.

See the example below for clarification.

color_pattern_times(["Red", "Blue", "Red", "Blue", "Red"]) ➞ 14

// There are 5 colors so it takes 2 seconds to color each one (2 x 5 = 10).
// You need to switch the pencils 4 times and it takes 1 second to switch (1 x 4 = 4).
// 10 + 4 = 14

Examples

colorPatternTimes(["Blue"]) ➞ 2

colorPatternTimes(["Red", "Yellow", "Green", "Blue"]) ➞ 11

colorPatternTimes(["Blue", "Blue", "Blue", "Red", "Red", "Red"]) ➞ 13

Notes

  • Only change coloring pencils if the next color is different to the color before it.
  • Return a number in seconds.

Solution:

function colorPatternTimes(cols) {
  let arr = [cols[0]];
  for (let col of cols) {
    if (arr[arr.length - 1] !== col) arr.push(col);
  }
  return arr.length - 1 + cols.length * 2;
}

isCryptSolution [CodeSignal]

CodeSignal

cryptarithm is a mathematical puzzle for which the goal is to find the correspondence between letters and digits, such that the given arithmetic equation consisting of letters holds true when the letters are converted to digits.

You have an array of strings crypt, the cryptarithm, and an an array containing the mapping of letters and digits, solution. The array crypt will contain three non-empty strings that follow the structure: [word1, word2, word3], which should be interpreted as the word1 + word2 = word3 cryptarithm.

If crypt, when it is decoded by replacing all of the letters in the cryptarithm with digits using the mapping in solution, becomes a valid arithmetic equation containing no numbers with leading zeroes, the answer is true. If it does not become a valid arithmetic solution, the answer is false.

Note that number 0 doesn’t contain leading zeroes (while for example 00 or 0123 do).

Example

For crypt = ["SEND", "MORE", "MONEY"] and

solution = [['O', '0'],
            ['M', '1'],
            ['Y', '2'],
            ['E', '5'],
            ['N', '6'],
            ['D', '7'],
            ['R', '8'],
            ['S', '9']]

the output should be
solution(crypt, solution) = true.

When you decrypt "SEND""MORE", and "MONEY" using the mapping given in crypt, you get 9567 + 1085 = 10652 which is correct and a valid arithmetic equation.

For crypt = ["TEN", "TWO", "ONE"] and

solution = [['O', '1'],
            ['T', '0'],
            ['W', '9'],
            ['E', '5'],
            ['N', '4']]

the output should be
solution(crypt, solution) = false.

Even though 054 + 091 = 145054 and 091 both contain leading zeroes, meaning that this is not a valid solution.

Solution:

function solution(crypt, solution) {
  let solObj = {};
  for (let sol of solution) {
    solObj[sol[0]] = sol[1];
  }
  let cryptWords = [];
  for (let word of crypt) {
    let temp = "";
    for (let ch of word) {
      temp += solObj[ch];
    }
    cryptWords.push(temp);
  }
  console.log(cryptWords);
  let [num1, num2, num3] = cryptWords.map((n) => Number(n));
  let [len1, len2, len3] = cryptWords.map((n) => n.length);
  if (len1 === 1 && len2 === 1 && len3 === 1) {
    return num1 + num2 === 0;
  }
  if (
    cryptWords[0][0] !== "0" &&
    cryptWords[1][0] !== "0" &&
    cryptWords[2][0] !== "0"
  ) {
    return num1 + num2 === num3;
  }
  return false;
}

Count the Lone Ones [Edabit]

Edabit

Create a function which counts how many lone 1s appear in a given number. Lone means the number doesn’t appear twice or more in a row.

Examples

countLoneOnes(101) ➞ 2

countLoneOnes(1191) ➞ 1

countLoneOnes(1111) ➞ 0

countLoneOnes(462) ➞ 0

Notes

Tests will include positive whole numbers only.

Solution:

function countLoneOnes(n) {
  let arr = n
    .toString()
    .split("")
    .map((n) => Number(n));
  arr.push(0);
  arr.unshift(0);
  let sol = 0;
  for (let i = 1; i < arr.length - 1; i++) {
    if (arr[i] == 1) {
      if (arr[i] !== arr[i - 1] && arr[i] !== arr[i + 1]) {
        sol++;
      }
    }
  }
  return sol;
}

Secret Agent Password [Edabit]

Edabit

Mubashir is going on a secret mission. He needs your help but you have to learn how to encode a secret password to communicate safely with other agents. Create a function that takes an argument message and returns the encoded password.

There are some variations on the rules of encipherment. One version of the cipher rules are outlined below:

secretPassword("mubashirh") ➞ "hsajsi13u2"

Step 1: Message length should be of nine characters containing only lowercase letters from ‘a’ to ‘z’. If the argument doesn’t meet this requirement you must return "BANG! BANG! BANG!" (Remember, there are no second chances in the spy world!)

Step 2: Divide the string into three equal parts of three characters each:

1 - mub
2 - ash
3 - irh

Step 3: Convert the first and third letter to the corresponding number, according to the English alphabets (ex. a = 1, b = 2, c = 3 … z = 26, etc).

mub = 13u2

Step 4: Reverse the fourth, fifth, and sixth letters:

ash = hsa

Step 5: Replace seventh, eighth, and ninth letter with next letter (z will be substituted with a).

irh = jsi

Step 6: Return the string in the following order: “Part_2+Part_3+Part_1”

"hsajsi13u2"

See the below examples for a better understanding:

Examples

secretPassword("mubashirh") ➞ "hsajsi13u2"

secretPassword("mattedabi") ➞ "detbcj13a20"

secretPassword("HeLen-eda") ➞ "BANG! BANG! BANG!"
// Length is not equal to 9
// Contains characters other than lower alphabets

Notes

N/A

Solution:

function secretPassword(message) {
  let alpha = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
  ];
  if (
    message.replace(/[^a-z]/g, "").toLowerCase() === message &&
    message.length === 9
  ) {
    let word = [];
    for (let i = 0; i < 9; i += 3) {
      word.push(message.substr(i, 3).split(""));
    }
    console.log(word);
    word[0] = [
      alpha.indexOf(word[0][0]) + 1,
      word[0][1],
      alpha.indexOf(word[0][2]) + 1,
    ];

    word[1] = [word[1][2], word[1][1], word[1][0]];

    word[2] = [
      alpha[(alpha.indexOf(word[2][0]) + 1) % 26],
      alpha[(alpha.indexOf(word[2][1]) + 1) % 26],
      alpha[(alpha.indexOf(word[2][2]) + 1) % 26],
    ];

    let sol = [word[1], word[2], word[0]].map((w) => w.join("")).join("");
    //console.log(sol);
    return sol;
  } else {
    return "BANG! BANG! BANG!";
  }
}

Validating a Set in the Set Game [Edabit]

Edabit

In the game Setthree cards form a set if each of the cards are identical or completely different for each of the four properties. All three cards must:

  1. Have the same color or different colors.
  2. Have the same number or different numbers.
  3. Have the same shades or different shades.
  4. Have the same shape or different shapes.

The four properties are:

  1. Colors: red, purple, green
  2. Numbers: 1, 2, 3
  3. Shades: empty, lined, full
  4. Shapes: squiggle, oval, diamond

Here, a set is represented by an array containing three cards. Each card is represented by an object of properties and values. Write a function that determines whether three cards constitute a valid set.

Here is an example of a set:

[
  { color: "red", number: 1, shade: "empty", shape: "squiggle" },
  { color: "red", number: 2, shade: "lined", shape: "diamond" },
  { color: "red", number: 3, shade: "full", shape: "oval" }
]

// "Same" properties: color
// "Different" properties: numbers, shading and shapes

The following is not a set:

[
  { color: "red", number: 1, shade: "empty", shape: "squiggle" },
  { color: "red", number: 2, shade: "lined", shape: "diamond" },
  { color: "purple", number: 3, shade: "full", shape: "oval" }
]

// Colors are not all identical, but not all different.

Examples

isSet([
  { color: "green", number: 1, shade: "empty", shape: "squiggle" },
  { color: "green", number: 2, shade: "empty", shape: "diamond" },
  { color: "green", number: 3, shade: "empty", shape: "oval" }
]) ➞ true

isSet([
  { color: "purple", number: 1, shade: "full", shape: "oval" },
  { color: "green", number: 1, shade: "full", shape: "oval" },
  { color: "red", number: 1, shade: "full", shape: "oval" }
]) ➞ true

isSet([
  { color: "purple", number: 3, shade: "full", shape: "oval" },
  { color: "green", number: 1, shade: "full", shape: "oval" },
  { color: "red", number: 3, shade: "full", shape: "oval" }
]) ➞ false

Notes

  • A set cannot have 2/3 cards having the same property. Either all must share that property, or none will share that particular property.
  • You can play Set by checking the Resources tab.

Solution:

function isSet(cards) {
  let sol = [];
  let keys = Object.keys(cards[0]);
  for (let i = 0; i < 4; i++) {
    let set = new Set();
    for (let j = 0; j < cards.length; j++) {
      //console.log(cards[j][keys[i]])
      set.add(cards[j][keys[i]]);
    }
    sol.push(set.size);
  }
  //console.log(sol);
  return sol.includes(2) ? false : true;
}

Exactly Three [Edabit]

Edabit

You are given a number n. Determine whether n has exactly 3 divisors or not.

Examples

isExactlyThree(4) ➞ true
// 4 has only 3 divisors: 1, 2 and 4

isExactlyThree(12) ➞ false
// 12 has 6 divisors: 1, 2, 3, 4, 6, 12

isExactlyThree(25) ➞ true
// 25 has only 3 divisors: 1, 5, 25

Notes

1 ≤ n ≤ 10^12

Solution:

function isExactlyThree(n) {
	let divs = [1,n];
	if(n<=3){
		return false;
	}
	for(let i = 2;i<= Math.sqrt(n);i++){
		if(n%i===0){
			divs.push(i);
			divs.push(n/i);
		}
	}
	return new Set(divs).size===3?true:false;
}

Substring Consonant-Vowel Groups [Edabit]

Edabit

Write two functions:

  1. One to retrieve all unique substrings that start and end with a vowel.
  2. One to retrieve all unique substrings that start and end with a consonant.

The resulting array should be sorted in lexicographic ascending order (same order as a dictionary).

Examples

getVowelSubstrings("apple")
➞ ["a", "apple", "e"]

getVowelSubstrings("hmm") ➞ []

getConsonantSubstrings("aviation")
➞ ["n", "t", "tion", "v", "viat", "viation"]

getConsonantSubstrings("motor")
➞ ["m", "mot", "motor", "r", "t", "tor"]

Notes

  • Remember the output array should have unique values.
  • The word itself counts as a potential substring.
  • Exclude the empty string when outputting the array.

Solution:

function getVowelSubstrings(str) {
  let sol = strArr(str);
  //console.log(sol)
  return sol.filter((word) => {
    let len = word.length - 1;
    return "aeiou".includes(word[0]) && "aeiou".includes(word[len]);
  });
}

function getConsonantSubstrings(str) {
  let sol = strArr(str);
  //console.log(sol)
  return sol.filter((word) => {
    let len = word.length - 1;
    return !"aeiou".includes(word[0]) && !"aeiou".includes(word[len]);
  });
}

function strArr(str) {
  let sol = [];
  let len = str.length;
  for (let i = 0; i < len; i++) {
    for (let j = 1; j <= len - i; j++) {
      sol.push(str.substr(i, j));
    }
  }
  sol.sort();
  return [...new Set(sol)];
}

Underscore-Hash Staircase [Edabit]

Edabit

Create a function that will build a staircase using the underscore _ and hash # symbols. A positive value denotes the staircase’s upward direction and downwards for a negative value.

Examples

staircase(3) ➞ "__#\n_##\n###"
__#
_##
###

staircase(7) ➞ "______#\n_____##\n____###\n___####\n__#####\n_######\n#######"
______#
_____##
____###
___####
__#####
_######
#######

staircase(2) ➞ "_#\n##"
_#
##

staircase(-8) ➞ "########\n_#######\n__######\n___#####\n____####\n_____###\n______##\n_______#"
########
_#######
__######
___#####
____####
_____###
______##
_______#

Notes

  • All inputs are either positive or negative values.
  • The string to be returned is adjoined with the newline character (\n).
  • A recursive version of this challenge can be found here.

Solution:

function staircase(n) {
  let sol = [];
  let abs = Math.abs(n);
  for (let i = 0; i < abs; i++) {
    sol.push(
      Array.from({ length: abs - i }, () => "#")
        .join("")
        .padStart(abs, "_")
    );
  }
  return n >= 0 ? sol.reverse().join("\n") : sol.join("\n");
}

First Letter Shift [Edabit]

Edabit

Given a sentence, create a function which shifts the first letter of each word to the next word in the sentence (shifting right).

Examples

shiftSentence("create a function") ➞ "freate c aunction"

shiftSentence("it should shift the sentence") ➞ "st ihould shift she tentence"

shiftSentence("the output is not very legible") ➞ "lhe tutput os iot nery vegible"

shiftSentence("edabit") ➞ "edabit"

Notes

  • The last word shifts its first letter to the first word in the sentence.
  • All sentences will be given in lowercase.
  • Note how single words remain untouched (example #4).

Solution:

function shiftSentence(str) {
  let strArr = str.split(" ");
  let firstLetter = strArr.map((w) => w[0]);
  for (let i = 1; i < strArr.length; i++) {
    strArr[i] = firstLetter[i - 1] + strArr[i].substr(1);
  }
  strArr[0] = firstLetter[firstLetter.length - 1] + strArr[0].substr(1);
  return strArr.join(" ");
}