If conditional giving true although it's supposed to be false [duplicate] - javascript

This question already has answers here:
Check variable equality against a list of values
(16 answers)
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
What is an off-by-one error and how do I fix it?
(6 answers)
Closed 4 months ago.
I'm having problem with the conditional always returning true. I'm not sure if it's the value it's seeing as truthy in general but it's messing with me.
Problem: Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.
Examples input/output:
XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false
function XO(str) {
let on = 0
let xn = 0
let result = ""
for (let i = 0; i <=str.length; i++) {
if (str[i] = "x" || "X"){
xn++
} if (str[i] = "o" || "O") {
on++
};
if (xn == on || xn && on == 0){
result = true
}else if (xn !== on) {
result = false
}
return result
}
}
Seems the conditional is always returning true. Not sure if it's because the types are true (which is why I kept it strict).

You have 3 mistakes in your XO function.
You have used assignment operator : = instead of equality
comparison operator : ==.
You are checking condition str[i] == "x" || "X". The correct way to write this is : str[i] == "x" || str[i] == "X".
You are checking xn==on inside the for loop. You should check that once your for loop is over.
Here is the correct code -
function XO(str) {
let on = 0
let xn = 0
for (let i = 0; i < str.length; i++) {
if (str[i] == "x" || str[i] == "X") {
xn++
continue;
}
if (str[i] == "o" || str[i] == "O") {
on++
continue;
};
}
return xn==on;
}

You just use toLowerCase() and at the end return if on===xn
function XO(str) {
let on = 0;
let xn = 0;
for (let i = 0; i < str.length; i++) {
if (str[i].toLowerCase() === "x") {
xn++;
}
if (str[i].toLowerCase() === "o") {
on++;
};
}
return xn === on
}
console.log(XO("ooxx"))
console.log(XO("xooxx"))
console.log(XO("ooxXm"))
console.log(XO("zpzpzpp"))
console.log(XO("zzoo"))

Related

Following function must return true if given sequence is valid. Why this function doesn't return true for "||" sequence?

