all valid combinations of n-pair of parenthesis - javascript

I am learning js now..
I am trying to write a simple js programme..
what I am trying to do is to print all valid combinations of n-pair
of parenthesis(properly opened and closed)
eg (), (()()),(())
i have written the logic can you tell me whether its correct or not
https://jsfiddle.net/e7mcp6xb/
module.exports = Parentheses = (function() {
var _isParenthesesMatch = function(str) {
var parentheses = str.length;
var rightParentheses = '(';
var leftParentheses = ')';
var rightCount = 0;
var leftCount = 0;
for(i=0;i<=str.length;i++){
if(rightParentheses == str.charAt(i))
{
rightCount++;
}
else if(leftParentheses == str.charAt(i))
{
leftCount++;
}
}
if(rightCount == leftCount){
return true;
}
else(rightCount != leftCount){
return false;
}
}
}());

The check is wrong, but You can fix it easily: In each step of the for loop the number of opening parenthesis cannot be smaller than the number of closing ones:
if (rightCount < leftCount)
return false;
The whole function should look like this:
function(str) {
var rightParentheses = '(';
var leftParentheses = ')';
var rightCount = 0;
var leftCount = 0;
for (var i = 0; i <= str.length; i++) {
if (rightParentheses == str.charAt(i))
rightCount++;
else if (leftParentheses == str.charAt(i))
leftCount++;
if (rightCount < leftCount)
return false;
}
return rightCount == leftCount;
}
If You'd like to generate all valid strings, you can use this function:
function nPair(n) {
if (n == 0)
return [""];
var result = [];
for (var i = 0; i < n; ++i) {
var lefts = nPair(i);
var rights = nPair(n - i - 1);
for (var l = 0; l < lefts.length; ++l)
for (var r = 0; r < rights.length; ++r)
result.push("(" + lefts[l] + ")" + rights[r]);
}
return result;
}
// result of nPair(3):
// ["()()()", "()(())", "(())()", "(()())", "((()))"]

