Problem Solving-1
Problem Solving-1
Problem Solving-1
Examples
Input: "coderbyte"
Output: etybredoc
function FirstReverse(str) {
return newString;
}
function FirstReverse(str) {
// code goes here
return str.split('').reverse().join('');
Examples
Input: 4
Output: 24
Input: 8
Output: 40320
function FirstFactorial(num) {
let factorial = 1;
return factorial;
function FirstFactorial(num) {
let answer = 1;
for (let index = 1; index <= num; index++) {
answer *= index;
}
return answer;
Longest Word
Examples
Input: "fun&!! time"
Output: time
function LongestWord(sen) {
sen = sen.trim();
sen = sen.replace(/[^a-zA-Zsd]/g, '');
return arr.shift();
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LongestWord(readline());
function LongestWord(sen) {
let validCharacters =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let maxLength = 0;
let longestWord = '';
}
}
return longestWord;
function LongestWord(sen) {
var trimmed = sen.replace(/[^\w]/g, ' ');
var words = trimmed.split(/\s+/);
var longestWord = words.sort(function(a, b) {return b.length - a.length;})[0];
return longestWord;
}
Examples
Input: "hello*3"
Output: Ifmmp*3
Input: "fun times!"
Output: gvO Ujnft!
function LetterChanges(str) {
str = str.trim().toLowerCase();
var len = str.length;
var newStr = '';
// capitlize vowels
for (let i = 0; i < newString.length; i++) {
if (vowels.includes(newString[i])) {
finalString += newString[i].toUpperCase();
} else {
finalString += newString[i];
}
}
return finalString;
function LetterChanges(str) {
str = str.replace(/[a-zA-Z]/g, function(ch) {
if (ch === 'z') return 'a';
else if (ch === 'Z') return 'A';
else return String.fromCharCode(ch.charCodeAt(0) + 1);
});
Have the function SimpleAdding(num) add up all the numbers from 1 to num. For example: if
the input is 4 then your program should return 10 because 1 + 2 + 3 + 4 = 10. For the test cases,
the parameter num will be any number from 1 to 1000.
Examples
Input: 12
Output: 78
Input: 140
Output: 9870
function SimpleAdding(num) {
if (num === 1) {
return 1;
}
else {
return num + SimpleAdding(num -1);
}
}
function SimpleAdding(num) {
let sum = 0;
for (i = 1; i <= num; i++) {
sum += i;
}
return sum;
function SimpleAdding(num) {
Letter Capitalize
Examples
Input: "hello world"
Output: Hello World
function LetterCapitalize(str) {
return str;
function LetterCapitalize(str) {
let newString = '';
for (let i = 0, newWord = true; i < str.length; i++) {
if (newWord) {
newString += str[i].toUpperCase();
} else {
newString += str[i];
}
return newString;
}
function LetterCapitalize(str) {
Simple Symbols
Examples
Input: "+d+=3=+s+"
Output: true
Input: "f++d+"
Output: false
function SimpleSymbols(str) {
if (/^[a-zA-Z]/.test(str) || /[a-zA-Z]$/.test(str)) {
return false;
}
else if (/[^+][a-zA-Z]/.test(str) || /[a-zA-Z][^+]/.test(str)) {
return false;
}
else {
return true;
}
function SimpleSymbols(str) {
function SimpleSymbols(str) {
Check Nums
Have the function CheckNums(num1,num2) take both parameters being passed and return the
string true if num2 is greater than num1, otherwise return the string false. If the parameter
values are equal to each other then return the string -1.
Examples
VIEW CHALLENGE
function CheckNums(num1,num2) {
if (num1 == num2) {
return "-1";
}
else {
return (num2 > num1);
}
}
function CheckNums(num1,num2) {
function CheckNums(num1,num2) {
Time Convert
Examples
Input: 126
Output: 2:6
Input: 45
Output: 0:45
function TimeConvert(num) {
var hours = Math.floor(num/60);
var minutes = num % 60;
var str = hours + ":" + minutes;
return str;
function TimeConvert(num) {
function TimeConvert(num) {
Alphabet Soup
Examples
Input: "coderbyte"
Output: bcdeeorty
Input: "hooplah"
Output: ahhloop
function AlphabetSoup(str) {
return result;
function AlphabetSoup(str) {
function AlphabetSoup(str) {
AB Check
Have the function ABCheck(str) take the str parameter being passed and return the string
true if the characters a and b are separated by exactly 3 places anywhere in the string at least
once (ie. "lane borrowed" would result in true because there is exactly three characters
between a and b). Otherwise return the string false.
Examples
Input: "after badly"
Output: false
Input: "Laura sobs"
Output: true
function ABCheck(str) {
patt = /(a...b|b...a)/
return patt.test(str);
function ABCheck(str) {
if (str.length < 5) {
return false;
}
console.log(str.length);
return false;
}
// keep this function call here
ABCheck(readline());
function ABCheck(str) {
Examples
Input: "hello"
Output: 2
Input: "coderbyte"
Output: 3
function VowelCount(str) {
if (arr == null) {
return 0;
}
else {
return arr.length;
}
}
function VowelCount(str) {
Word Count
Examples
Input: "Hello World"
Output: 2
Input: "one 22 three"
Output: 3
function WordCount(str) {
function WordCount(str) {
return str.split(' ').length;
}
function WordCount(str) {
Ex Oh
Examples
Input: "xooxxo"
Output: true
Input: "x"
Output: false
function ExOh(str) {
var regExPatternX = /x/gi;
var regExPatternO = /o/gi;
var arrayXLen = str && str.match(regExPatternX) ?
str.match(regExPatternX).length : 0;
var arrayOLen = str && str.match(regExPatternO) ?
str.match(regExPatternO).length : 0;
function ExOh(str) {
let xCount = 0;
let oCount = 0;
function ExOh(str) {
Examples
Input: "eye"
Output: true
function Palindrome(str) {
modified = str.replace(/W/g,"");
function Palindrome(str) {
Arith Geo
Have the function ArithGeo(arr) take the array of numbers stored in arr and return the
string "Arithmetic" if the sequence follows an arithmetic pattern or return "Geometric" if it
follows a geometric pattern. If the sequence doesn't follow either pattern return -1. An
arithmetic sequence is one where the difference between each of the numbers is consistent,
where as in a geometric sequence, each term after the first is multiplied by some constant or
common ratio. Arithmetic example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54]. Negative
numbers may be entered as parameters, 0 will not be entered, and no array will contain all the
same elements.
Examples
Input: [5,10,15]
Output: Arithmetic
Input: [2,4,16,24]
Output: -1
function ArithGeo(arr) {
var len = arr.length;
var arithK = arr[1] - arr[0];
var geoK = arr[1] / arr[0];
return -1;
}
function ArithGeo(arr) {
if (arithmetic) {
return 'Arithmetic';
}
if (geometric) {
return 'Geometric';
}
return -1;
function ArithGeo(arr) {
Array Addition I
Examples
Input: [5,7,16,1,2]
Output: false
Input: [3,5,-1,8,12]
Output: true
function ArrayAdditionI(arr) {
var target;
var addArr = arrayPrep(arr);
var len = addArr.length;
var permNum = Math.pow(2, len);
console.log('test0 ', permNum, target, addArr);
function arrayPrep(arr2) {
arr.sort(function(a, b){
return a - b
});
target = arr2.pop()
return arr2
}
}
function ArrayAdditionI(arr) {
let sum = 0;
for (let j = 0; j < combos[i].length; j++) {
if (combos[i][j] === '1') {
sum += arr[j];
}
}
function ArrayAdditionI(arr) {
Letter Count I
Examples
Input: "No words"
Output: -1
function LetterCountI(str) {
var arr = str.toLowerCase().split(" ");
var n = arr.length;
var counter = 1;
var maxcount = 0;
var newarr = [];
if (newarr[0][1] == 1) {
return -1;
}
else {
return newarr[0][0];
}
}
function LetterCountI(str) {
let bestCount = 0;
let bestWord = '';
function LetterCountI(str) {
Examples
Input: [4, 90]
Output: 90 4
function SecondGreatLow(arr) {
arr.sort(function(a, b) {return a - b});
arr = lonely(arr);
var newlen = arr.length;
function lonely(arr) {
var len = arr.length;
var testobj = {};
var output = [];
var count = 0;
for (var i = 0; i < len; i++) {
var holder = arr[i];
if (!testobj[holder]) {
testobj[holder] = true;
output[count++] = holder;
}
}
return output
}
}
function SecondGreatLow(arr) {
function SecondGreatLow(arr) {
Examples
if (numleng > 3) {
var arr = string.split("");
for (var i= numleng - 3; i > 0; i = i - 3) {
arr.splice(i, 0, ",");
}
var newstring = arr.join("");
}
return newstring;
function DivisionStringified(num1,num2) {
function DivisionStringified(num1,num2) {
return result;
}
Counting Minutes I
Input: "12:30pm-12:00am"
Output: 690
Input: "1:23am-1:08am"
Output: 1425
Solutions for Counting Minutes I
JAVASCRIPT
VIEW CHALLENGE
function CountingMinutesI(str) {
var seps = str.split("-");
var col1 = seps[0].indexOf(":");
var col2 = seps[1].indexOf(":");
var hour1 = parseInt(seps [0].slice(0, col1));
var hour2 = parseInt(seps[1].slice(0, col2));
var min1 = parseInt(seps[0].slice(col1+1, col1+3));
var min2 = parseInt(seps[1].slice(col2+1, col2+3));
var ampm1 = seps[0].slice(-2);
var ampm2 = seps[1].slice(-2);
if (ampm1 == "pm" && hour1 != 12) {
hour1 = hour1 + 12;
}
if (ampm2 == "pm" && hour2 != 12) {
hour2 = hour2 + 12;
}
if (hour1 == 12 && ampm1 == "am") {
hour1 = 0;
}
if (hour2 == 12 && ampm2 == "am") {
hour2 = 0;
}
var time1 = (hour1*60) + min1;
var time2 = (hour2*60) + min2;
if (diff < 0) {
diff = diff + (60 * 24);
}
return diff;
function CountingMinutesI(str) {
function parseMinutes(timeStr) {
var time = timeStr.match(/d+/g);
var hour = parseInt(time[0]), minute = parseInt(time[1]);
var ampm = (timeStr.match(/[a|p]m/g)[0] === 'am') ? 0 : 1;
if (hour === 12) hour = 0;
Examples
Input: [1, 2, 3]
Output: 0
Input: [4, 4, 4, 6, 2]
Output: 1
function MeanMode(arr) {
len = arr.length
//Step 1: determine the mean - self explanatory
function mean(arr) {
var count = 0;
for (var i = 0; i < len; i++) {
count += arr[i]
}
console.log (count / len)
return count / len
}
//Step 2: determine the mode. We need to count how many of each type are in the
array. One alternative is to keep a counter going, sort the array and then count
until an item changes, keeping track of the maximum count and the associate value.
The following is a much easier way, assuming that one has a basic familiarity with
javascript objects. It makes each new entry a key, and keeps count of how many of
each there are, then makes an array of the key-value pairs created.
function mode(arr) {
var obj = {};
for (var i = 0, len = arr.length; i < len; i++) {
if (obj[arr[i]] === undefined) {
obj[arr[i]] = 1;
}
else {
obj[arr[i]]++;
}
}
var objarr = [];
for (x in obj) {
objarr.push([x, obj[x]]);
}
objarr.sort(function(a, b) {return b[1] - a[1]});
console.log(objarr[0][0]);
return objarr[0][0];
}
//Compare the mean and the mode
return mode(arr) == mean(arr)? 1: 0;
}
function MeanMode(arr) {
// Find mode
let mostOccurances = 0;
let mode = 0;
for (let i = 0; i < arr.length; i++) {
let marco = arr[i];
for (let j = i+1, count = 0; j < arr.length; j++) {
if (marco === arr[j]) {
// match!
count++;
if (count > mostOccurances) {
mostOccurances = count;
mode = arr[j];
}
}
}
}
// Find mean
let mean = 0;
for (let i = 0; i < arr.length; i++) {
mean += arr[i];
}
mean = Math.round(mean/arr.length);
function MeanMode(arr) {
function mean(arr) {
return arr.reduce(function(a,b) {return a+b;}, 0) / arr.length;
}
Dash Insert
Have the function DashInsert(str) insert dashes ('-') between each two odd numbers
in str. For example: if str is 454793 the output should be 4547-9-3. Don't count zero as an
odd number.
Examples
Input: 99946
Output: 9-9-946
Input: 56730
Output: 567-30
function DashInsert(num) {
var strnum = num.toString();
var arr = strnum.split("");
return x;
function DashInsert(str) {
function DashInsert(str) {
function isOdd(n) {
return parseInt(n) % 2 === 1;
}
Swap Case
Examples
Input: "Hello-LOL"
Output: hELLO-lol
Input: "Sup DUDE!!?"
Output: sUP dude!!?
function SwapCase(str) {
arr = str.split("");
for (var i = 0; i < arr.length; i++) {
if (arr[i] == arr[i].toUpperCase()) {
arr[i] = arr[i].toLowerCase();
}
else if (arr[i] == arr[i].toLowerCase()) {
arr[i] = arr[i].toUpperCase();
}
}
str = arr.join("");
return str;
function SwapCase(str) {
function SwapCase(str) {
Examples
Input: "75Number9"
Output: 84
return ans
}
function NumberAddition(str) {
if (!DIGITS.includes(str[i])) {
if (number !== '') {
numbers.push(number);
}
number = '';
} else {
number += str[i];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += parseInt(numbers[i]);
}
return sum;
}
function NumberAddition(str) {
var numbers = str.match(/\d+/g) || [];
return numbers.reduce(function(sum, number) {return sum + Number(number)}, 0);
}
Third Greatest
Examples
Input: ["coder","byte","code"]
Output: code
Input: ["abc","defg","z","hijk"]
Output: abc
function ThirdGreatest(strArr) {
strArr.sort(function(a, b) {return b.length - a.length});
return strArr[2];
}
function ThirdGreatest(strArr) {
return strArr[2];
function ThirdGreatest(strArr) {
Examples
Input: 4
Output: true
Input: 124
Output: false
function PowersofTwo(num) {
else {
while (num >= 2){
var test = num%2;
if (test == 0){
num = num/2
ans = "true";}
else{
num = 0;
ans = "false"}
}
}
// code goes here
return ans;
function PowersofTwo(num) {
return Number.isInteger(Math.log(num) / Math.log(2)) ? true : false;
function PowersofTwo(num) {
Additive Persistence
Examples
Input: 4
Output: 0
Input: 19
Output: 2
VIEW CHALLENGE
function AdditivePersistence(num) {
function arrprep(numb) {
var numstr = numb.toString();
var arr = numstr.split('');
var numarr = arr.map(function(val) {
return parseInt(val)
})
return numarr
}
function addup(arr) {
var redux = arr.reduce(function(a, b){
return a + b })
return redux
}
var count = 0;
return count
function AdditivePersistence(num) {
num = num.toString();
let count = 0;
}
return count;
}
function AdditivePersistence(num) {
Multiplicative Persistence
Examples
Input: 4
Output: 0
Input: 25
Output: 2
function MultiplicativePersistence(num) {
function numprep(num) {
var strnum = num.toString();
var arr = strnum.split('');
var numarr = arr.map(function(val) {
return parseInt(val)});
return numarr
}
function multnums(arr) {
var newnum = arr.reduce(function(a, b) {
return a * b})
return newnum
}
// code goes here
var count = 0;
function MultiplicativePersistence(num) {
num = num.toString();
let count = 0;
while(1) {
if (num.length === 1) {
break;
}
count++;
let sum = 1;
for (let i = 0; i < num.length; i++) {
sum *= parseInt(num[i]);
}
num = sum.toString();
}
return count;
function MultiplicativePersistence(num) {
Examples
Input: ["1","2","E","E","3"]
Output: 1,2
Input: ["4","E","1","E","2","E","3","E"]
Output: 4,1,2,3
function OffLineMinimum(strArr) {
var len = strArr.length;
var count = 0;
var holdArr = [];
var ans = [];
function OffLineMinimum(strArr) {
let smallestIndex = 0;
let smallestNumber = null;
strArr.forEach(function(value,index){
if (index > maxIndex) {
return;
}
if (value !== 'E' && value !== 'R') {
if (smallestNumber === null || parseInt(value) < smallestNumber) {
smallestIndex = index;
smallestNumber = parseInt(value);
}
}
});
strArr[smallestIndex] = 'R';
return smallestNumber;
}
return result.join(',');
function OffLineMinimum(strArr) {
Changing Sequence
Examples
return index;
}
}
function ChangingSequence(arr) {
function ChangingSequence(arr) {
if (arr.length < 2) return -1;
var increasing = arr[0] < arr[1];
return -1;
}
Examples
Input: [5,11,1,5,1]
Output: true
Input: [1,8,2,4,4]
Output: false
function OverlappingRanges(arr) {
var target = arr.pop();
var MaxLowerBound = Math.max(arr[0], arr[2]);
var MinUpperBound = Math.min(arr[1], arr[3]);
function OverlappingRanges(arr) {
let count = 0;
for (let i = arr[0]; i <= arr[1]; i++) {
if (i >= arr[2] && i <= arr[3]) {
count++;
}
}
return (count >= arr[4]) ? true : false;
}
function OverlappingRanges(arr) {
var range1 = [arr[0], arr[1]]; // (a, b)
var range2 = [arr[2], arr[3]]; // (c, d)
var minimumOverlap = arr[4] - 1;
Superincreasing
Examples
Input: [1,2,3,4]
Output: false
Input: [1,2,5,10]
Output: true
function Superincreasing(arr) {
var maxInd = arr.length - 1;
var target;
var sum;
}
Superincreasing(readline());
function Superincreasing(arr) {
function Superincreasing(arr) {
if (arr.length < 2) return false;
if (arr.length === 2) return arr[0] < arr[1];
if (arr[0] >= arr[1]) return false;
Hamming Distance
Examples
Input: ["10011", "10100"]
Output: 3
Input: ["helloworld", "worldhello"]
Output: 8
function HammingDistance(strArr) {
let count = 0;
for (let i = 0; i < strArr[0].length; i++) {
if (strArr[0][i] !== strArr[1][i]) {
count++
}
}
return count;
}
function HammingDistance(strArr) {
var word1 = strArr[0],
word2 = strArr[1],
len = word1.length,
count = 0;
function HammingDistance(strArr) {
var hammingDistance = 0;
for (var i = 0; i < strArr[0].length; i++) {
if (strArr[0][i] !== strArr[1][i]) {
hammingDistance++;
}
}
return hammingDistance;
}
Rectangle Area
Top Rated User Solution
function RectangleArea(strArr) {
var obj = {};
obj.x1 = parseInt(strArr[0].match(/((-*d+)/)[1], 10);
obj.y1 = parseInt(strArr[0].match(/(-*d+))/)[1], 10);
function RectangleArea(strArr) {
let deltaX = 0;
let deltaY = 0;
coords.forEach(function(val){
if (x === val[0]) {
deltaY = Math.abs(val[1] - y);
}
if (y === val[1]) {
deltaX = Math.abs(val[0] - x);
}
});
function RectangleArea(strArr) {
var points = strArr.map(str => str.match(/\d+/g));
var minX = points.map(point => point[0]).sort()[0];
var minY = points.map(point => point[1]).sort()[0];
var maxX = points.map(point => point[0]).sort().reverse()[0];
var maxY = points.map(point => point[1]).sort().reverse()[0];
Bitwise One
Have the function BitwiseOne(strArr) take the array of strings stored in strArr, which will
only contain two strings of equal length that represent binary numbers, and return a final binary
string that performed the bitwise OR operation on both strings. A bitwise OR operation places a
0 in the new string where there are zeroes in both binary strings, otherwise it places a 1 in that
spot. For example: if strArr is ["1001", "0100"] then your program should return the string
"1101"
Examples
Input: ["100", "000"]
Output: 100
Input: ["00011", "01010"]
Output: 01011
VIEW CHALLENGE
function BitwiseOne(strArr) {
var str1 = strArr[0];
var str2 = strArr[1];
var newStr = '';
len = str1.length;
return newStr;
}
function BitwiseOne(strArr) {
var output = '';
for (var i = 0; i < strArr[0].length; i++) {
if (strArr[0][i] === '1' || strArr[1][i] === '1') {
output += '1';
} else {
output += '0';
}
}
return output;
}
function BitwiseOne(strArr) {
Other Products
Examples
Input: [1,4,3]
Output: 12-3-4
Input: [3,1,2,6]
Output: 12-36-18-6
function OtherProducts(arr) {
let holdArray = [];
return holdArray.join('-');
}
function OtherProducts(arr) {
function OtherProducts(arr) {
var products = [];
for (var i = 0; i < arr.length; i++) {
var other = arr.slice(0, i).concat(arr.slice(i + 1));
products.push(product(other));
}
return products.join('-');
}
Wave Sorting
Examples
Input: [0, 1, 2, 4, 1, 1, 1]
Output: false
function WaveSorting(arr) {
newArr = [];
// find the count of the most frequent element, which is the mode
function mostFrequent(arr) {
arr.sort();
var most = 0;
var frequency = 1;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === arr[i + 1]) {
frequency++;
if (frequency > most) {
most = frequency;
}
} else {
frequency = 1;
}
}
return most;
}
function WaveSorting(arr) {
// as long as we can put some other number in between the same number, it works
return mostFrequent(arr) < (arr.length / 2);
}
Array Matching
Examples
function ArrayMatching(strArr) {
strArr = strArr.map(val => val.replace(/[[]]/g, '')
.split(/s*,s*/).map(val1 => parseInt(val1, 10)));
function ArrayMatching(strArr) {
return results.join('-');
}
function ArrayMatching(strArr) {
arr1 = strArr[0].match(/\d+/g).map(Number);
arr2 = strArr[1].match(/\d+/g).map(Number);
Binary Reversal
Examples
Input: "213"
Output: 171
Input: "4567"
Output: 60296
function BinaryReversal(str) {
function BinaryReversal(str) {
function toBinary(str) {
result = Number(str).toString(2);
// pad left with leading 0's to make it a multiple of 8 digits...
if (result.length % 8 !== 0)
return new Array(8 - (result.length % 8)).fill(0).join('') + result;
else return result;
}
function toDecimal(str) {
return parseInt(str, 2);
}
function BinaryReversal(str) {
//return toBinary(str);
var reverse = toBinary(str).split('').reverse().join('');
return toDecimal(reverse);
}
Examples
Input: [9, 9, 4, 2]
Output: 1
Input: [10, 22, 9, 33, 21, 50, 41, 60, 22, 68, 90]
Output: 7
function LongestIncreasingSequence(arr) {
let len = arr.length;
let arrHolder = [];
//take out all the arrays that are not ascending (use the ascend() to determine)
arrHolder = arrHolder.filter(val => ascend(val));
function ascend(inputArr) {
let arrlen = inputArr.length;
return inputArr.every((val, ind) => {
if (ind < arrlen - 1) {
return val < inputArr[ind + 1];
}
return true;
});
}
// https://stackoverflow.com/questions/2631726/how-to-determine-the-longest-
increasing-subsequence-using-dynamic-programming
// Used algorithm from here
function LongestIncreasingSequence(arr) {
return lis.length;
function increasing(arr) {
return arr.every(function(value, index, arr) {
var prev = (index === 0) ? 0: arr[index - 1];
return prev < value;
});
}
function LongestIncreasingSequence(arr) {
var longest = 0;
Even Pairs
Examples
Input: "3gy41d216"
Output: true
Input: "f09r27i8e67"
Output: false
function EvenPairs(str) {
return regEx.test(str);
function EvenPairs(str) {
}
}
function EvenPairs(str) {
var numbers = str.match(/\d+/g);
for (var number of numbers) {
if (hasEvenPairs(number)) return true;
}
return false;
}
Examples
Input: 2
Output: 3
Input: 180
Output: 181
function NextPalindrome(num) {
while (true) {
numString = count.toString();
revString = numString.split('')
.reverse()
.join('');
if (revString === numString) return parseInt(numString, 10);
count++;
}
}
function NextPalindrome(num) {
function isPalindrome(str) {
for (let i = 0, max = Math.floor(str.length/2); i < max; i++) {
if (str[i] !== str[str.length-1-i]) {
return false;
}
}
return true;
}
}
function isPalindrome(num) {
var numStr = num.toString();
return numStr.split('').reverse().join('') === numStr;
}
function NextPalindrome(num) {
var nextNum = num + 1;
while (!isPalindrome(nextNum)) {
nextNum++;
}
return nextNum;
}
Examples
Input: 453857
Output: 85
Input: 363223311
Output: 63
function LargestPair(num) {
function LargestPair(num) {
num = num.toString();
let largestNum = 0;
for (let i = 1; i < num.length; i++) {
let testNum = parseInt(num[i-1] + num[i]);
if (testNum > largestNum) {
largestNum = testNum;
}
}
return largestNum;
}
function LargestPair(num) {
var max = 0;
var numStr = num.toString();
Nonrepeating Character
Examples
Input: "abcdef"
Output: a
function NonrepeatingCharacter(str) {
function NonrepeatingCharacter(str) {
str = str.replace(/\s+/g, '');
var counts = {};
Two Sum
Have the function TwoSum(arr) take the array of integers stored in arr, and determine if any
two numbers (excluding the first element) in the array can sum up to the first element in the
array. For example: if arr is [7, 3, 5, 2, -4, 8, 11], then there are actually two pairs that sum to
the number 7: [5, 2] and [-4, 11]. Your program should return all pairs, with the numbers
separated by a comma, in the order the first number appears in the array. Pairs should be
separated by a space. So for the example above, your program would return: 5,2 -4,11
If there are no two numbers that sum to the first element in the array, return -1
Examples
function TwoSum(arr) {
arr.forEach(item => {
const compliment = answer - item;
if (history.has(compliment)) {
matches.push([item, compliment]);
} else {
history.add(item);
}
});
function TwoSum(arr) {
var pairs = [];
var sum = arr[0];
var rest = arr.slice(1);
pairs = findPairs(rest, sum);
Have the function BitwiseTwo(strArr) take the array of strings stored in strArr, which will
only contain two strings of equal length that represent binary numbers, and return a final binary
string that performed the bitwise AND operation on both strings. A bitwise AND operation
places a 1 in the new string where there is a 1 in both locations in the binary strings, otherwise
it places a 0 in that spot. For example: if strArr is ["10111", "01101"] then your program
should return the string "00101"
Examples
Input: ["100", "000"]
Output: 000
Input: ["10100", "11100"]
Output: 10100
function BitwiseTwo(strArr) {
let num1 = strArr[0];
let num2 = strArr[1];
let len = strArr[0].length;
let resStr = '';
function BitwiseTwo(strArr) {
function BitwiseTwo(strArr) {
var result = '';
for (var i = 0; i < strArr[0].length; i++) {
if (strArr[0][i] === '1' && strArr[1][i] === '1') {
result += '1';
} else {
result += '0';
}
}
return result;
}
Have the function PowerSetCount(arr) take the array of integers stored in arr, and return
the length of the power set (the number of all possible sets) that can be generated. For
example: if arr is [1, 2, 3], then the following sets form the power set:
[]
[1]
[2]
[3]
[1, 2]
[1, 3]
[2, 3]
[1, 2, 3]
You can see above all possible sets, along with the empty set, are generated. Therefore, for this
input, your program should return 8.
Examples
Input: [1, 2, 3, 4]
Output: 16
Input: [5, 6]
Output: 4
function PowerSetCount(arr) {
let len = arr.length;
return Math.pow(2, len);
}
function PowerSetCount(arr) {
return Math.pow(2, arr.length);
}
function PowerSetCount(arr) {
return Math.pow(2, arr.length);
}
Product Digits
Examples
Input: 6
Output: 2
Input: 23
Output: 3
function ProductDigits(num) {
let pivot = Math.sqrt(num);
let value = num.toString().length + 1;
for (let i = 1; i <= pivot; i++) {
if (num % i === 0) {
let maxFactor = i;
maxCompFactor = num / maxFactor;
maxFactorString = maxFactor.toString();
maxCompFactorString = maxCompFactor.toString();
let totalLength = maxFactorString.length +
maxCompFactorString.length;
if (totalLength < value) {
value = totalLength;
}
}
}
return value;
}
function ProductDigits(num) {
let pf = primeFactors(num);
if (pf.length === 1) {
return pf[0].toString().length + 1;
}
function primeFactors(num) {
if (num === 1) return 1;
let pf = [];
function getDivisors(num) {
var divisors = [1];
for (var i = 2; i <= num / 2; i++) {
if (num % i === 0) {
divisors.push(i);
}
}
divisors.push(num);
return divisors;
}
function ProductDigits(num) {
var divisors = getDivisors(num);
var pairs = [];
Palindrome Creator
The input will only contain lowercase alphabetic characters. Your program should always
attempt to create the longest palindromic substring by removing 1 or 2 characters (see second
sample test case as an example). The 2 characters you remove do not have to be adjacent in
the string.
Examples
Input: "mmop"
Output: not possible
Input: "kjjjhjjj"
Output: k
function PalindromeCreator(str) {
let len = str.length;
//test to see if it is a Palindrome already
if (isPalindrome(str)) {
return 'palindrome';
}
for (let i = 0; i < len; i++) {
let testArray = str.split('');
let res = testArray.splice(i, 1);
let newString = testArray.join('');
if (isPalindrome(newString)) {
console.log('one');
return res.join('');
}
}
for (let i = 0; i < len; i++) {
let res = [];
for (let j = i; j < len - 1; j++) {
let testArray = str.split('');
res[0] = testArray.splice(i, 1);
res[1] = testArray.splice(j, 1);
let newString = testArray.join('');
if(isPalindrome(newString)) {
return res.join('');
}
}
}
return 'not possible';
}
//----------------helpers---------------------------
function isPalindrome(str) {
let newStr = str.split('').reverse().join('');
if (newStr === str) {
return true;
}
return false;
}
if (isPalindrome(str)) {
return 'palindrome';
}
// Create combos
let combos = [];
for (let i = 0, max = Math.pow(2, str.length); i < max; i++) {
let combo = i.toString(2);
if (palindromeCombos.length === 0) {
return 'not possible';
}
// Sort so first two letters found will be returned first for when
// there are multiple values
palindromeCombos.sort(function(a,b){
return parseInt(a,2) < parseInt(b,2);
});
return result;
function isPalindrome(str) {
return (str === str.split('').reverse().join('')) ? true : false;
}
function isPalindrome(str) {
return str === str.split('').reverse().join('');
}
function PalindromeCreator(str) {
if (isPalindrome(str)) return 'palindrome';
The goal of your program is to return the decimal equivalent of the Roman numeral given. For
example: if str is "XXIV" your program should return 24
Examples
Input: "IV"
Output: 4
Input: "XLVI"
Output: 46
function BasicRomanNumerals(str) {
let letterObj = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
let res = 0;
let len = str.length;
for (let i = 0; i < len; i++) {
if (!letterObj[str[i + 1]] || letterObj[str[i]] >= letterObj[str[i +
1]]) {
res += letterObj[str[i]];
} else {
res += (letterObj[str[i + 1]] - letterObj[str[i]]);
i++;
}
}
return res;
}
function BasicRomanNumerals(str) {
/*
Symbol I V X L C D M
Value1 5 10 50 100 500 1,000
*/
const ROMAN_I = 1;
const ROMAN_V = 5;
const ROMAN_X = 10;
const ROMAN_L = 50;
const ROMAN_C = 100;
const ROMAN_D = 500;
const ROMAN_M = 1000;
let sum = 0;
switch(symbol) {
case 'I':
if (nextSymbol === 'V') {
sum += ROMAN_V - ROMAN_I;
i++;
} else if (nextSymbol === 'X') {
sum += ROMAN_X - ROMAN_I;
i++;
} else {
sum += ROMAN_I;
}
break;
case 'V':
sum += ROMAN_V;
break;
case 'X':
if (nextSymbol === 'L') {
sum += ROMAN_L - ROMAN_X;
i++;
} else if (nextSymbol === 'C') {
sum += ROMAN_C - ROMAN_X;
i++;
} else {
sum += ROMAN_X;
}
break;
case 'L':
sum += ROMAN_L;
break;
case 'C':
if (nextSymbol === 'D') {
sum += ROMAN_D - ROMAN_C;
i++;
} else if (nextSymbol === 'M') {
sum += ROMAN_M - ROMAN_C;
i++;
} else {
sum += ROMAN_C;
}
break;
case 'D':
sum += ROMAN_D;
break;
case 'M':
sum += ROMAN_M;
break;
default:
// Illegal char or space
break;
}
}
return sum;
}
function BasicRomanNumerals(str) {
var decimals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
var romans = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV',
'I'];
var output = 0;
Food Distribution
For example: if arr is [5, 3, 1, 2, 1], this means you have 5 sandwiches to give out. You can
distribute them in the following order to the people: 2, 0, 1, 0. Giving these sandwiches to the
people their hunger levels now become: [1, 1, 1, 1]. The difference between each pair of people
is now 0, the total is also 0, so your program should return 0. Note: You may not have to give
out all, or even any, of your sandwiches to produce a minimized difference.
Another example: if arr is [4, 5, 2, 3, 1, 0] then you can distribute the sandwiches in the
following order: [3, 0, 1, 0, 0] which makes all the hunger levels the following: [2, 2, 2, 1, 0]. The
differences between each pair of people is now: 0, 0, 1, 1 and so your program should return the
final minimized difference of 2.
Examples
Input: [5, 2, 3, 4, 5]
Output: 1
Input: [3, 2, 1, 0, 4, 1, 0]
Output: 4
function FoodDistribution(arr) {
let treats = arr.shift();
let myArray = arr.slice(0);
let arrMin = arr.sort((val1, val2) => val2 - val1).pop()
let len = myArray.length;
//check to see if we have enough treats to get everybody to the current best
level
let testCount = myArray.reduce((val1, val2) => {
return val1 + val2 - arrMin;
}, 0);
if (testCount <= treats) {
return 0;
}
let count = 0;
for (let i = 0, len = valQuantArr.length; i < len - 1; i++) {
count += Math.abs(valQuantArr[i].value - valQuantArr[i + 1].value);
}
return count;
}
//-----------------helpers-----------------------
flattenMid = (arr, treats, q) => {
let index = 0;
while (treats > 0 && index > -1) {
index = arr.findIndex((val, ind) => {
return val.quant <= q && ind >= 1 && ind < arr.length - 1 &&
val.value > arr[ind - 1].value && val.value > arr[ind + 1].value;
});
if (index >= 0) {
arr[index].value --;
treats -= q;
}
}
return [objectify(arr), treats];
}
//turns an array into an object with the value equal to the number, and the
//quant being the number of times it occurs in a row
objectify = (array) => {
//if it is the array of numbers
if (typeof array[0] === 'number') {
let target = [];
let counter = 0;
for (let i = 0, len = array.length; i < len; i++) {
let val = array[i];
counter++;
if (array[i] === array[i + 1]) {
continue;
} else {
target.push({
value: array[i],
quant: counter
});
counter = 0;
}
}
return target;
} else {
//if it is an array of objects, turn it into an array of numbers, and
//then run it through the objectify method
let targetArray = [];
array.forEach (val => {
while (val.quant) {
targetArray.push (val.value);
val.quant--;
}
});
return objectify(targetArray);
}
};
function FoodDistribution(arr) {
// Also can add a check here to remove sandwiches that would put hunger < 0
return lowestHungerDifference;
function getHungerDifference(arr){
let diff = 0;
for (let i = 1; i < arr.length; i++) {
diff += Math.abs(arr[i] - arr[i-1]);
}
return diff;
}
function FoodDistribution(arr) {
var N = arr[0];
var hungerLevels = arr.slice(1);
while (N > 0) {
var maxDifference = 0;
// the index to be fed a sandwich next
var mostNeeded = -1;
for (var i = 0; i < hungerLevels.length - 1; i++) {
var difference = Math.abs(hungerLevels[i + 1] - hungerLevels[i]);
if (difference > maxDifference) {
maxDifference = difference;
mostNeeded = (hungerLevels[i + 1] > hungerLevels[i]) ? (i + 1) : i;
}
}
// now we know who needs the sandwich so badly. give it away
if (mostNeeded === -1) {
// the adjacent differences are all 0's, so stop giving the sandwiches
away
return 0;
} else {
hungerLevels[mostNeeded] -= 1;
N--;
}
}
return sumOfDifferences;
}
Three Sum
Have the function ThreeSum(arr) take the array of integers stored in arr, and determine if
any three distinct numbers (excluding the first element) in the array can sum up to the first
element in the array. For example: if arr is [8, 2, 1, 4, 10, 5, -1, -1] then there are actually three
sets of triplets that sum to the number 8: [2, 1, 5], [4, 5, -1] and [10, -1, -1]. Your program should
return the string true if 3 distinct elements sum to the first element, otherwise your program
should return the string false. The input array will always contain at least 4 elements.
Examples
function ThreeSum(arr) {
// Generate combos
let combos = [];
for (let i = 0, max = Math.pow(2, arr.length); i < max; i++) {
let combo = i.toString(2);
if (digitsSum !== 3) {
continue;
}
// Pad digits
while (combo.length < arr.length) {
combo = '0' + combo;
}
combos.push(combo);
}
// Test combos
let goodCombos = [];
combos.forEach(function(combo){
let sum = 0;
for (let i = 0; i < combo.length; i++) {
if (combo[i] === '1') {
sum += parseInt(arr[i]);
}
}
if (sum === answer) {
goodCombos.push(combo);
}
});
function ThreeSum(arr) {
var sum = arr[0];
var numbers = arr.slice(1);
Correct Path
For example: if str is "r?d?drdd" then your program should output the final correct string that
will allow a path to be formed from the top left of a 5x5 grid to the bottom right. For this input,
your program should therefore return the string rrdrdrdd. There will only ever be one correct
path and there will always be at least one question mark within the input string.
Examples
Input: "???rrurdr?"
Output: dddrrurdrd
Input: "drdr??rrddd?"
Output: drdruurrdddd
function CorrectPath(str) {
//create an array to hold the positions of the question marks
let blankArray = [];
//put the position of the question marks into the array
str.split('').forEach((val, ind) => {
if (val === '?') {
blankArray.push(ind);
}
});
//we are going to try each possibility until we find one that works, This
will be 4^num permutations
let total = Math.pow(4, num);
function CorrectPath(str) {
// Try paths
combos.forEach(function(combo){
let comboArray = combo.split('');
let tryPath = '';
for (let i = 0; i < str.length; i++) {
if (str[i] === '?') {
let direction = comboArray.shift();
switch (direction) {
case '0': // right
tryPath += 'r';
break;
case '1': // down
tryPath += 'd';
break;
case '2': // left
tryPath += 'l';
break;
case '3': // up
tryPath += 'u';
break;
default:
// Should never happen
break;
}
} else {
tryPath += str[i];
}
}
if (pathGood(tryPath)) {
goodPaths.push(tryPath);
}
});
// goodPaths according to the spec shold only ever be === 1, but this code can
handle more true cases
return goodPaths[0];
let grid = [
[1,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0]
]; // goal 4,4
}
}
function findMissingChars(str) {
// first, generate all possible cases: replacing ? with directions
var permutations = [''];
for (var i = 0; i < str.length; i++) {
if (str[i] === '?') {
var newPermutations = [];
permutations.forEach(function(permutation) {
newPermutations.push(permutation + 'u');
newPermutations.push(permutation + 'd');
newPermutations.push(permutation + 'l');
newPermutations.push(permutation + 'r');
});
permutations = newPermutations;
} else {
permutations = permutations.map(permutation => permutation + str[i]);
}
}
function CorrectPath(str) {
var validPaths = findMissingChars(str);
Scale Balancing
There will only ever be one unique solution and the list of available weights will not be empty. It
is also possible to add two weights to only one side of the scale to balance it. If it is not
possible to balance the scale then your program should return the string not possible.
Examples
function ScaleBalancing(strArr) {
let objects = strArr[0].substr(1, strArr[0].length-2).split(', ').map(object =>
parseInt(object));
let weights = strArr[1].substr(1, strArr[1].length-2).split(', ').map(weight =>
parseInt(weight));
/*
Generate all possible combinations of weights AND permutations of left/right
- 3^n time
0 - Weight not in use
1 - Weight on left side
2 - Weight on right side
*/
let combos = [];
for (let i = 0, max = Math.pow(3, weights.length); i < max; i++) {
let combo = i.toString(3);
let numWeights = combo.split('').reduce((a,v) => a + (parseInt(v) > 0 | 0),
0);
// Pad
while (combo.length < weights.length) {
combo = '0' + combo;
}
combos.push(combo);
}
// console.log(combos);
// Test combos
let goodCombos = [];
combos.forEach(function(combo){
let left = objects[0];
let right = objects[1];
if (goodCombos.length === 0) {
return 'not possible';
}
// Sort first by number of physical weights used, then by total weight if there
are multiple sets
goodCombos.sort(function(a, b){
let aCount = a.split('').reduce((ac,v) => ac + (parseInt(v) > 0 | 0), 0);
let bCount = b.split('').reduce((ac,v) => ac + (parseInt(v) > 0 | 0), 0);
function ScaleBalancing(strArr) {
var weights = strArr[1].match(/\d+/g).map(Number);
var weightsOnScale = strArr[0].match(/\d+/g).map(Number);
var leftWeight = weightsOnScale[0];
var rightWeight = weightsOnScale[1];
// no solution
return 'not possible';
}
Examples
Input: "21aa3a ggg4g4g6ggg"
Output: false
function ThreeNumbers(str) {
words.forEach(function(word){
let numbers = 0;
let threeAdjacent = false;
let usedDigits = '';
for (let i = 0; i < word.length; i++) {
// Check for used digits
if (usedDigits.includes(word[i])) {
// used! fail
result = false;
}
if (DIGITS.includes(word[i])) {
numbers++;
usedDigits += word[i];
if (numbers === 3) {
if (DIGITS.includes(word[i-1]) && DIGITS.includes(word[i-2])) {
threeAdjacent = true;
}
}
}
// Check for 3 adjacent preceding digits
}
} else {
result = false;
}
});
return result;
}
function ThreeNumbers(str) {
var words = str.split(' ');
var numbersOfWords = words.map(word => word.match(/\d+/g));
return true;
}
function ThreeNumbers(str) {
Alphabet Searching
Examples
Input: "abcdefghijklmnopqrstuvwxyyyy"
Output: false
Input: "abc123456kmo"
Output: false
function AlphabetSearching(str) {
str = str.toLowerCase();
for (let i = 97; i < 97 + 26; i++) {
let char = String.fromCharCode(i);
if (!str.includes(char)) {
return false;
}
}
return true;
}
function AlphabetSearching(str) {
function isAlpha(char) {
return /[A-Za-z]/.test(char);
}
function AlphabetSearching(str) {
var foundLetters = [];
for (var i = 0; i < str.length; i++) {
if ( isAlpha(str[i]) && (foundLetters.indexOf(str[i]) === -1) ) {
foundLetters.push(str[i]);
}
}
return foundLetters.length === 26;
}
Examples
function TimeDifference(strArr) {
//times will hold our time differences
let times = [];
let newStrArr = strArr.map (val => {
let matches = val.match(/^(\d+):(\d+)([ap]m)$/);
let hours = parseInt(matches[1], 10);
let minutes = parseInt(matches[2], 10);
let half = matches[3];
if (half === 'am' && hours === 12) {
hours = 0;
}
if (half === 'pm' && hours !== 12) {
hours += 12;
}
return (hours * 60 + minutes);
})
.sort((a, b) => { return a - b});
//tricky - second example shows that we have to consider the earliest time both
on day 0 and day 1
newStrArr.push(newStrArr[0] + 24 * 60);
function TimeDifference(strArr) {
return smallestDifference;
}
function TimeDifference(strArr) {
let array = strArr.map(value => {
let matches = value.match(/^(\d+):(\d+)([ap]m)$/);
let h = parseInt(matches[1], 10);
let m = parseInt(matches[2], 10);
if (matches[3] === 'am' && h === 12) {
h = 0;
} else if (matches[3] === 'pm' && h !== 12) {
h += 12;
}
return (60 * h + m);
}).sort(function(a, b) {
return a - b;
});
array.push(array[0] + 24 * 60);
let times = [];
for (let i = 0; i < array.length - 1; i++) {
times.push(array[i+1] - array[i]);
}
return Math.min(...times);
}
// keep this function call here
TimeDifference(readline());
Triangle Row
Examples
Input: 1
Output: 2
Input: 2
Output: 4
function TriangleRow(num) {
return Math.pow(2, num);
}
console.log(TriangleRow(5));
function TriangleRow(num) {
}
// keep this function call here
TriangleRow(readline());
function TriangleRow(num) {
// the easy answer - it always sums up to n^2
//return num * num;
Vowel Square
a b c d
e i k r
o u f j
Within this matrix there is a 2x2 square of vowels starting in the second row and first column,
namely, ei, ou. If a 2x2 square of vowels is found your program should return the top-left
position (row-column) of the square, so for this example your program should return 1-0. If no
2x2 square of vowels exists, then return the string not found. If there are multiple squares of
vowels, return the one that is at the most top-left position in the whole matrix. The input matrix
will at least be of size 2x2.
Examples
Input: ["gg", "ff"]
Output: not found
function VowelSquare(strArr) {
strArr = strArr.map(val => {
return val.toLowerCase().replace(/[aeiou]/g, "!");
})
for (let r = 0, len = strArr.length; r < len - 1; r++) {
for (let c = 0, len = strArr[0].length; c < len - 1; c++) {
if (checkPoint(strArr, [r, c])) {
return `${r}-${c}`;
}
}
}
return 'not found'
function VowelSquare(strArr) {
function isVowel(letter) {
const VOWELS = 'aeiou';
return VOWELS.includes(letter);
}
}
function VowelSquare(strArr) {
var matrix = strArr.map(row => row.split(''));
Closest Enemy
Have the function ClosestEnemy(arr) take the array of numbers stored in arr and from the
position in the array where a 1 is, return the number of spaces either left or right you must
move to reach an enemy which is represented by a 2. For example: if arr is [0, 0, 1, 0, 0, 2, 0, 2]
then your program should return 3 because the closest enemy (2) is 3 spaces away from the 1.
The array will contain any number of 0's and 2's, but only a single 1. It may not contain any 2's
at all as well, where in that case your program should return a 0.
Examples
Input: [1, 0, 0, 0, 2, 2, 2]
Output: 4
Input: [2, 0, 0, 0, 2, 2, 1, 0]
Output: 1
function ClosestEnemy(arr) {
if (!arr.includes(2)) {
return 0;
}
loc1 = arr.findIndex(val => {
return val === 1;
});
function ClosestEnemy(arr) {
// Search right
let deltaRight = undefined;
for (let i = hero+1; i < arr.length; i++) {
if (arr[i] === 2) { // Found enemy
deltaRight = i - hero;
break;
}
}
// Search left
let deltaLeft = undefined;
for (let i = hero-1; i >= 0; i--) {
if (arr[i] === 2) { // Found enemy
deltaLeft = hero - i;
break;
}
}
function ClosestEnemy(arr) {
// index of 1
var me = arr.indexOf(1);
var minimumDistance = arr.length;
Closest Enemy II
0 0 0 0
1 0 0 0
0 0 0 2
0 0 0 2
For this input your program should return 2 because the closest enemy (2) is 2 spaces away
from the 1 by moving left to wrap to the other side and then moving down once. The array will
contain any number of 0's and 2's, but only a single 1. It may not contain any 2's at all as well,
where in that case your program should return a 0.
Examples
function ClosestEnemyII(strArr) {
//step one - return 0 if there is no 2 in the array
let twosies = strArr.filter(val => {
return val.includes("2");
});
if (!twosies.length) {
return 0;
}
//step two - get the coordinates of the 1 (targetX, targetY)
targetY = strArr.findIndex(val => {
return val.includes('1');
});
targetX = strArr[targetY].search(/1/);
//step three find the smallest path to a 2
let res = strArr.length * strArr[0].length;
//--------------------helpers----------------------
//despite the name, use for column and row distance
function rowDist(y, x, len) {
return Math.min(Math.abs(x - y), Math.abs(y - x + len));
}
function ClosestEnemyII(strArr) {
// Find hero
let heroY = -1;
let heroX = -1;
for (let i = 0; i < strArr.length; i++) {
let result = strArr[i].indexOf(1);
if (result > -1) {
heroX = result;
heroY = i;
}
}
if (enemies.length === 0) {
return 0;
}
//console.log(enemies);
let closestDistance = Number.MAX_SAFE_INTEGER;
return closestDistance;
// find the distance between two elements with given [row, column] indices
function getDistance(matrixSize, indices1, indices2) {
var rowDistance = Math.min(Math.abs(indices2[0] - indices1[0]),
Math.abs(indices1[0] - (indices2[0] - matrixSize)));
var columnDistance = Math.min(Math.abs(indices2[1] - indices1[1]),
Math.abs(indices1[1] - (indices2[1] - matrixSize)));
return rowDistance + columnDistance;
}
function ClosestEnemyII(strArr) {
var matrix = strArr.map(line => line.split('').map(Number));
var minDistance = matrix.length * 2;
// location of me: 1
var meIndices;
// locations of enemies: 2's
var enemiesIndices = [];
Examples
Input: "5556293383563665"
Output: false
Input: "5788888888882339999"
Output: true
function NumberStream(str) {
for (let i = 2; i < 10; i++) {
let iChar = i.toString();
let needle = iChar.repeat(i);
if (str.indexOf(needle) !== -1) {
return true;
}
}
// code goes here
return false;
function NumberStream(str) {
function NumberStream(str) {
// generate patterns first
var patterns = [];
for (var i = 1; i < 10; i++) {
patterns.push(String(i).repeat(i));
}
Largest Four
Have the function LargestFour(arr) take the array of integers stored in arr, and find the
four largest elements and return their sum. For example: if arr is [4, 5, -2, 3, 1, 2, 6, 6] then the
four largest elements in this array are 6, 6, 4, and 5 and the total sum of these numbers is 21,
so your program should return 21. If there are less than four numbers in the array your program
should return the sum of all the numbers in the array.
Examples
Input: [1, 1, 1, -5]
Output: -2
Input: [0, 0, 2, 3, 7, 1]
Output: 13
function LargestFour(arr) {
let newArr = arr.sort((val1, val2) => {
return val2 - val1;
})
.splice(0, 4);
return newArr.reduce((val1, val2) => {
return val1 + val2;
}, 0);
}
function LargestFour(arr) {
function LargestFour(arr) {
return arr.sort((a, b) => a < b).slice(0, 4).reduce((sum, v) => sum + v, 0);
}
Distinct Characters
Examples
Input: "12334bbmma:=6"
Output: true
Input: "eeeemmmmmmmmm1000"
Output: false
function DistinctCharacters(str) {
let mySet = new Set(str.split(''));
return mySet.size >= 10 ? true : false
}
function DistinctCharacters(str) {
function DistinctCharacters(str) {
var distincts = {};
Questions Marks
Input: "aa6?9"
Output: false
Input: "acc?7??sss?3rr1??????5"
Output: true
function QuestionsMarks(str) {
let numPlaces = [];
//presumption of false, until flag is turned true
let flag = false;
Camel Case
Examples
Input: "a b c d-e-f%g"
Output: aBCDEFG
function CamelCase(str) {
let strArr = str.split(/[^a-zA-Z]/);
strArr = strArr.map((val, ind) => {
val = val.toLowerCase();
if (ind) {
valArr = val.split('');
valArr[0] = valArr[0].toUpperCase();
return valArr.join('');
}
return val;
})
return strArr.join('');
}
ASCII Conversion
Examples
Input: "hello world"
Output: 104101108108111 119111114108100
Input: "abc **"
Output: 979899 4242
function ASCIIConversion(str) {
let myArr = str.split(' ').map(val => {
return val.split('').map(val2 => {
return val2.charCodeAt(0);
}).join('')
}).join(' ');
return myArr;
}
Examples
Input: 2222220222
Output: true
Input: 20864646452
Output: false
function SimpleEvens(num) {
return num.toString(10).search(/[13579]/) === -1 ? 'true' : 'false';
}
SimpleEvens(readline());
Snake Case
For example: if str is "BOB loves-coding" then your program should return the
string bob_loves_coding.
Examples
Input: "a b c d-e-f%g"
Output: a_b_c_d_e_f_g
function SnakeCase(str) {
return str.split(/[^a-zA-Z]/).map(val => {return
val.toLowerCase()}).join('_');
}
SnakeCase(readline());
Find Intersection
For example: if strArr contains ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"] the output should return
"1,4,13" because those numbers appear in both strings. The array given will not be empty, and
each string inside the array will be of numbers sorted in ascending order and may contain
negative numbers.
Examples
Examples
Input: [2, 2, 2, 2, 4, 1]
Output: false
String Merge
Examples
Input: "aaa*bbb"
Output: ababab
Input: "123hg*aaabb"
Output: 1a2a3ahbgb
function StringMerge(str) {
const cleanString = str.replace(/[^\w*]/g, '');
const len = (cleanString.length - 1) / 2;
let newString = '';
const arr = str.split('*');
One Decremented
Examples
Input: "56"
Output: 0
Input: "9876541110"
Output: 6
function OneDecremented(num) {
let counter = 0;
let arr = num.toString().split('');
arr.forEach((val, ind) => {
if (parseInt(val, 10) - parseInt(arr[ind + 1], 10) === 1) {
counter++;
}
})
return counter;
}
Examples
Input: [5, 7, 16, 1, 2]
Output: 7
Input: [1, 1, 1, 2]
Output: 1
function ElementMerger(arr) {
if (arr.length === 1) {
return arr[0];
} else {
newArr = [];
arr.forEach((val, ind) => {
if (ind < arr.length - 1) {
newArr.push(Math.abs(val - arr[ind + 1]));
}
})
return ElementMerger(newArr);
}
}
ElementMerger(readline());
GCF
Have the function GCF(arr) take the array of numbers stored in arr which will always contain
only two positive integers, and return the greatest common factor of them. For example:
if arr is [45, 12] then your program should return 3. There will always be two elements in the
array and they will be positive integers.
Examples
Input: [1, 6]
Output: 1
Input: [12, 28]
Output: 4
function GCF(arr) {
let res = null;
let max = Math.max(...arr);
let min = Math.min(...arr);
for (let i = 1; i <= min; i++) {
if (max % i === 0 && min % i === 0) {
res = i;
}
}
return res;
}
Serial Number
1. It needs to contain three sets each with three digits (1 through 9) separated by a period.
2. The first set of digits must add up to an even number.
3. The second set of digits must add up to an odd number.
4. The last digit in each set must be larger than the two previous digits in the same set.
If all the above constraints are met within the string, the your program should return the
string true, otherwise your program should return the string false. For example: if str is
"224.315.218" then your program should return "true".
Examples
Input: "11.124.667"
Output: false
Input: "114.568.112"
Output: true
function SerialNumber(str) {
//check the format of the string
let goal = /^\d{3}\.\d{3}\.\d{3}$/
if (!goal.test(str)) {
return 'false';
}
String Periods
For example: if str is "abcababcababcab" then your program should return abcab because that
is the longest substring that is repeated 3 times to create the final string. Another example:
if str is "abababababab" then your program should return ababab because it is the longest
substring. If the input string contains only a single character, your program should return the
string -1.
Examples
Input: "abcxabc"
Output: -1
Input: "affedaaffed"
Output: -1
function StringPeriods(str) {
// we will use only lengths of substrings that divide evenly into str
const len = str.length;
const pivot = Math.max(Math.trunc(Math.sqrt(len)), len);
for (let i = 2; i <= pivot; i++) {
if (len % i === 0) {
const block = str.slice(0, len / i);
if (block.repeat(i) === str) {
return block;
}
}
}
return -1;
}
Palindrome Swapper
Examples
Input: "anna"
Output: anna
Input: "kyaak"
Output: kayak
function PalindromeSwapper(str) {
let inputArray = str.split('');
let strLen = inputArray.length;
let palTester = function(arr) {
let len = arr.length;
for (let i = 0; i < len; i++) {
if (arr[i] !== arr[len - (1 + i)]) {
return false;
}
}
return true;
}
Remove Brackets
Examples
Input: "(())()((("
Output: 3
Input: "(()("
Output: 2
function RemoveBrackets(str) {
let throwouts = 0;
let counter = 0;
let arr = str.split('');
let len = arr.length;
return throwouts;
}
Command Line
Examples
Star Rating
So your program should return the string "full full half empty empty".
Examples
Input: "0.38"
Output: half empty empty empty empty
Input: "4.5"
Output: full full full full half
function StarRating(str) {
let num = (Math.round(parseFloat(str) * 2)) / 2;
let starString = '';
let half = !(Math.trunc(num) === num);
starString = starString + ' full'.repeat(num);
if (half) {
starString += ' half';
}
return (starString + ' empty'.repeat(5 - num)).trim();
}