I am trying to make a calculator of sorts where you perform an operation and the code returns an answer that follows the rules of significant figures. Here is a boiled down portion of what I have coded:
var x = 0.002.toString().split(""); //to convert the number to a list
for(i = 0; i <= x.length; i++) {
if(x[i] != 0 || ".") {
x.splice(0, i);
{ break; }
}
}
The for loop is supposed to delete all of the non-significant 0's at the beginning, but it isn't working and I don't know what the problem could be.
if( x[i] != 0 || ".")
always succeeds because "." is always truthy. Try
if( !(x[i] === '0' || x[i] === '.') )
to check if the character is neither a zero nor decimal point.
Related
I'm writing a function that will count the number of vowels in a string.
I decided to use a for-loop and an if-statement to do this.
function vowels (string) {
var counter = 0;
for (let i=0; i < string.length; i++) {
if (i == 'a' || i == 'e' || i == 'i' || i == 'o' || i == 'u') {
counter++;
}return counter;
}
}
This is my code. When I call the function, it only returns 0 no matter how many vowels my string has. What's wrong?
Couple of things.
You're not looping through the string but the length of it. You need to use the length to get the position of the string.
You're returning the counter, exiting the function, on index 0.
I also added a toLowerCase to account for casing. A === a but that depends on your use case.
Always use === operator when validating types. You can learn more here but basically == compares value only and === compares value and type.
e.g. 0 == '0' equals true and 0 === '0' equals false
function vowels (value) {
let counter = 0;
let char = '';
for (let i = 0; i < value.length; i++) {
char = value[i].toLowerCase();
if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u') {
counter++
}
}
return counter;
}
vowels("AaBbCcDdEe");
returns 4. AaEe.
I'm currently solving a problem at CoderByte. Here's the scenario.
Have the function SerialNumber(str) take the str parameter being passed and determine if it is a valid serial number with the following constraints:
It needs to contain three sets each with three digits (1 through 9) separated by a period.
The first set of digits must add up to an even number.
The second set of digits must add up to an odd number.
The last digit in each set must be larger than the two previous digits in the same set.
If all the above constraints are met within the string, the your program should return the string true, otherwise your program should return the string false. For example: if str is "224.315.218" then your program should return "true".
Examples
Input: "11.124.667"
Output: false
Input: "114.568.112"
Output: true
Here's my JS code for this problem.
function SerialNumber(str) {
// code goes here
if(str.length < 11) {
return "false";
}
for (let x = 0; x < str.length; x++) {
if(str[x] === '0') {
return "false";
}
}
const first = str[0] + str[1] + str[2];
const second = str[4] + str[5]+ str[6];
if (first % 2 !== 0 || second % 2 === 0) {
return "false";
}
if (str[2] < str[1] || str[2] < str[0] || str[6] < str[5] || str[6] < str[4] || str[10] < str[8] || str[10] < str[9]) {
return "false";
} else {
return "true";
}
}
console.log("11.124.667 : " + SerialNumber("11.124.667"));
console.log("114.568.112 : " + SerialNumber("114.568.112"));
When I input "11.124.667", it will return to false (which is correct). And when I input "114.568.112", it will also return to false (which is not correct). Any tips on how can I obtain this? Thanks for the feedback.
I tried your code and the problem comes from the third return false for the 2nd example, when you set second, you concatenate strings instead of adding numbers, thus %2 is always equal to 0 since
I added console.log before each return false to see which condition failed.
Here's the fixed code in which I added parseInt for first and second
function SerialNumber(str) {
if (str.length < 11) {
console.log("first")
return "false";
}
for (let x = 0; x < str.length; x++) {
if (str[x] === '0') {
console.log("second")
return "false";
}
}
const first = parseInt(str[0]) + parseInt(str[1]) + parseInt(str[2]);
const second = parseInt(str[4]) + parseInt(str[5]) + parseInt(str[6]);
if (first % 2 !== 0 || second % 2 === 0) {
console.log("third")
return "false";
}
if (str[2] < str[1] || str[2] < str[0] || str[6] < str[5] || str[6] < str[4] || str[10] < str[8] || str[10] < str[9]) {
console.log("fourth")
return "false";
} else {
return "true";
}
}
console.log("11.124.667 : " + SerialNumber("11.124.667"));
console.log("114.568.112 : " + SerialNumber("114.568.112"))
I am trying to learn loops and strings in Javascript, and was wondering if it is possible to declare different characters for a variable in a loop. For example, I know that I can have a code like:
for (var i = 0 ; char && (i < str.length) ; i++) {
if (i == 3 || i == 7) char = '-' == str.charAt(i) }
but if I wanted to allow for different characters in certain parts of a string (such as variable char equaling both a { if i == 2 while also equaling a } if i == 6) such as:
var char = 12 == str.length ;
for (var i = 0 ; char && (i < str.length) ; i++) {
if (i === 2) char = '{' == str.charAt(i)
While also allowing for:
if (i === 6) char = '}' == str.charAt(i)
So, essentially, is it possible to have a single string be able to allow different characters in set positions? If not, any ideas on how to enact something similar? I hope this makes sense, I wasn't entirely sure how to best phrase this question.
Clarification edit: if I programmed something allowing users to type something in, but it only allows for certain characters to be typed in certain spots.
Am I somewhere near the solution? I always get a double number of the consonants.
I was convinced that this was the correct approach.
function consonants(str) {
var countConsonants = 0;
for (var i = 0; i <= str.length; i++) {
if (str[i] !== "a" || str[i] !== "e" || str[i] !== "i" ||
str[i] !== "o" || str[i] !== "u" || str[i] !== " ") {
countConsonants += 1;
}
}
return (countConsonants);
}
consonants("asdfghaaa");
I am expecting an answer of 5 i.e. sdfgh are the consonants.
Your logic is flawed, The operator in your condition should be AND && not OR ||, since you want to compare all the chars not just one of them :
function consonants(str) {
var countConsonants = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] !== "a" && str[i] !== "e" && str[i] !== "i" &&
str[i] !== "o" && str[i] !== "u" && str[i] !== " ") {
countConsonants++;
}
}
return (countConsonants);
}
console.log(consonants("asdfghaaa"));
NOTE : The loop should stop at length-1 since arrays are 0 based, so replace :
for (var i = 0; i <= str.length; i++) {
__________________^^
By :
for (var i = 0; i < str.length; i++) {
__________________^
Hope this helps.
You can do
let str = 'asdfghaaa';
let result = str.split('').filter(e => e.match(/[^aeiou]/) != null).length;
console.log(result);
The main problem in counts lies within your conditions.
You're increasing the number of consonants whenever one of the conditions fail (that's what || does, known as the OR operator). So whenever a character !== "a" OR !== "e", you're increasing the count, which is wrong. (Imagine that a is !== 'e', so you're counting a as a consonant).
Change the || binary operator to && (AND); this way, you're only increasing the consonant count whenever the current character str[i] is not among the values you're verifying for (a, e, i, o, u, ' ').
As others pointed out, you're also likely to run into an error as the max value of i should be Length-1.
There also other problems you need to consider:
What happens when the character is an uppercase letter?
What happens when the character is a punctuation mark or a number?
For a beginner, this may not be relevant, but it's well worth getting these techniques under your skin: It's more readable to create an array that contains all of the value you're verifying for ["a","e", etc] and then, for each char in the source string, just verify if array.indexOf(str[i]) >= 0 (which means that the character is included in the array).
Your answer is almost right. The only problem is || instead of &&. You're checking that it's not a AND it's not e AND it's not i, etc. Your function comes out true for every letter, since a is (not a || not e), right?
function consonants (str) {
return str.match(/[aeoiu]/gi)||[].length;
}
May be not good for long string.
You need to and your conditions because if you use || the condition always evaluates to true. Your loop should go from 0 to index < str.length.
function consonants(str) {
var countConsonants = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) !== "a" && str.charAt(i) !== "e" && str.charAt(i) !== "i"
&& str.charAt(i) !== "o" && str.charAt(i) !== "u" && str.charAt(i) !== " ") {
countConsonants++;
}
}
return countConsonants;
}
console.log(consonants("asdfghaaa"));
I had this challenge too here is how i did:
const paragraph = "A quick brow fox is trying to bite me."
paragraph.match(/(?![aeiou])[a-z]/gi, "").length
Source: https://forum.freecodecamp.org/t/regex-for-consonants/282833/4
Here is a working example
let str="Hello world.";
let vowel=str.match(/[aeiou]/gi).length;
let consonant = str.match(/[^aeiou .]/gi).length;
console.log("Vowel "+vowel+"\n");
console.log("Vowel "+consonant+"\n");
The Coderbyte problem is:
Using the JavaScript language, have the function DashInsert(str) insert dashes ('-') between each two odd numbers in str. For example: if str is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
So when the input is 99946, the output should be 9-9-946.
I had this solution, which wouldn't quite work:
function DashInsert(num) {
var arr = num.toString().split('');
var i = 0;
while(i < arr.length-1){
if( arr[i]%2 !==0 && arr[i+1]%2 !==0){
arr.splice(i+1,0,'-');
}
i++
}
return arr.join('');
}
Then I found this similar answer:
function DashInsert(num) {
var arr = num.toString().split('');
var i = 0
while(i < arr.length-1){
if( arr[i]%2===1 && arr[i+1]%2===1){
arr.splice(i+1,0,'-');
}
i++
}
return arr.join(''); }
str = 99946;
alert(DashInsert(str));
Can anyone explain why it should be arr[i]%2===1?
both are correct .
for example , take 9 : 9%2 != 0 and also 9%2 ==1 . think about it , all odd numbers can be split to
2n+1 . a modulo of 2 will always return 1 , which is not 0.
For anyone else who stumbles upon this in a frustrated googling haze...
After the first hyphen is added, it changes the length of the array, so it gets evaluated in the loop to see if the hyphen element !== 0.
Since a '-' !== 0, another hyphen is added.
This is also why you keep blowing your stack since the hyphen keeps changing the length of your array (side note, always cache your length in a variable outside of your for loop and use that in your loop instead).
To fix it, you could add a bunch more &&'s to your if statement i.e.
if(theArray[x] % 2 !== 0 && theArray[x+1]% 2 !== 0 && theArray[x] !== '-' && theArray[x+1] !== '-')
or you could just be more specific and only look for modulo results that evaluate to 1.
I tried this and it works..
HTH..
private static String createDashedString(String str) {
StringBuilder builder = new StringBuilder();
char[] chararray = str.toCharArray();
for (int i=0;i<chararray.length-1;i++) {
int firstInt = Character.getNumericValue(chararray[i]);
int nextInt = Character.getNumericValue(chararray[i+1]);
if ((firstInt%2 !=0) && (nextInt%2 !=0)) {
builder.append(firstInt);
builder.append("-");
}else {
builder.append(firstInt);
}
}
builder.append(chararray[chararray.length-1]);
return builder.toString();
}
public static void main(String args[]) {
String str = "999999";
//01234
System.out.println(createDashedString(str));
}
function DashInsert(str) {
let bil = 0;
while (bil < str.length-1) {
if (Number(str[bil]) % 2 === 1 && Number(str[bil+1]) % 2 === 1) {
str = str.slice(0,bil+1) + "-" + str.slice(bil+1);
bil = bil + 2;
}
else {
bil++;
}
}
return str;
}
console.log(DashInsert("454793"));
let x = '99946'
let z=[]
for(var i = 0;i<x.length;i++){
if(x[i]%2 == 0 && x[i+1]%2 == 1 ){
z+=x[ i ]
}else if (x[i]%2 == 1 && x[i+1]%2 == 0){
z+=x[i]
}else if (x[i]%2 == 1 && x[i+1]%2 == 1){
z+=x[i]+"-"
}else{
z+=x[i]
}
}
console.log(z)