Try this, i have modified your code a little bit. Modification and its explanation is marked in comments.
module.exports = Parentheses = (function() {
var _isParenthesesMatch = function(str) {
var parentheses = str.length;
var rightParentheses = '(';
var leftParentheses = ')';
var count=0;
for(i=0;i<str.length;i++){
//this is to check valid combination start always from ( and end with )
if(str.charAt(0)==rightParentheses && str.length-1==leftParentheses)
{
if(rightParentheses == str.charAt(i))
{
count++; //this will calculate how many times rightParentheses is present & increment count by 1
}
else if(leftParentheses == str.charAt(i))
{
count--; //this will simply decrement count to match valid sequence
}
}
if(count==0){
return true;
}
}
}());

Your function is wrong, try checking if left and right parenthesis and balanced:
function isValid(str){
var stripedStr = str.replace(/[^\(\)]+/g, '');
return stripedStr.split('').reduce(function(a, b){
return a > -1 ? b === '(' ? a + 1 : a - 1 : -1;
}, 0) === 0;
}
stripedStr - use replace() to remove any characters that are not ( or ).
split('') - returns an array so we can use reduce.
reduce() - applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.
The reduce starts with 0 as initial value and in the reduce function we count parenthesis
(+1 for (, -1 for ) )
Our string is valid if our counter never goes below 0 and we end up with 0.
You can write the reduce function like this too:
function(previousValue, currentValue){
if (previousValue > -1){
if (currentValue === '('){
return previousValue + 1;
} else {
return previousValue - 1;
}
}
return -1;
}
This is equivalent to:
function(a, b){
return a > -1 ? b === '(' ? a + 1 : a - 1 : -1;
}

It is wrong, because your function will return true for this example ))(( or this ())(()

Related

Search if a string contains a substring in Javascript (partial search)

Yes I know we can use indexOf and includes or a regular expression to find weather a string is present in another string.
But we have a different requirement. We would like indexOf or includes function to return true even if partial string is matched not the whole world. Let me provide an example.
Let's say my username is "Animation". The string the I am entering is "sssrtAnimyt5678". Now as the string "sssrtAnimyt5678" contains "Anim" which is present in "Animation" we want the function to return true.
The problem with indexOf, includes and regular expression is it tries to find the whole word "Animation" but not the partial word "Anim". I even used KMP Algorithm and found out that even KMP searches for "Animation" not "Anim". Below is the implementation of KMP in Javascript.
var makeKMPTable = function(word) {
if(Object.prototype.toString.call(word) == '[object String]' ) {
word = word.split('');
}
var results = [];
var pos = 2;
var cnd = 0;
results[0] = -1;
results[1] = 0;
while (pos < word.length) {
if (word[pos - 1] == word[cnd]) {
cnd++;
results[pos] = cnd;
pos++;
} else if (cnd > 0) {
cnd = results[cnd];
} else {
results[pos] = 0;
pos++;
}
}
return results;
};
var KMPSearch = function(string, word) {
if(Object.prototype.toString.call(string) == '[object String]' ) {
string = string.split('');
}
if(Object.prototype.toString.call(word) == '[object String]' ) {
word = word.split('');
}
var index = -1;
var m = 0;
var i = 0;
var T = makeKMPTable(word);
while (m + i < string.length) {
if (word[i] == string[m + i]) {
if (i == word.length - 1) {
return m;
}
i++;
} else {
m = m + i - T[i];
if (T[i] > -1) {
i = T[i];
} else {
i = 0;
}
}
}
return index;
};
console.log(KMPSearch("sssrtAnimyt5678", "Animation")); // returns -1
So I would like to know if such kind of partial search is possible and if anybody can point me to such implementation details or algorithm it would be helpful.
Thanks in Advance.
Just check any possible substring.
const
hasCommon = (a, b) => {
for (let i = 0; i < a.length; i++) {
for (let j = i + 1; j <= a.length; j++) {
if (b.includes(a.slice(i, j))) return true;
}
}
return false;
};
console.log(hasCommon('Animation', 'sssrtAnimyt5678'));

If-else-statement returns undefined in palindrome function

In my palindrome function an if-else-statement returns undefined. Basically, I am trying to find the biggest palindromic number with three digits. For example with two digits: 99 * 91 = 9009.
var palindromic = function(n) {
var save,
result,
counter = 900;
var checker = function(string) {
s = string.toString();
if(!(s)) {
return true;
} else if(s[0] !== s[s.length - 1]) {
return false;
}
checker(s.slice(1, -1));
}
var recursive = function() {
result = counter * n;
if(counter === n) {
return;
} else if(checker(result)) { // this line of code here, undefined.
save = result;
}
counter++;
recursive();
}
recursive();
return save;
};
What is wrong? Any help is welcome!
There are two problems in the code
checker() should have return checker(s.slice(1,-1)); as last line.
In recursive() when checker(result) is true recursive() should return.
Here's corrected code.
var palindromic = function (n) {
var save,
result,
counter = 900;
var checker = function (s) {
//s = string.toString();
if ( !(s) ) {
return true;
} else if ( s[0] !== s[s.length-1] ) {
return false;
}
return checker(s.slice(1,-1));
}
var recursive = function () {
result = counter * n;
if ( counter === n ) {
return;
} else if ( checker(result + "") ) { // this line of code here, undefined.
save = result;
return;
}
counter++;
recursive();
}
recursive();
return save;
};
Output:
palindromic(2)
2002
palindromic(3)
2772
palindromic(5)
5005
palindromic(6)
6006
palindromic(9)
8118
palindromic(23423)
188484881
A little spoiler and improving
You can do it without a recursion.
Usage of a reverse function to reverse a string.
Usage of two for loops, starting from the highest number.
function strReverse(str) {
var reverse = "";
for(var i = (str.length - 1); i >= 0; i -= 1) {
reverse += str[i];
}
return reverse;
}
function palindromic(n) {
var highestPalindrom = 0;
// Start with the highest number!
for(var i = n; i > 1; i -= 1) {
// Start also with the highest number!
for(var j = n; j > 1; j -= 1) {
// Get product
var product = i * j;
// Compare the string in reverse with the string itself
// If it is true, then it is a palindrom!
if(strReverse(product.toString()) === product.toString()) {
highestPalindrom = product;
// Break inner loop
break;
}
}
// Break outer loop
break;
}
return highestPalindrom;
}
var hP = palindromic(99);
console.log(hP);

Javascript Happy Numbers not working

Here I have a function that should take a number n into the disHappy(n) to check if all
n in [n-0) are happy.
Happy Numbers wikipedia
If I only run happyChecker(n), I can tell that 7 is happy, but disHappy(n) doesn't show it. It is as if it doesn't receive the true. I have used console.log()'s all over the place and happyChecker(n) shows a number that SHOULD return true. When I placed a console.log() above the return true; for if(newNum===1), it showed that it branched into that branch but it just didn't seem to return the true.
function happyChecker(n) {
var arr = [];
var newNum = 0;
//here I split a number into a string then into an array of strings//
num = n.toString().split("");
for (var i = 0; i < num.length; i++) {
arr[i] = parseInt(num[i], 10);
}
//here I square each number then add it to newNum//
for (var i = 0; i < arr.length; i++) {
newNum += Math.pow(arr[i], 2);
}
//here I noticed that all unhappy numbers eventually came into one of these three//
//( and more) numbers, so I chose them to shorten the checking. A temporary solution for sure//
if (newNum === 58 || newNum === 4 || newNum == 37) {
return false;
}
if (newNum === 1) {
return true;
} else {
happyChecker(newNum);
}
}
function disHappy(num) {
for (j = num; j > 0; j--) {
if (happyChecker(j)) {
console.log(j + " is a Happy Number. It's so happy!!!.");
}
}
}
When you recurse, you need to return the value returned:
if (newNum === 1) {
return true;
} else {
return happyChecker(newNum);
}
You also should declare "num" with var.
I'm ordinarily not a "code golfer", but this is a good example of how the (new-ish) iterator utility methods on the Array prototype can clean up code. You can use the .reduce() function to traverse the array of digit characters and do the work of squaring and summing all at once:
var newNum = n.toString()
.split('')
.reduce(function(sum, digit) {
return sum + (+digit * +digit);
}, 0);
The call to .toString() returns a string, then .split('') gives you an array. Then .reduce() starts with an initial sum of 0 and for each element of the array (each digit), it adds to it the square of that digit. (Instead of parseInt() I just used the + unary operator; we know for sure that each string will be a valid number and an integer.)
You need to add return to the happyChecker call.
return happyChecker(newNum);
see:
http://jsfiddle.net/YjgL8/2/
here is my implementation
var getSum = function (n) {
if (!n >= 0) return -1;
var digits = n.toString().split("");
var sum = 0;
for (var i = 0; i < digits.length; i++) {
var digit = parseInt(digits[i], 10);
sum += digit * digit;
}
return sum;
}
/**
* #param {number} n
* #return {boolean}
*/
var isHappy = function(n, visited) {
if (n < 0) return false;
if (n === 1) return true;
if (typeof visited === 'undefined') visited = {};
sum = getSum(n);
if (visited[sum]) return false; // cycle
visited[sum] = true;
return isHappy(sum, visited);
};
Complete Example of finding happy numbers in range of custom number.
function happyNumbers() {
var result = document.getElementById("happy-result")
var inputy = parseInt(document.getElementById("happyValue").value)
result.innerHTML=""
for (i = 1; i < inputy; i++) {
(happy(i, i))
}
}
function happy(value,value2) {
var result = document.getElementById("happy-result")
var lengthNum = value.toString().length;
var resultNumbers = 0
for (var b = 0 ; b < lengthNum; b++) {
resultNumbers = resultNumbers + parseInt(value.toString().charAt(b)) * parseInt(value.toString().charAt(b))
}
if (resultNumbers == 4) {
return false
} else if (resultNumbers == 1) {
result.innerHTML += "<br> happy number " + i
return true
}else{
happy(resultNumbers, value2);
}
}
window.onload=happyNumbers()
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="panel panel-default">
<div class="panel-heading">happy numbers</div>
<div class="panel-body">
<label>Enter the number that you want ot have see happy numbers uo to it</label>
<input id="happyValue" oninput="happyNumbers()" value="100" class="form-control" />
<div id="happy-result"></div>
</div>
</div>

Javascript -> Recursively find a substring within a string

I'm trying to write a recursive program to count the number of times a substring ("cat") appears in a string ("catdogcowcat"). Not sure what I'm doing wrong, but I keep getting the following error:
TypeError: Cannot read property 'length' of undefined
Here's my code:
function strCount (str, sub) {
var subLen = sub.length;
var strLen = str.length;
if (strLen < subLen) {
return 0;
} else if (str.slice(0, subLen) === sub) {
return 1 + strCount(str.substring(subLen));
} else return strCount(str.substring(1));
}
I think it's breaking when I try to get the length of the substring on this line, but that's just my guess based on my infantile understanding of devtools debugging:
return 1 + strCount(str.substring(subLen));
Thanks!
Your strCount function takes 2 arguments, so make sure you pass sub when you call it recursively:
function strCount (str, sub) {
var subLen = sub.length;
var strLen = str.length;
if (strLen < subLen) {
return 0;
} else if (str.slice(0, subLen) === sub) {
return 1 + strCount(str.substring(subLen), sub);
} else return strCount(str.substring(1), sub);
}
You could use regular expression, with match instead of having to do a recursive function
function strCount(needle,haystack){
var r = new RegExp(needle,"g");
var r2 = haystack.match(r);
return (r2?r2.length:0);
}
console.log( strCount("cat","catdowcowcat") );
you need to pass value for sub ..
function strCount(str, sub) {
var subLen = sub.length;
var strLen = str.length;
if (strLen < subLen) {
return 0;
} else if (str.slice(0, subLen) === sub) {
return 1 + strCount(str.substring(subLen),sub);
} else
return strCount(str.substring(1),sub);
}
you can call the method
$(document).ready(function(){
alert(strCount("catdogcowcat","cat"));
});
It will return the result as 2.
Fiddle
http://jsfiddle.net/deepaksuresh3003/RDmby/
you are calling your own method strCount(str.substring(subLen)) without providing second parameter and hence the function is taking 'sub' parameter as undefined.
Update your code as follows and it will start working:
function strCount(str, sub) {
var subLen = sub.length;
var strLen = str.length;
if (strLen < subLen) {
return 0;
} else if (str.slice(0, subLen) === sub) {
return 1 + strCount(str.substring(subLen), sub);
} else return strCount(str.substring(1),sub);
}

how to increment the value of a char in Javascript

How do I increment a string "A" to get "B" in Javascript?
function incrementChar(c)
{
}
You could try
var yourChar = 'A'
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B'
So, in a function:
function incrementChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1)
}
Note that this goes in ASCII order, for example 'Z' -> '['. If you want Z to go back to A, try something slightly more complicated:
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
var index = alphabet.indexOf(c)
if (index == -1) return -1 // or whatever error value you want
return alphabet[index + 1 % alphabet.length]
}
var incrementString = function(string, count){
var newString = [];
for(var i = 0; i < string.length; i++){
newString[i] = String.fromCharCode(string[i].charCodeAt() + count);
}
newString = newString.join('');
console.log(newString);
return newString;
}
this function also can help you if you have a loop to go through

Categories

Resources