This question already has answers here:
Assign only if condition is true in ternary operator in JavaScript
(13 answers)
Closed 6 years ago.
I am trying to count all the times the letter x and the letter o appear in a string and I'm returning true if they appear the same number of times and false otherwise.
I've completed the problem, but when using a ternary statement it forced me to create an extra condition I didn't need since you seem to need 3 operations in a ternary statement so I just counted every time something else appears in a string. Is there any way I can use a ternary statement without creating an unnecessary condition or would I have to use if statements?
function ExOh(str) {
var ex = 0
var oh = 0
var other = 0
for (var i = 0; i < str.length; i++) {
str[i] === "x" ? ex++ : str[i] === "o" ? oh++ : other++
}
return ex === oh
}
console.log(ExOh("xooabcx$%x73o"));
console.log(ExOh("xooxxo"));
console.log(ExOh("x"));
console.log(ExOh(""));
//wouldn't let me just have one statement after the ternary so I created the other variable.
Why not add the boolean value?
ex += str[i] === "x";
oh += str[i] === "o";
Example
var a = 0;
a += false;
document.write(a + '<br>');
a += true;
document.write(a + '<br>');
While you just need the difference, you can use a single variable and count up for x and down for o. The return value is the not value of count.
function ExOh(str) {
var count = 0, i;
for (i = 0; i < str.length; i++) {
count += str[i] === "x";
count -= str[i] === "o";
}
return !count;
}
document.write(ExOh("xooabcx$%x73o") + '<br>');
document.write(ExOh("xooxxo") + '<br>');
document.write(ExOh("x") + '<br>');
document.write(ExOh("") + '<br>');
Related
This is the question
Given a dictionary of variable names where each name follows CamelCase notation, print the item containing most words. Please note, abbr, like ID , IP are considered one word. i.e. name IPAddress contains two words, IP and Address
singleWordChecking('HelloWorldWideWeb'); the result count should be 4
singleWordChecking('HelloWWW'); the result count should be 2
below are my function on checking single world
function singleWordChecking(word) {
let singleWordCount = 0;
for (let i = 0; i < word.length; i++) {
if (
word[i].toUpperCase() === word[i] &&
word[i + 1].toLowerCase() === word[i + 1]
) {
singleWordCount += 1;
console.log(singleWordCount);
} else if (
word[i].toUpperCase() === word[i] &&
word[i + 1].toUpperCase() === word[i + 1]
) {
return singleWordCount;
}
}
return singleWordCount;
}
singleWordChecking('HelloWorldWideWeb');
singleWordChecking('HelloWWW');
i try with word[i].toUpperCase() === word[i] for verifying the first letter is capitalized,
then if second letter is lowercase
count + 1
however when the word is 'HelloWWW'
the console shows the error of
Cannot read properties of undefined (reading 'toLowerCase')
at singleWordChecking
How do i fix this so that the edge cases can be considering into the function
The reason you are getting the error is because you are going out of bounds of the array by doing your check for the following letter, you will need to add an extra check for:
i + 1 < world.length
However, there are a couple of other issues. For one, you are returning the count when you should be incrementing the count for all capital abbreviations, also checking for 2 capital letters in a row is insufficient because abbreviations can be any length, therefore a possible solution is:
function singleWordChecking(word) {
let singleWordCount = 0;
let isAbbreviation = false;
for (let i = 0; i < word.length; i++) {
if (word[i].toUpperCase() === word[i]) {
if (i + 1 < word.length && word[i + 1].toLowerCase() === word[i + 1]) {
singleWordCount += 1;
isAbbreviation = false;
continue;
}
if (!isAbbreviation) {
singleWordCount += 1;
}
isAbbreviation = true;
}
}
return singleWordCount;
}
The exercise:
The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
Examples
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( #" => "))(("
My code was like that:
function duplicateEncode(word) {
let str = "";
for (let i = 0; i < word.length; i++) { //This iteration is to examine every character in the string;
for (let j = 0; j < word.length; j++) { //This iteration is to compare every character to every other inside the string, in order to check if there is any repetition
if (j === i) { //This first conditon was selected because a character is not supposed to be compared to itself
continue;
} else if (word[i] === word[j]) {
str = str + ")";
break;
} else if (j !== word.length - 1) {
continue;
} else if (j === word.length - 1) {
str = str + "(";
}
}
}
return str;
}
Does anyone can help me figure out why it doesn't work for all cases?
For example:
console.log(duplicateEncode("abc"));
It should return ((( instead of ((
But,
console.log(duplicateEncode("mulherm"));
returns exacly what it supposed to: )((((()
Apparently, whenever a string does not have a character that repeats,the function returns a string without the first element. But whenerver the string has at least one element that repeats it returns exacly what it's supposed to.
What is going on with my code?
I think the issue is that when you use your snippet below, you prevent yourself from entering the last loop.
if (j === i) {
continue;
}
The issue is present whenever a word with a non duplicated letter is last. i.e.
This works
console.log(duplicateEncode("aba")); //returns )()
This does not
console.log(duplicateEncode("aab")); //returns ))
What you could do is add a statement that when
i === word.length - 1
and no
"(" are in your
str variable, you can append another ")" to your str.
In other words, if you have found no duplicated characters after checking the before last position while iterating over your entire word, the last is guaranteed to be unique as well.
Console logs below
function duplicateEncode(word) {
let str = "";
for (let i = 0; i < word.length; i++) { //This iteration is to examine every character in the string;
for (let j = 0; j < word.length; j++) { //This iteration is to compare every character to every other inside the string, in order to check if there is any repetition
console.log(i);
console.log(j);
console.log(str);
if (j === i) { //This first conditon was selected because a character is not supposed to be compared to itself
console.log("continue")
continue;
} else if (word[i] === word[j]) {
console.log("append )")
str = str + ")";
break;
} else if (j !== word.length - 1) {
console.log("j !== length")
continue;
} else if (j === word.length - 1) {
console.log("append (")
str = str + "(";
}
}
}
return str;
}
Use a debugger to step through your code line by line. There are cases where the inner loop completes without ever meeting one of the conditions for a adding a character to the string.
Instead, use a boolean flag to denote whether the letter is duplicated, set that inside the loop (much simpler logic), then after the loop do str += (found ? ')' : '(');. This ensures you add exactly one character to the output string per iteration of the outer loop.
I'm writing a calculator in JS and currently I'm writing the '=' function, now I pasted my code below, so I made exp = 5 + 5, everything works fine it tells me that total is 10, now when I do 5+5+5 it still says 10, it's as if the loop ins't working, because I want it to do 5+5 first, update the total to be 10 and then find the + operator again and then add whatever is after the plus, how do I do this? I have no idea why the loop isn't working
All help is appreciated,
Have a nice day,
larwa
function equal(){
var exp = document.form.textview.value;
var expArray = exp.split(/\b/);
console.log(expArray);
let total = 0;
for (let i = 0 ; i < expArray.length; i++){
console.log(expArray[0])
total = parseFloat(expArray[0])
if(i = '+' || '-' || '/' || '*'){
console.log(i);
n = expArray.indexOf(i)
total += parseFloat(expArray[n + 1]);
}
}
There are certain mistakes in your code.
The total should be initialized outside the for loop, otherwise it will generate incorrect total value.
if(i = '+' || '-' || '/' || '*'){, in this instead of using assignment operator i:e =, comparison operator i:e == or === (strict equality operator) should be used. As well separate comparison expressions are required i:e i=== '+' || i=== '-' || i=== '/' || i=== '*'. The i is nothing but index of the array elements, instead of i it should be array element. i:e expArray[i].
let exp = "5 + 5 + 5";
function equal() {
var expArray = exp.split(/\b/);
let total = parseFloat(expArray[0]);
for (let i = 0; i < expArray.length; i++) {
const dig = expArray[i].trim();
if (dig === '+' || dig === '-' || dig === '/' || dig === '*') {
total += parseFloat(expArray[i + 1]);
}
}
return total;
}
console.log(equal());
Try this
for (let i = 0 ; i < expArray.length; i++){
console.log(expArray[0])
total = parseFloat(expArray[0])
if(i == '+' || '-' || '/' || '*'){
console.log(i);
n = expArray.indexOf(i)
total += parseFloat(expArray[n + 1]);
}
The = operator is used for assigning values to a variable, however the == operator is used for comparison between two variables irrespective of the datatype of variable
I have attempted to make an algorithm that will do the same thing as this function: var string= string.split(' ').join('');
So if I have the following String: Hello how are you it becomes Hellohowareyou
I don't want to use .replace or regex or .split
However, the algorithm doesn't seem to make any changes to the String:
var x = prompt("Enter String");
for (var i=0; i<=x.length;i++) {
if (x[i] == " ") {
x[i] = "";
}
}
alert(x);
Iterate over the string copying characters, skipping spaces. Your code doesn't work because strings are immutable, so you cannot change characters within the string by doing x[i] = 'c'.
See Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
var string = 'Hello How are you';
var noSpaces = '';
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) != ' ' ) {
noSpaces += string.charAt(i);
}
}
alert(noSpaces);
Your code is not working because, probably for strings, similar to a getter, there is no setter for indexed approach(x[0] = "w"). You cannot consider a string as an array. Its a special form of object (immutable object) that can be accessed with index, but strictly there is no setter in this approach.
You can fix your code by changing like below,
var x = prompt("Enter sum or 'e' to Exit");
var modified = "";
for (var i=0; i<x.length;i++) {
if (x[i] != " ") {
modified += x[i];
}
}
alert(modified);
And you can do this in other better ways like below by using regex,
var x = prompt("Enter sum or 'e' to Exit");
x = x.replace(/\s/g,"");
In your code you just compare the value and try to replace with same variable but it's not possible to replace same with variable, just stored your value with new variable some thing like below
var x = prompt("Enter sum or 'e' to Exit");
var v='';
for (var i=0; i<x.length;i++) {
if (x[i] != " ") {
v +=x[i];
}
}
alert(v);
Here is the link https://jsfiddle.net/rqL3cvog/
Another approach, which updates the variable x and does not use another variable is to use a reverse for loop and use slice to take the string before and after i:-
var x = prompt("Enter String");
for (var i = x.length; i--;) {
if (x[i] == " ") {
x = x.slice(0, i) + x.slice(i + 1, x.length);
}
}
alert(x);
Or, a reverse for loop with substr :-
var x = prompt("Enter String");
for (var i = x.length; i--;) {
if (x[i] == " ") {
x = x.substr(0, i) + x.substr(i + 1);
}
}
alert(x);
Hie ,
Please check below code. Its lengthy. But others can help to make it short. Check output
var x = prompt("Hello how are you");
y = ''
flag = false
for (var i=0; i<x.length;i++) {
if (x[i] == " ") {
flag= true
}
else {
if (flag == true) {
y += ' '
y += x[i]
flag = false
}
else {
y += x[i]
}
}
}
alert(y)
Output is : "Hello how are you"
Code just sets a flag when you get a space in x[i] & when you get next character its just add single space instead of whitespace & adds next character to output string & again sets flag to false.
Hey guys working on a problem from CoderBytes. The directions of the following:
Using the JavaScript language, have the function DashInsert(num) insert dashes ('-') between each two odd numbers in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
Use the Parameter Testing feature in the box below to test your code with different arguments.
So I didn't create a function but here is my road map.
num = 3333333333
arr = num.toString().split("")
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 1 && arr[i + 1] % 2 === 1){
num.toString().replace(arr[i].toString() + arr[i+1].toString(),
arr[i].toString() + "-" + arr[i+1].toString())
}
}
The thing is when I run this it only puts a dash between the first two threes. I really can't figure out why this is happening. Anyone know where I am going wrong?
Here, this simple solution should do well:
var num = 3434333333
var arr = num.toString().split("");
var finalStr = "";
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 1 && arr[i + 1] % 2 === 1){
finalStr += arr[i] + "-";
}
else {
finalStr += arr[i];
}
}
simply keep a string for the result, if two consecutive numbers are odd append an extra "-" after the number in the string, otherwise simply append the number and your final string will contain the desired result.
See the DEMO here