Created
August 14, 2021 16:28
-
-
Save modeware/7955bdae35aed952a7ff78476a30a52c to your computer and use it in GitHub Desktop.
Program to return the shortest balanced fragment of a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Author: Safiq Lodi | |
//Goal: To find the shortest balanced fragment in a string. | |
/* | |
A balanced string that has equal number of lower and upper case characters. | |
For example - AaBb is a balanced string but TacoCat is not. | |
*/ | |
const lower = 'lower'; | |
const upper = 'upper'; | |
// const string = 'TACOtacoshgdhjsgdhshdgsghdfghsfdAAaamsdAasdhshdgh'; | |
// const string = 'AbcdefghijklmonopqrstuvwxyzaabbAsjshdghsdghsgdABDbda'; | |
const string = 'TacoCat'; | |
// const string = 'Cat'; | |
function balancedString(string) { | |
let characters = string; | |
let w = '' | |
let balanced_map = {} | |
var shortestBalancedFragment = 10000000000000000000000000; | |
for(let i = 0; i < characters.length; i++) { | |
w = characters[i]; | |
for(let j = i + 1; j < characters.length; j++) { | |
w += characters[j]; | |
if(checkBalance(w)){ | |
balanced_map[w] = w.length; | |
if(shortestBalancedFragment > w.length){ | |
shortestBalancedFragment = w.length | |
} | |
} | |
} | |
} | |
console.log(shortestBalancedFragment) | |
console.log(balanced_map, w) | |
if(Object.keys(balanced_map).length == 0) { | |
//if no balanced fragment | |
return -1; | |
} | |
else{ | |
//return shortest balanced fragment | |
return shortestBalancedFragment | |
} | |
} | |
function checkBalance(word){ | |
//Approach is to split the word into two arrays lowercase and uppercase arrays | |
const lowerLetters = []; | |
const upperLetters = []; | |
console.log(word) | |
for (const char of word) { | |
if(checkCase(char) == lower){ | |
lowerLetters.push(char); | |
}else{ | |
upperLetters.push(char); | |
} | |
} | |
//If there are equal number of letters in both the arrays | |
//We check if there are equivalent capital and small letters using the javascript includes method. | |
if(lowerLetters.length == upperLetters.length){ | |
console.log(lowerLetters, upperLetters) | |
for (const l of lowerLetters){ | |
if(!(upperLetters.includes(l.toUpperCase()))){ | |
return false; | |
} | |
else{ | |
continue; | |
} | |
} | |
return true; | |
} | |
return false; | |
} | |
//This function checks whether the charater is lower or upper case | |
function checkCase(character){ | |
if(character == character.toLowerCase()){ | |
return lower | |
}else{ | |
return upper | |
} | |
} | |
console.log("Final Answer, shoretst balanced string length: ", balancedString(string)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment