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(" ");
}

Multiplication Table [Eddabit]

Edabit

Your task, is to create N x N multiplication table, of size n provided in parameter.

For example, when n is 5, the multiplication table is:

  • 1, 2, 3, 4, 5
  • 2, 4, 6, 8, 10
  • 3, 6, 9, 12, 15
  • 4, 8, 12, 16, 20
  • 5, 10, 15, 20, 25

This example will result in:

[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]

Examples

multiplicationTable(1) ➞ [[1]]

multiplicationTable(3) ➞ [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

Notes

N/A

Solution:

function multiplicationTable(n) {
  let sol = [];
  for (let i = 1; i <= n; i++) {
    let temp = Array.from({ length: n }, () => i);
    temp = temp.map((num, i) => num * (i + 1));
    sol.push(temp);
  }
  return sol;
}

Hexadecimal Color Mixer [Edabit]

Edabit

In this challenge, you have to mix two or more colors to get a brand new color from their average rgb values.

Each color will be represented in its hexadecimal notation, and so as a string starting with # containing three pairs of alphanumeric characters, equals to the three rgb values (in base 16) of red, green and blue.

To obtain the new color, you need to get the arithmetic average of the sums of the individual red, green and blue values of each given color. When the average is a float number, you have to round it to the nearest integer (rounding up for decimal parts equal to 0.5).

Mixing yellow and red:

Hexadecimal code of yellow = "#FFFF00"
Hexadecimal code of red = "#FF0000"

yellow to RGB = Red: ["FF" = 255], Green: ["FF" = 255], Blue: ["00", 0]
red to RGB = Red: [""FF = 255], Green: ["00" = 0], Blue: ["00" = 0]

Average of Red values = (255 + 255) / 2 = 255
Average of Green values = (255 + 0) / 2 = 127.5 = 128
Average of Blue values = (0 + 0) / 2 = 0 = 0

Rgb of new color = [255, 128, 0]
Hexadecimal conversion = [255 = "FF"], [128 = "80"], [0 = "00"]

New color = "#FF8000" (orange)

Given an array of strings colors containing a series of hexadecimal codes, implement a function that returns the hexadecimal code of the new color, as a new string.

Examples

hexColorMixer(["#FFFF00", "#FF0000"]) ➞ "#FF8000"
// Orange

hexColorMixer(["#FFFF00", "#0000FF"]) ➞ "#808080"
// Medium gray

hexColorMixer(["#B60E73", "#0EAEB6"]) ➞ "#625E95"
// Lavender

Notes

  • Remember to round to the nearest integer the average of the rgb values.
  • You can test the color codes in any hexadecimal-colors utility site, such as this one that I used for testing cases.
  • All the given hexadecimal strings are valid; there are no exceptions to handle.
  • If you’re interested in rgb colors and their validation, you can give also try this challenge made by @Pustur (open this link in a new tab to avoid issues due to the refresh of the page)

Solution:

function hexColorMixer(colors) {
  let colorArr = [];
  for (let color of colors) {
    let temp = [];
    for (let i = 1; i < color.length; i += 2) {
      temp.push("0x" + color.substr(i, 2));
    }
    colorArr.push(temp);
  }
  let colorArrTrans = [];
  for (let i = 0; i < colorArr[0].length; i++) {
    let temp = [];
    for (let j = 0; j < colorArr.length; j++) {
      temp.push(colorArr[j][i]);
    }
    colorArrTrans.push(temp);
  }
  let sol = colorArrTrans
    .map((a) => a.reduce((acc, curr) => parseInt(curr) + acc, 0))
    .map((a) => {
      let temp = Math.round(a / colors.length).toString(16);
      if (temp.length == 1) {
        return "0" + temp;
      }
      return temp;
    });

  return "#" + sol.join("").toUpperCase();
}

Modify Words [Edabit]

Edabit

Create a function that takes an array of any length. Modify each element (capitalize, reverse, hyphenate).

Examples

editWords(["new york city"]) ➞ ["YTIC KR-OY WEN"]

editWords(["null", "undefined"]) ➞ ["LL-UN", "DENIF-EDNU"]

editWords(["hello", "", "world"]) ➞ ["OLL-EH", "-", "DLR-OW"]

editWords([""]) ➞ ["-"]

Notes

Input array values can be any type.

Solution:

function editWords(arr) {
	let sol =[];
	for(let word of arr){
		word = word.toUpperCase().split("").reverse().join("");
		let len = Math.ceil(word.length/2);
		sol.push(word.substr(0,len)+"-"+word.substr(len));
	}
	return sol;
}

Meme Sum :) [Edabit]

Edabit

For this challenge, forget how to add two numbers together. The best explanation on what to do for this function is this meme:

Alternative Text

Examples

memeSum(26, 39) ➞ 515
// 2+3 = 5, 6+9 = 15
// 26 + 39 = 515

memeSum(122, 81) ➞ 1103
// 1+0 = 1, 2+8 = 10, 2+1 = 3
// 122 + 81 = 1103

memeSum(1222, 30277) ➞ 31499

Notes

N/A

Solution:

function memeSum(a, b) {
  let aArr = a
    .toString()
    .split("")
    .map((n) => Number(n));
  let bArr = b
    .toString()
    .split("")
    .map((n) => Number(n));
  let sol = [];
  console.log(aArr, bArr);
  while (aArr.length > 0 || bArr.length > 0) {
    let numOne = aArr.pop();
    let numTwo = bArr.pop();
    numOne = numOne == undefined ? 0 : numOne;
    numTwo = numTwo === undefined ? 0 : numTwo;
    sol.push(numOne + numTwo);
  }
  return parseInt(sol.reverse().join(""));
}