Skip to content

Instantly share code, notes, and snippets.

@ryanomor
ryanomor / changeDirectory.js
Created June 27, 2018 15:25
Create a function that emulates the '../' function in the command line
let str1 = '/a/b/../foo/.///';
let str2 = '/a/./b/../../c';
let str3 = '/home';
let str4 = '/a/../../../b';
let str5 = '/../';
function changeDirectory(str) {
let result = "",
ignoreChars = ['.', '..', '/', '//', ''],
directoryArr = str.split('/');
@ryanomor
ryanomor / isBalance.js
Created May 3, 2018 03:25
Create a function that checks if parentheses and brackets are correctly balanced in a string
var isBalance = function(str) {
if(str.length < 1) return false;
let pairs = {
'(': ')',
'{': '}',
'[': ']'
};
let openers = []; // replace [] with: new Stack
for (let index in str) {
@ryanomor
ryanomor / shortenedString.js
Last active April 23, 2018 16:04
Given a sorted string, either return a shortened version of it where the character is accompanied by an integer representing how many times it's in the string. If the shortened version is longer than the original, return the original
const shortened = str => {
let newStr = "",
charCount = 1;
for (let i = 0; i < str.length; i++) {
if (charCount < 2 && str[i] != str[i + 1]) {
newStr += str[i];
charCount = 1;
} else if (str[i] != str[i + 1]) {
newStr += str[i] + charCount;
@ryanomor
ryanomor / findTriplets.js
Created April 23, 2018 00:12
Find three numbers in an array that sum to the specified number
function findTriplets(arr, n) {
let idx2, idx3;
arr.sort((a, b) => a - b); // sort arr in ascending order
for(let i = 0; i < arr.length - 2; i++) {
idx2 = i + 1; // index of the first element in the remaining list of elementss
idx3 = arr.length - 1; // index of the last element
while(idx2 < idx3) {
if(arr[i] + arr[idx2] + arr[idx3] == n) {
@ryanomor
ryanomor / checkArrayDiagonals.js
Last active June 27, 2018 14:20
Given an array, check to see if at least one of its diagonals have the same values
let myArr = [1,2,3,4,
4,0,4,4,
7,0,1,4,
4,4,4,1],
myArr2 = [1,2,3,4,
4,1,4,4,
7,0,1,4,
4,4,4,1];