Skip to content

Instantly share code, notes, and snippets.

@timkellogg
Last active March 9, 2018 11:43
Show Gist options
  • Save timkellogg/6962d8033d31fe840985 to your computer and use it in GitHub Desktop.
Save timkellogg/6962d8033d31fe840985 to your computer and use it in GitHub Desktop.
Algorithm Practice in Ruby and JavaScript
# Basic math functions added to Array class
class Array
def square
self.map { |n| n * n }
end
def cube
self.map { |n| n * n * n }
end
def average
sum / self.length
end
def sum
self.inject(:+)
end
def even
self.select { |n| n.even? }
end
def odd
self.select { |n| n.odd? }
end
end
var Calculator = {
average: function() {
var sum = 0;
var average = 0;
if (arguments.length === 0) { return average; } else {
for(var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return average = sum / arguments.length;
}
}
};
// remove falsey values from arr
function bouncer(arr) {
// filters element by truth value of it
arr = arr.filter(function(element) {
return element;
});
return arr;
}
# Fix greeting error
class Person
def initialize(name)
@name = name
end
def greet(other_name)
"Hi #{other_name}, my name is #{@name}"
end
end
# Uses the collatz theorem for input
def collatz n
count = 1
result = []
if count == 1
result << n
count += 1
end
until n == 1 do
if n.even?
n = n / 2
result << n
count += 1
else
n = n * 3 + 1
result << n
count += 1
end
end
result.length
end
// Codewars -> create pyramid from numbers
function pattern(n) {
var output = '';
if (n == 1) {
output += '1';
}
else if (n > 1) {
output += '1';
for (var i = 1; i < n; i++) {
var line = Array(i+2).join(i+1)
output += '\n' + line;
}
}
else {
return output;
}
return output;
}
// Codewars challenge to compare whether coupons are valid
function checkCoupon(enteredCode, correctCode, currentDate, expirationDate){
var currentDateParsed = Date.parse(currentDate);
var expirationDateParsed = Date.parse(expirationDate)
if ((enteredCode === correctCode) && (currentDateParsed <= expirationDateParsed)){
return true
} else {
return false
}
}
// Codewars challenge -> decoding morse code
decodeMorse = function(input) {
const MORSE_CODE = {
'-.-.--': '!',
'.-..-.': '"',
'...-..-': '$',
'.-...': '&',
'.----.': '\'',
'-.--.': '(',
'-.--.-': ')',
'.-.-.': '+',
'--..--': ',',
'-....-': '-',
'.-.-.-': '.',
'-..-.': '/',
'-----': '0',
'.----': '1',
'..---': '2',
'...--': '3',
'....-': '4',
'.....': '5',
'-....': '6',
'--...': '7',
'---..': '8',
'----.': '9',
'---...': ':',
'-.-.-.': ';',
'-...-': '=',
'..--..': '?',
'.--.-.': '@',
'.-': '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',
'..--.-': '_',
'...---...': 'SOS'
}
var letters = input.split(' ');
var output = [];
for (var i = 0; i < input.length; i++) {
if (letters[i] === '') {
output.push(' ');
} else {
output.push(MORSE_CODE[letters[i]]);
}
}
return output.join('');
}
// finds and delete elements passed in the first param from those passed in 2,3
function destroyer(arr) {
// store variables; if try to access arguments[1]/2 in isntKey it treats that as in the function scope so defined above
var list = arguments[0];
var key1 = arguments[1];
var key2 = arguments[2];
// callback function to test if key passes condition
function isntKey(value) {
if (value !== key1 && value !== key2) {
return value;
}
}
// filters array as variable filtered
return filtered = list.filter(isntKey);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
# Removes vowels from string
def disemvowel(str)
str.chars.reject { |char| char.downcase =~ /[aeiou]/ }.join
end
// checks to see if str ends with target
function end(str, target) {
// clears whitespace
var noWhiteSpace = str.replace(' ', '');
// if removing the whitespace doesn't alter the str, it's one word
if (str === noWhiteSpace) {
// set the last letter to be the str at the -1 index
var lastLetter = str.slice(-1);
// when target is the same as the last letter
if (target === lastLetter) {
return true;
} else {
return false;
}
// str is multiple words
} else {
// split into words and find last word which is the same as the arr flipped and at the 0th index
var words = str.toLowerCase().split(' ');
var lastWord = words.reverse()[0];
// when target equals last word
if (target === lastWord) {
return true;
} else {
return false;
}
}
}
// Factorializes number
function factorialize(num) {
var product = 1;
for(var i = num; i > 0; i--) {
product *= i;
}
return product;
}
// finds the appropriate place for a num to slot into a given arr
function where(arr, num) {
arr.push(num);
return arr.sort().indexOf(num);
}
// Codewars challenge -> find and replace 2 with t
function tea42(input) {
return String(input).replace(/2/g, 't');
}
def generateHashtag str
if str.length > 140 || str == ''
false
else
new_str = str.split(' ').map(&:capitalize).join
new_str = "##{new_str}" if str.chars.first != '#'
end
end
# Greets enthusiastically
def greet(name)
"Hello " << name.capitalize << "!"
end
# Finds if isogram
def is_isogram(string)
string.downcase.chars.uniq.join.eql? string.downcase
end
// This function loops through multidimensional arrays (2 deep) and returns an array of the highest number within each array
function largestOfFour(arr) {
// create variables of largestNum and result to store each largestNum
var largestNum = 0;
var result = [];
// loop through outer arrays
for(var i = 0; i < arr.length; i++ ) {
// loop through inner arrays
for(var j = 0; j < arr[i].length; j++ ) {
// if the number is greater than the largestNum, set the largestNum to equal it
if (arr[i][j] > largestNum) {
largestNum = arr[i][j];
}
}
// push final value of largestNum in sub-arr to result
result.push(largestNum);
}
// return resulting arr
return result;
}
// Finds the longest word in a string
function findLongestWord(str) {
var words = str.split(' ');
var longestWord = "";
for(var word in words) {
if (words[word].length >= longestWord.length) {
longestWord = words[word];
} else {
console.log("skipped" + word);
}
}
return longestWord.length;
}
# Duh, it multiplies (easiest challenge)
def multiply a, b
a * b
end
// matches characters in first index of arr by characters in second index of arr
function mutation(arr) {
// clean and sort variables for easier regex matching and avoiding case sensitivity (instead of in regex)
var text = arr[0].toLowerCase().split('').sort().join('');
var searchChars = arr[1].toLowerCase().split('').sort().join('');
// create a new regular expression of search characters and store it in variable re
var re = new RegExp(searchChars);
// test whether the text contains the regular expression; if it does return true; else false
return re.test(text);
}
# Finds if a number has a narcissistic structure
def narcissistic?( value )
# Find Narcissistic number
digits = value.to_s.chars.map(&:to_i)
raise_to = digits.length
# One digit value is always Narcissistic
return true if raise_to.eql? 1
# Calculate narcissistic value
narcissistic = digits.map! { |digit| digit ** raise_to }.inject(&:+).to_i
# Compare narcissistic with value
true ? narcissistic.eql?(value) : false
end
#Re-open the class String and add the my_new_method method.
class String
def my_new_method
self.upcase
end
end
function palindrome(str) {
if (str.split('').reverse().join('') === str) { return true }
else { return false };
}
// robost checker -> avoids capitalization, unclean strings, multiple spaces
function palindromeStrong(str) {
// strip punctuation & lower capitalization
var cleanStr = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").toLowerCase();
// remove white space
var noWhite = cleanStr.replace(/ /g, '');
// check string against reversed string
if (noWhite.split('').reverse().join('') === noWhite) {
return true;
} else {
return false;
}
}
// Simple codewars challenge
function playerRankUp (points) {
if (points >= 100)
return "Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up."
else
return false
end
}
# Codewars challenge -> manual exponent method
def power(base, exponent)
return false if exponent < 0
output = []
if exponent == 0
output << 1
end
exponent.times do
output.push base
end
output.inject('*')
end
// repeats a given str for num times
function repeat(str, num) {
if (num > 0) {
var result = [];
for (var i = 0; i < num; i++) {
result.push(str);
}
return result.join('');
} else {
return "";
}
}
# Codewars challenge -> find repeated substring and print out the pattern and the number of times it repeats
# I played a little Ruby Golf with this code to try to condense it.
def f s
container =[]
pattern = ''
s.chars.each_with_index do |char, index|
index != 0 && char == s[0] ? break : pattern << char
end
(s.scan(pattern).count == 1) ? container.push(s) : container.push(pattern)
container.push s.scan(pattern).count
end
# Flip words around center
def reverse_by_center(s)
# find if odd
if s.length.odd?
# find middle
middle = (s.length / 2).ceil
middle_char = s[middle]
# create indeces for slicing
first_end = middle
second_start = middle + 1
# first slice
slice_1 = s[0,first_end]
# second slice
slice_2 = s[second_start, s.length]
# add them
slice_2.concat(middle_char).concat(slice_1)
else
# find endpoints
middle = s.length / 2
second_start = middle
# create slices
slice_1 = s[0, middle]
slice_2 = s[second_start, s.length]
# add them
slice_2.concat(slice_1)
end
end
// reverses a string in js
function reverseString(str) {
return str.split('').reverse().join('');
}
// Codewars challenge -> convert rgba decimals into valid HEX codes
function rgb(r, g, b){
// deal with floats/negative numbers
var R = r < 0 ? 0 : Math.round(r);
var G = g < 0 ? 0 : Math.round(g);
var B = b < 0 ? 0 : Math.round(b);
// deal with numbers greater than 255
if (R > 255) { R = 255 };
if (G > 255) { G = 255 };
if (B > 255) { B = 255 };
// convert to hex and replace default toString output of 0 instead of 00 while making all caps
return ( (R.toString(16) + G.toString(16) + B.toString(16)).replace(/[0]/g, '00')).toUpperCase();
}
// roman numeral converter for X, V, I
// easily extensible to above by adding another loop and a replace function but this is what the challenge required
function convert(num) {
var result = [];
var value = num;
// find all 10s
for(var i = value; i > 10; i -= 10) {
result.push("X");
value -= 10;
}
// find all 5s
for(var j = value; j > 4; j -= 5) {
result.push("V");
value -= 5;
}
// find all 1s
for(var k = value; k > 0; k --) {
result.push("I");
value -= 1;
}
// clean result to switch out shortcut
return result.join('').replace('VIIII', 'IX');
}
convert(36);
convert(9);
// Codewars challenge -> find sum of series: 1 + 1/4 + 1/7 + 1/10 + ...
function SeriesSum(n) {
if (n === 0) {
return n.toFixed(2);
} else {
var denom = 1;
var output = [1];
for (var i = 1; i < n; i++) {
var denom = denom + 3;
output.push(1/denom);
}
return eval(output.join('+')).toFixed(2);
}
};
// removes arr elements specified by second arg
function slasher(arr, howMany) {
// if howMany is given extreme values return empty arr
if (arr.length < howMany || arr.length === howMany) {
return [];
} else if (howMany === 0) {
return arr;
} else {
// return arr with the num of elem cut off
return arr.splice(2, howMany);
}
}
# Sorts the gift code given by challenge
def sort_gift_code code
code.chars.sort.join
end
# Squares every digits in array
def square_digits num
num.to_s.split(//).map { |n| n.to_i * n.to_i }.join.to_i
end
# Squares and then sums values in array
def squareSum(numbers)
numbers.map { |n| n * n }.inject(:+)
end
function solution(pairs) {
results = [];
for(prop in pairs) {
results.push(prop + " = " + pairs[prop]);
}
return results.toString();
}
// sums the values of arr and its intermediate nums
function sumAll(arr) {
// define numberic sorting function
function sortNumber(a,b) {
return a - b;
}
// create variables and arrange arr from lowest to highest
var sorted = arr.sort(sortNumber);
var start = sorted[0];
var finish = sorted[1];
var sum = start;
// loop through and add start, end and intermediaries
for (var i = finish; i > start; i-- ) {
sum += i;
}
return sum;
}
# Finds out if a valid is valid
def isValidWalk(walk)
str = walk.join
return false if str.length < 4
n = str.scan('n').count
w = str.scan('w').count
s = str.scan('s').count
e = str.scan('e').count
if n == s && e == w && str.length <= 10
true
else
false
end
end
// capitalizes first letter of words in string passed
function titleCase(str) {
// split str into lower case words sep by space
var words = str.toLowerCase().split(' ');
// create empty array to push new words into
var capitalWords = [];
// loop over each word
for(var i = 0; i < words.length; i++ ) {
// store the letter equal to the first letter of the word capitalized
var letter = words[i].charAt(0).toUpperCase();
// add that letter and the rest of the word to the array
capitalWords.push(letter + words[i].slice(1));
}
// send back the words into a str
return capitalWords.join(' ');
}
# Puts string into valid titles
def title_case(*args)
title = args[0]
minor_words = args[1]
# downcase minor_word
new = minor_words.split.map(&:downcase) if minor_words
words = title.downcase.split(' ')
if title && minor_words
words.map do |word|
if word == words.first
word.capitalize!
elsif new.include? word
word
else
word.capitalize!
end
end
words.join(' ')
elsif title.empty?
""
else
words.map(&:capitalize).join(' ')
end
end
// Codewars challenge -> takes a number and outputs to binary
function toBinary(n) {
return (n >>> 0).toString(2);
}
// truncates first arg based on second arg
function truncate(str, num) {
// checks invalid conditions
if (str.length === num || str.length < num ) {
return str;
console.log('made it');
} else {
var letters = str.split('');
var last = num - 3;
return letters.slice(0, last).join('') + '...';
}
}
// Compares sum of two arrays with 'anchor elements as the tiebreaker'
function tug_o_war(teams) {
var arr_one = teams[0].reduce(add, 0);
var arr_two = teams[1].reduce(add, 0);
function add(a,b) {
return a + b;
}
if (arr_one > arr_two) {
return "Team 1 wins!";
} else if (arr_one < arr_two) {
return "Team 2 wins!";
} else if (teams[0][0] > teams[1][4]) {
return "Team 1 wins!";
} else if (teams[0][0] < teams[1][4]) {
return "Team 2 wins!";
} else {
return "It's a tie!"
}
}
# return the two oldest/oldest ages within the array of ages passed in.
def two_oldest_ages(ages)
ages.sort.reverse.slice(0,2).reverse!
end
# Spins certain words according to prompt
def spinWords(string)
# Get 5 letter words
words = string.split(' ')
# Reverse first and last of words
words.map! do |word|
if word.length >= 5
word.reverse!
else
word
end
end
words.join(" ")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment