I am solving an algorithm question whereby it requires me to ensure that brackets, parenthesis and braces are put in the correct order or sequence.
Here is a link to the question, https://leetcode.com/problems/valid-parentheses/
An example is shown below:
Here is my code for the solution:
const isParenthesisValid = (params) => {
myList = []
lastElement = myList[myList.length - 1]
for (let i = 0; i < params.length; i++) {
if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) {
myList.push(params[i])
} else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) {
myList.pop()
} else return false
}
return myList.length ? false : true
}
// I get false as an answer everytime whether the pattern is correct or wrong
// false
console.log(isParenthesisValid("[()]"))
But I don't know why I get false everytime, I have compared my answer with someones else answer who did the same thing but it seems I am omitting something not so obvious.
I hope someone can point out in my code where i am getting it wrong.
Your lastElement retrieves the last element of the list at the start of the program - when there is no such element - so it's always undefined. You need to retrieve the value inside the loop instead.
const isParenthesisValid = (params) => {
myList = []
for (let i = 0; i < params.length; i++) {
const lastElement = myList[myList.length - 1]
if (params[i] === "(" || params[i] === "[" || params[i] === "{" ) {
myList.push(params[i])
} else if ((params[i] === ")" && lastElement === "(") || (params[i] === "]" && lastElement === "[") || (params[i] === "}" && lastElement === "{")) {
myList.pop()
} else return false
}
return myList.length ? false : true
}
console.log(isParenthesisValid("[()]"))
Or, a bit more readably:
const isParenthesisValid = (input) => {
const openDelimiters = [];
for (const delim of input) {
const lastElement = openDelimiters[openDelimiters.length - 1];
if (delim === "(" || delim === "[" || delim === "{") {
openDelimiters.push(delim)
} else if ((delim === ")" && lastElement === "(") || (delim === "]" && lastElement === "[") || (delim === "}" && lastElement === "{")) {
openDelimiters.pop()
} else return false
}
return openDelimiters.length === 0;
}
console.log(isParenthesisValid("[()]"))
Another approach, linking each delimiter with an object:
const delims = {
')': '(',
'}': '{',
']': '[',
};
const isParenthesisValid = (input) => {
const openDelimiters = [];
for (const delim of input) {
if ('([{'.includes(delim)) {
openDelimiters.push(delim)
} else if (')]}'.includes(delim) && openDelimiters[openDelimiters.length - 1] === delims[delim]) {
openDelimiters.pop()
} else return false
}
return openDelimiters.length === 0;
}
console.log(isParenthesisValid("[()]"))
Forgive me if this question has already been asked; I've searched the site for this question and haven't stumbled upon it yet.
I'm creating a word-guessing game, and I'm having trouble with the last of my functions. The function arguments are a user-inputted character ("character"), a randomly generated word ("word"), and a scrambled version of that word ("scrmbldword"). As an example, the word could be "chilly", and the scrambled version would have a corresponding number of underscores "______". The role of this function is to take the user input, scan the "word" for that letter, and if it finds that letter in the word, to replace an underscore of the "scrmbldword" with the corresponding letter.
For instance, the word would be "chilly", and the user input would be the character "l"; I need the scrmbldword to become "___ll_".
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replace(scrmbldword[k], character);
console.log(tempWord);
}
}
}
Thank you for all the answers, but when I copy and paste them into my code, they are not working. I'm trying to understand the code behind your various answers so I can edit them myself, but for the most part I don't get it. Perhaps it would help you all if I gave more context, so here's my file entirely...
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Word Guess Game</title>
</head>
<body>
<div>
<p id="directions-text">Type any letter to start playing</p>
<p id="userchoice-text"></p>
<p id="userguesslist-text"></p>
<p id="unscrambledword-text"></p>
</div>
<script type="text/javascript">
var userGuesses = [];
var unknownWord = "";
function wordGenerator() {
var computerChoices = ["lowly", "start", "chilly", "bun", "bead", "friend", "return", "view", "cloth", "frogs", "celery", "basin", "stand", "special", "broad", "abaft", "plead", "quartz", "mark", "tempt", "shop", "stone", "scorch", "taboo", "hoax", "spiffy", "insure"];
var cpuWord = computerChoices[Math.floor(Math.random() * computerChoices.length)];
console.log(cpuWord);
return cpuWord;
};
var computerWord = wordGenerator();
function scrambledWord(string) {
var knownWord = ""
if (string.length == 3) {
knownWord = "___"
} else if (string.length == 4) {
knownWord = "____"
} else if (string.length == 5) {
knownWord = "_____"
} else if (string.length == 6) {
knownWord = "______"
} else if (string.length == 7) {
knownWord = "_______"
}
return knownWord;
}
var unknownWord = scrambledWord(computerWord);
var directionsText = document.getElementById("directions-text");
var userChoiceText = document.getElementById("userchoice-text");
var userGuessList = document.getElementById("userguesslist-text");
var unscrambledWordText = document.getElementById("unscrambledword-text");
document.onkeyup = function (event) {
var userGuess = event.key;
if ((userGuess === "a") || (userGuess === "b") || (userGuess === "c") || (userGuess === "d") || (userGuess === "e") || (userGuess === "f") || (userGuess === "g") || (userGuess === "h") || (userGuess === "i") || (userGuess === "j") || (userGuess === "k") || (userGuess === "l") || (userGuess === "m") || (userGuess === "n") || (userGuess === "o") || (userGuess === "p") || (userGuess === "q") || (userGuess === "r") || (userGuess === "s") || (userGuess === "t") || (userGuess === "u") || (userGuess === "v") || (userGuess === "w") || (userGuess === "x") || (userGuess === "y") || (userGuess === "z")) {
userGuesses.push(userGuess);
directionsText.textContent = "";
userChoiceText.textContent = "You chose: " + userGuess;
userGuessList.textContent = "You have guessed: " + userGuesses;
unscrambledWordText.textContent = "The word is: " + unknownWord;
wordChecker(userGuess)
} else {
alert("You did not enter an alphabetical character.")
}
};
function wordChecker(input) {
if (computerWord.includes(input)) {
alert("You guessed a correct character")
unscrambledWord(input, unknownWord, computerWord)
} else {
alert("You guessed an incorrect character")
}
}
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replace(scrmbldword[k], character);
console.log(tempWord);
}
}
}
As per my understanding, you can try this
function unscrambledWord(character, word, scrmbldword = "_".repeat(word.length)) {
return [...scrmbldword].map((d, i) => d == '_' && word[i] == character ? character : d).join('')
}
console.log(unscrambledWord('l', 'chilly'))
I think Nitish Narang is really a nice answer, but if you really want to use your existing function, you can try to define and use a replaceAt function, like this :
function unscrambledWord(character, scrmbldword, word) {
for (k = 0; k < word.length; k++) {
if (character == word[k]) {
var tempLetter = word[k];
console.log(tempLetter)
tempWord = scrmbldword.replaceAt(k, character);
console.log(tempWord);
}
}
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
unscrambledWord("l", "______", "chilly")
You can use the replace method with a RegExp that has the global flag, which tells us to replace all instances of that RegExp.
RegExp(`[^${character}]`, "g")
We're making a regex that matches any character except the provided character.
function unscrambledWord(character, word) {
const notCharacter = RegExp(`[^${character}]`, "g")
return word.replace(notCharacter, "_")
}
I want to add conditions in JavaScript filter() method dynamically.
I have the code below:
let condition = '';
let a = ['empEmail', 'employeeAction', 'transactionNo', 'deviceListName', 'projectName'];
if (this.selectedEmployeeAlias != undefined) {
condition += '&& a => a.empEmail === this.selectedEmployeeAlias';
}
if (this.employeeStatusList != undefined) {
condition += '&& a.employeeAction === this.employeeStatusList'
}
if (this.selectedTransactionNo != undefined) {
condition += '&& a.transactionNo === this.selectedTransactionNo';
}
if (this.selectedDeviceList != undefined) {
condition += ' && a.deviceListName == this.selectedDeviceList';
}
if (this.selectedProjectName != undefined) {
condition += '&& a.projectName == this.selectedProjectName';
}
var finalCondition = condition.substring(2, condition.length);
var fArray = arrayDetails.filter(finalCondition);
The code is returning an error as:
finalCondition is not a function.
Could you please let me know how can I add conditions to filter() dynamically.
You could take an array of functions with conditions. Then iterate with every.
var conditions = [];
if (this.selectedEmployeeAlias !== undefined) {
conditions.push(a => a.empEmail === this.selectedEmployeeAlias);
}
if (this.employeeStatusList !== undefined) {
conditions.push(a => a.employeeAction === this.employeeStatusList);
}
if (this.selectedTransactionNo !== undefined) {
conditions.push(a => a.transactionNo === this.selectedTransactionNo);
}
if (this.selectedDeviceList !== undefined) {
conditions.push(a => a.deviceListName == this.selectedDeviceList);
}
if (this.selectedProjectName !== undefined) {
conditions.push(a => a.projectName == this.selectedProjectName);
}
var fArray = arrayDetails.filter(o => conditions.every(c => c(o)));
As you got the nakes of the keys, just loop over them and check for undefineds:
const keys = ['empEmail', 'employeeAction', 'transactionNo', 'deviceListName', 'projectName'];
const result = arrayDetails.filter(el => {
for(const key of keys) {
if(this[key] === undefined) continue;
if(this[key] !== el[key]) return false;
}
return true;
});
eval to the Rescue!
While it's generally advised against, eval does exactly what you want here.
Just pass your condition variable to eval inside the .filter method and voila!
let condition='';
let a = ['empEmail', 'employeeAction', 'transactionNo', 'deviceListName', 'projectName'];
if (this.selectedEmployeeAlias != undefined) {
condition += '&& a => a.empEmail === this.selectedEmployeeAlias';
}
if (this.employeeStatusList != undefined) {
condition += '&& a.employeeAction === this.employeeStatusList'
}
if (this.selectedTransactionNo != undefined) {
condition += '&& a.transactionNo === this.selectedTransactionNo';
}
if (this.selectedDeviceList != undefined) {
condition += ' && a.deviceListName == this.selectedDeviceList';
}
if (this.selectedProjectName != undefined) {
condition += '&& a.projectName == this.selectedProjectName';
}
var finalCondition=condition.substring(2, condition.length);
var fArray=arrayDetails.filter(stuff => eval(finalCondition));
TableHandler.prototype.IsAlreadySelected = function(dataToCheck)
{
var _this = this;
if (_this.NewTemplateUsageSelected.length > 0)
{
var len = _this.NewTemplateUsageSelected.length;
for (var i = 0; i < len; i++)
{
var an = _this.NewTemplateUsageSelected[i];
var isTemplateUsageDataDuplicate=false;
var isNonApplicableCGDataDuplicate=false;
if ((an.CustomerName == dataToCheck.CustomerName) &&
(an.ProgramName == dataToCheck.ProgramName) &&
(an.WorkpackageName == dataToCheck.WorkpackageName) &&
(an.ActivityName == dataToCheck.ActivityName) &&
(an.SelectedWorkFlowType == dataToCheck.SelectedWorkFlowType) &&
(an.SelectedWorkFlowCategory == dataToCheck.SelectedWorkFlowCategory) &&
(an.ReWorkflow== dataToCheck.ReWorkflow) &&
(an.AllowCheckGroupSelection == dataToCheck.AllowCheckGroupSelection) &&
(an.InitiatorGroupSelection == dataToCheck.InitiatorGroupSelection) &&
(an.R1GroupSelection == dataToCheck.R1GroupSelection) &&
(an.R2GroupSelection == dataToCheck.R2GroupSelection) &&
(an.R3GroupSelection == dataToCheck.R3GroupSelection) &&
(an.R4GroupSelection == dataToCheck.R4GroupSelection) &&
(an.InitiatorMinReworkEffort == dataToCheck.InitiatorMinReworkEffort) &&
(an.R1MinReworkEffort == dataToCheck.R1MinReworkEffort) &&
(an.R2MinReworkEffort == dataToCheck.R2MinReworkEffort) &&
(an.R3MinReworkEffort == dataToCheck.R3MinReworkEffort) &&
(an.R4MinReworkEffort == dataToCheck.R4MinReworkEffort) &&
(an.AllowFileAttachment == dataToCheck.AllowFileAttachment) &&
(an.QualityReviewer== dataToCheck.QualityReviewer) &&
(an.AllowLiabiltySelection == dataToCheck.AllowLiabiltySelection)&&
(an.SetToInactive == dataToCheck.SetToInactive)&&
(an.NonApplicabilityCheckGroupAllowed == dataToCheck.NonApplicabilityCheckGroupAllowed))
{
istemplateusagedataduplicate=true;
}
var checkgroupslendataToCheck=dataToCheck.NonApplicableCheckGroupList.length;
var nalen=an.NonApplicableCheckGroupList.length;
if(checkgroupslendataToCheck == nalen )
{
for (var i = 0 ;i < checkgroupslendataToCheck ; i++)
{
var naDatatocheck= dataToCheck.NonApplicableCheckGroupList[i];
var naData=an.NonApplicableCheckGroupList[i];
if(
( naDatatocheck.INonApplicability == naData.INonApplicability )&&
( naDatatocheck.R1NonApplicability == naData.R1NonApplicability )&&
( naDatatocheck.R2NonApplicability == naData.R2NonApplicability) &&
( naDatatocheck.R3NonApplicability == naData.R3NonApplicability )&&
( naDatatocheck.R4NonApplicability == naData.R4NonApplicability))
isNonApplicableCGDataDuplicate=true;
else
{
isNonApplicableCGDataDuplicate=false;
break;
}
}
if(isNonApplicableCGDataDuplicate==true && istemplateusagedataduplicate==true)
return true;
}
}
}
};
The above code is causing error Internet may run slowly. When i seached for a solution i got solutions like change of registry and IE version, Move the code to cdebehind,usage of plugin etc.. Which are not feasible in our project. So I have to change the above logic.Any inbuilt function in javascript or jquery which i can use to campare a two nested list.
The inner loop needs to use a different variable as its counter or it will make the outer loop go on infinitely. Currently you are using i for both loops.
See the bottom of this post;
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(aString)
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);
You iterate on sString wich doesn't exist and not on your parameter aString.
Where is sString being declared in your function? Try with aString (or declare var sString = aString) and try again.
Please change function myF(aString) to function myF(sString)
There is a naming mistake. Here is a working copy of your code .
http://jsfiddle.net/hXarY/
You can try using "firebug" to catch such errors if you do not already do.
function isVowel(aCharacter)
{
return ((aCharacter == 'a') || (aCharacter == 'A')||
(aCharacter == 'e') || (aCharacter == 'E')||
(aCharacter == 'i') || (aCharacter == 'I')||
(aCharacter == 'o') || (aCharacter == 'O')||
(aCharacter == 'u') || (aCharacter == 'U')||
(aCharacter == 'y') || (aCharacter == 'Y'));
}
function myF(sString) // this should be sString , not aString
{
// variable to hold resultString
var resultString = '';
// variable to hold the current and previous characters
var currentCharacter = '';
var precedingCharacter = '';
// in the case of the first character in the string there is no
// previous character, so we assign an empty string '' to the variable at first
//precedingCharacter = '';
// TODO part (ii)
// add code as directed in the question
var i = 0;
for( i; i < sString.length; ++i)
{
currentCharacter = sString.charAt(i);
if (isVowel(currentCharacter) && (!isVowel(precedingCharacter)))
{
resultString = resultString + 'ub';
}
resultString = resultString + currentCharacter;
precedingCharacter = currentCharacter;
}
return resultString;
}
var string1 = "the cat sat on the mat";
var result1 = myF(string1);
document.write(string1);//THIS ISN'T GOING TO BE DISPLAYED, BUT WHY?
document.write('<BR>');
document.write(result1);