Function must return true for "()" sequence and false for "[)" sequence, so it does. But why this function doesn't return true for "||" sequence? Could you help, please?
I wrote this code, but nothing works :(
function check(s) {
const brackets = {
")": "(",
"]": "[",
"}": "{",
"|": "|",
};
const st = [];
for (let i = 0; i < s.length; i++) {
if (isClosedBracket(s[i])) {
if (brackets[s[i]].toString() !== st.pop()) {
return false;
}
} else {
st.push(s[i]);
}
}
return st.length === 0;
}
//if bracket is in this array, function returns true, so bracket is closing
function isClosedBracket(ch) {
return [")", "]", "}", "|"].indexOf(ch) > -1;
}
Well, since the pipe sequence "||" uses the same character for opening and closing, then when the first | (the opening one) will be encountered, the block of code for the closing bracket will be executed.
Your code works, but it will not operate correctly if the opening character is the same as the closing character. If you absolutely need this feature, then consider adding more checks in this particular situation.
However, the code will get much more complex since a singular | could also mean a closing bracket in an error sequence, so inputs like "(|)" will be a bit complicated to handle.
Thank you all! I solved this problem by adding another if/else block. Here is solution, if you need it =3
function check(str) {
let stack = [];
for (let i = 0; i < str.length; i++) {
if (
+str[i] === 1 ||
+str[i] === 3 ||
+str[i] === 5 ||
str[i] === "(" ||
str[i] === "[" ||
str[i] === "{"
) {
stack.push(str[i]);
} else if (
(+str[i] === 2 && stack.at(-1) === "1") ||
(+str[i] === 4 && stack.at(-1) === "3") ||
(+str[i] === 6 && stack.at(-1) === "5") ||
(str[i] === ")" && stack.at(-1) === "(") ||
(str[i] === "]" && stack.at(-1) === "[") ||
(str[i] === "}" && stack.at(-1) === "{")
) {
stack.pop();
} else if (str[i] !== stack.at(-1)) {
stack.push(str[i]);
} else {
stack.pop();
}
}
return !stack.length > 0;
}
Any ideas how to improve this code?

how to fix: Array index is out of range

i have this problem
Have the function WildcardCharacters(str) read str which will contain two strings separated by a space. The first string will consist of the following sets of characters: +, , and {N} which is optional. The plus (+) character represents a single alphabetic character, the asterisk () represents a sequence of the same character of length 3 unless it is followed by {N} which represents how many characters should appear in the sequence where N will be at least 1. Your goal is to determine if the second string exactly matches the pattern of the first string in the input.
i have the solution with js, but now i am trying to solve with swift, i need your help.
this work with js, and i'm using swift v4.2
code with js
function WildcardCharacters(str) {
// code goes here
let strArr= str.split(' ')
let specChar = strArr[0]
let charStr = strArr[1].split('')
let arr = specChar.split('')
let letters = /^[A-Za-z]+$/
let i = 0
while(i< arr.length){
if(arr[i] == '+'){
if(!charStr[0].match(letters)) return "false"
charStr = charStr.slice(1,charStr.length)
}
else if(arr[i] == '*'){
let curr = charStr[0]
let j = 1, k = 0
if(arr[i+1] != undefined && arr[i+1] == '{'){
k = arr[i+2]
i = i+4
}else{
k = 3
i++
}
while(j < k){
charStr = charStr.slice(1,charStr.length)
if(charStr[0] != curr) return "false"
j++
}
charStr = charStr.slice(1,charStr.length)
continue
}
i++
}
if(charStr.length != 0) return 'false'
return "true"
}
// keep this function call here
WildcardCharacters("+++++* abcdemmmmmm");
code by Smakar20 (user github)
code with swift
extension String {
func isAlphanumeric() -> Bool {
return self.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) == nil && self != ""
}
func isAlphanumeric(ignoreDiacritics: Bool = false) -> Bool {
if ignoreDiacritics {
return self.range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil && self != ""
}
else {
return self.isAlphanumeric()
}
}
}
func wild (str: String) -> String
{
let strArr = str.split(separator: " ")
let specChar = strArr[0]
var charStr = Array(strArr[1])
let arr = Array(specChar)
var i = 0
while (i<arr.count)
{
if arr[i] == "+"
{
if !String(charStr[0]).isAlphanumeric()
{
return "false"
}
charStr = Array(charStr[0...charStr.count])
}
else if arr[i] == "*"
{
let curr = charStr[0]
var j = 0
var k = 0
if String(arr[i+1]).isAlphanumeric() != true && arr[i+1] == "{"
{
k = Int(String(arr[i+2]))!
i = i+4
}
else
{
k = 3
i += 1
}
while (j<k)
{
charStr = Array(charStr[1...charStr.count])
if charStr[0] != curr
{
return "false"
}
j += 1
}
charStr = Array(charStr[1...charStr.count])
continue
}
i += 1
}
if charStr.count != 0
{
return "false"
}
return "true"
}
wild(str: "+++++* abcdemmmmmm")
if str is "++*{5} gheeeee" then the second string in this case does match the pattern, so your program should return the string true. If the second string does not match the pattern your program should return the string false.
heeelp

in Java script Given two strings, find if they are one edit away from each other

can you help me to write a function in javascript to Given two strings, find if they are one edit away from each other example :
(pale, ple ) true
(pales, pale ) true
(pale, bale ) true
(pale, bake) false
(face, facts ) false
Can you try this function to check that string only differs by one edit.
function checkDifferntString(str1, str2) {
let diff = 0;
if (str1 === str2) return true; // equal return true
let lengthDiff = Math.abs(str1.length - str2.length)
if (lengthDiff > 1) return false; // checks length diff if > 2 return false
for (let i=0; (i<str1.length || i < str2.length);i++) {
if (diff > 1) return false; // diff greater than 1 return false
if (str1.charAt(i) !== str2.charAt(i)) diff++
}
if (diff <= 1) return true
else return false;
}
console.log(checkDifferntString("pale", "pale")) // true
console.log(checkDifferntString("pale", "pales")) // true
console.log(checkDifferntString("pales", "pale")) // true
console.log(checkDifferntString("pales", "bale")) // false
I hope it helps. Thanks!
Check this out.
I made a simple function that iterates through the given two strings and check if there's more than 1 difference (in terms of characters) between these strings, an optional argument cs to allow case sensitivity, by default it equals to false, so 'a' and 'A' are the same.
function isEditFrom(str1, str2, cs) {
var cs = cs || false, i = 0, diff = 2, len1 = str1.length, len2 = str2.length, l = (len1 > len2) ? len1: len2;
if(len1 !== 0 && len2 !== 0) {
if(cs === false) {
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
}
for(; i < l; i++) {
if(str1[i] !== str2[i]) {
if(--diff === 0) {
return false;
}
}
}
return true;
} else {
return false;
}
}
and now we call that function:
isEditFrom('Pale', 'bAle'); // returns True
isEditFrom('Pale', 'bAle', true); // returns False as we set the third argument to true enabling case sensitivity, 'a' != 'A'
isEditFrom('face', 'facts'); // returns False

Can someone explain to me how a function can equal 0?

function containsPunctuation(word)
{
var punctuation = [";", "!", ".", "?", ",", "-"];
for(var i = 0; i < punctuation.length; i++)
{
if(word.indexOf(punctuation[i]) !== -1)
{
return true;
}
}
return false;
}
function isStopWord(word, stopWords)
{
for (var i = 0; i < stopWords.length; i += 1)
{
var stopWord = stopWords[i];
if ((containsPunctuation(word)) && (word.indexOf(stopWord) === 0) && (word.length === stopWord.length + 1))
{
return true;
}
else if (word === stopWord)
{
return true;
}
}
return false;
}
At the blockquote, how is containsPunctuation(word) && (word.indexOf(stopWord) === 0? Can someone explain why they are both equal to zero?
I'm also not sure why (word.length === stopWord.length + 1) is used.
I think you are reading the if statement a little bit incorrectly. Not knowing what the isStopWord function is supposed to do I can't tell you what the (word.length === stopWord.length + 1) part is all about.
I can tell you that (containsPunctuation(word)) is its own boolean value, because that function returns a true or false. That part is its own evaluation.
The second part (word.indexOf(stopWord) === 0) is also a complete evaluation. That part has nothing to do with the containsPunctuation function. The indexOf function returns an integer, so it can equal 0.
The third part (word.length === stopWord.length + 1) is checking to see if the length of word is one more than the length of stopWord.
They are all separate evaluations and because you are using && between them all, they all must evaluate as true in order for the code block that follows it to run.
Here are the indexOf docs for string and array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
--EDIT--
in light of your comment, my guess for the (word.length === stopWord.length + 1) is because the word might contain a punctuation mark that is not included in the stopWord so this if check will only return true if the punctuation is at the end of the word because the indexOf check will only return 0 if the stopword starts at the beginning of the word.

Weird if-else behaviour Javascript [duplicate]

This question already has answers here:
if statement in javascript always true
(5 answers)
Closed 6 years ago.
The else-statement below never executes even if the if-statement is false. I think I've made some very basic mistake but can't figure out what.
var a = ["king","queen","100"];
for (var i=0; i<a.length; i++) {
if (a[i] === "king" || "queen"){
console.log("monarch");
}
else {
console.log("The number is: "+ parseInt(a[i]));
}
}
// This prints out "monarch" 3 times
Should be:
var a = ["king","queen","100"];
for (var i=0; i<a.length; i++) {
if (a[i] === "king" || a[i] === "queen"){
console.log("monarch");
}
else {
console.log("The number is: "+ parseInt(a[i]));
}
}
You wrote your boolean expression the way we would speak a spoken language, "A is either 1 or 2". That's not the way the OR is interpreted.
Either the left side of the OR is true: a[i] === "king" is true; or the right side of the OR is true: "queen". It's evaluating the string by itself, and the string "queen" is not null, so it evaluates to true.
You gotta make your two conditions separately with || as follow: a[i] === "king" || a[i] === "queen"

Categories