I want to make something like this:
if(day==1 || day==11 || day==21 || day==31 || day==41 ......){
result="dan";
}
else{
result="dana";
}
How can i do that with every number that ends with one and of course without writing all numbers?
Just check the remainder of division by 10:
if (day % 10 == 1) {
result = "dan";
} else {
result = "dana";
}
% is the "Modulo" or "Modulus" Operator, unless you're using JavaScript, in which case it is a simple remainder operator (not a true modulo). It divides the two numbers, and returns the remainder.
You can check the remainder of a division by 10 using the Modulus operator.
if (day % 10 == 1)
{
result = "dan";
}
else
{
result = "dana";
}
Or if you want to avoid a normal if:
result = "dan" + (day % 10 == 1 ? "" : "a");
% is the Javascript Modulus operator. It gives you the remainder of a division:
Example:
11 / 10 = 1 with remainder 1.
21 / 10 = 2 with remainder 1.
31 / 10 = 3 with remainder 1.
...
See this answer: What does % do in JavaScript? for a detailed explication of what the operator does.
Modulus operator. You can research it but basically you want to detect if a number when divided by 10 has a remainder of 1:
if( day%10 == 1)
this can be solved by single line
return (day % 10 == 1) ? 'dan' : 'dana';
You can convert the number to a string and use String.prototype.endsWith().
const number = 151
const isMatch = number.toString().endsWith('1')
let result = ''
if (isMatch) {
result = 'dan'
} else {
result = 'dana'
}
I'm using it in some code that sets the ordinal. For example, if you want to display 1st, 2nd, 3rd, or 4th:
let ordinal = 'th';
if (number.toString().endsWith('1')) {
ordinal = 'st'
}
if (number.toString().endsWith('2')) {
ordinal = 'nd'
}
if (number.toString().endsWith('3')) {
ordinal = 'rd'
}
Related
I am doing an exercise, the problem is that my if/else structure does not work properly and I do not know why.
Here is the exercise statement and my code
Your task is to write a function, fizzBuzz, that accepts a number and returns a string:
'fizz' if the number is divisible by 3;
'buzz' if the number is divisible by 5;
'fizzbuzz' if the number is divisible by both 3 and 5.
'{number}' if the number doesn't fulfil any of the above conditions.
function fizzBuzz(number) {
if (number % 3 === 0) {
return "fizz"
};
if (number % 5 === 0) {
return "buzz"
};
if (number % 3 === 0 && number % 5 === 0) {
return "fizzbuz"
};
else return number
}
Try a little mental debugging. Look at your code and run different values through it in your mind:
What happens if you run the value 6 through it?
What happens if you run the value 10 through it?
What happens if you run the value 15 through it?
Ask yourself, "How could I fix this?" (hint: order of operations is important).
Something like this would do what you expect:
function fizzBuzz(n) {
const fizz = n % 3 ? '' : 'fizz' ;
const buzz = n % 5 ? '' : 'buzz' ;
return !fizz && !buzz ? '{number}' : `${fizz}${buzz}` ;
}
or this:
function fizzBuzz( n ) {
let s;
if ( n % 3 === 0 ) {
s = 'fizz' ;
if ( n % 5 === 0 ) {
s = 'fizzbuzz' ;
}
} else if ( n % 5 == 0 ) {
s = 'buzz' ;
} else {
s = '{number}' ;
}
return s;
}
This does [at most] 2 divisions and 2 comparisions.
The former does 2 divisions and 3-4 comparisons, so it is nominally less efficient.
But I know which version I'd rather look at.
The problem is, if a number is divisible by 5 and 3 (ex 15) "fizz" would only be returned (as a factor of 3) because every block {...} terminates the function with a return (this technique is called a "short-circuit", which isn't a bad practice). So you need to put the 5 and 3 condition first. Also that condition had an undefined variable called solution so that would've been the first error. One minor thing is that each block {...} was suffixed with a semi-colon: ; which is just bad formatting but it doesn't affect functionality.
function fB(number) {
if (number % 3 === 0 && number % 5 === 0) {
return "fizzbizz";
}
if (number % 3 === 0) {
return "fizz";
}
if (number % 5 === 0) {
return "bizz";
}
return number;
}
console.log(fB(15));
console.log(fB(575));
console.log(fB(49));
console.log(fB(51));
console.log(fB(80));
console.log(fB(375));
console.log(fB(99));
console.log(fB(Infinity));
I was trying to solve this problem on a leet code called Rotate digits.
This is the working solution of the problem in Javascript :
var IsGood = function(n){
let result = false;
while(n > 0){
let digit = n % 10; // 2 % 10
// ignore 0, 1, 8; by themselves, no change
if( (digit === 3) || (digit === 4) || (digit === 7) ) return false;
if( (digit === 2) || (digit === 5) || (digit === 6) || (digit === 9) ) result = true;
n /= 10;
}
return result;
}
var rotatedDigits = function(N) {
let count = 0;
for(let i = 1; i <= N; i++){
if(IsGood(i)) count++;
}
return count;
}
My question inside the IsGood function why are we taking n % 10 and then dividing n /=10. I have seen this implementation in almost all solutions to this problem. Can someone please explain the logic behind this?
Take the number 123
The remainder of that number when divided by 10 is 3 (123 % 10) = 3.
So n%10 is giving you the last digit of the number
If you want to test the next digit in the number you have to remove the 3. The way to do that is to divide by 10 and only take the integer part (12.3 lose the .3 part) which you get by 123 / 10
You can keep doing that until you get to a number less than 10 which must be the final digit! this algorithm is a way to examine each digit in a number using math rather than string manipulation
123 % 10 = 3 first digit
123 / 10 = 12
12 % 10 = 2 next digit
12 / 10 = 1
1 < 10 so final digit
Write a javascript program that displays the numbers from 10 to 100. But for multiples of 4 print "Penny" instead of the number and for multiples of 6 print "Leonard". For numbers which are multiples of both 4 and 6 print "Bazzinga"
I know how to do two parts struggling to print 6 and 4;
function baZzinga (number) {
for (var number = 10; number <= 101; number++)
if(number % 4 == 0) {
console.log("penny");
}
else if (number % 6 == 0) {
console.log("Leonard");
} else if ( not sure what goes here) {
help help help
} else {
console.log(number");
}
You want the and condition first. Try this
var result = document.getElementById("result");
function baZzinga (number) {
for (var number = 10; number <= 101; number++) {
if (number % 4 == 0 && number % 6 == 0) {
result.innerHTML += "Bazinga";
}
else if(number % 4 == 0) {
result.innerHTML += "penny";
}
else if (number % 6 == 0) {
result.innerHTML += "Leonard";
}
else {
result.innerHTML += number;
}
}
}
baZzinga()
<p id="result"></p>
I changed console.log to result.innerHTML because I wanted to demonstrate it in a snippet.
I have a few comments on your code -- constructive criticism, I hope! First, you don't need the number parameter in your bazzinga function. Next, the indentation of the code you posted makes it hard to read. Finally, you should almost always use === instead of ==. The === tests for strict equality, whereas == tries to do some type conversions first (and can therefore produce unexpected results). See the official docs.
To answer you question: check for divisibility by 6 AND 8 first. That way, it will override the individual cases. I believe you want something like this:
function bazzinga() {
for (var number = 10; number <= 100; number++) {
if (number % 4 === 0 && number % 6 === 0) {
console.log("Bazzinga");
} else if (number % 4 === 0) {
console.log("Penny");
} else if (number % 6 === 0) {
console.log("Leonard");
}
}
}
Here is a solution using the format you posted:
for (var number = 10; number <= 100; number++) {
if(number % 4 === 0 && number % 6 === 0){
console.log("bazzinga");
} else if(number % 4 === 0) {
console.log("penny");
} else if (number % 6 === 0) {
console.log("Leonard");
} else {
console.log(number);
}
}
Or use the ternary operator to be even more succinct!
for (var i = 10; i <= 100; i++){
var penny = i % 4 === 0;
var leonard = i % 6 === 0;
console.log(penny ? (leonard ? "bazzinga" : "penny"): leonard ? "leonard" : i);
}
function process_num(num) {
return num % 4 == 0 ? num % 6 == 0 ? "Bazzinga" : "Penny" : num % 6 == 0 ? "Leonard" : num;
}
for (x = 10; x <= 100; x++) { console.log( x + ': is ', process_num(x)) }
Nested Ternary operator for conciseness
If it passes outer ternary test it is divisible by 4:
Enter into nested termary one to test if num is also divisible by 6 for the BaZzinga prize!!
If it fails the BaZzinga challenge, we know it previously passed the divisible by 4 test so print "penny"
Failing the outer ternary condition, we know it's not divisible by 4:
Enter nested ternary two to consider if divisible by 6. If so print "Leonard".
If not it's failed both the outer (div by 4) and inner (div by 6) so return the number unchanged.
Now that the logic is contained in the function, we can just create a for loop to iterate over the required numbers printing out the correct values.
For example if the number 752 contains the number 5? Whats the best way to check? Convert to string or divide into individual digits?
Convert to string and use indexOf
(752+'').indexOf('5') > -1
console.log((752+'').indexOf('5') > -1);
console.log((752+'').indexOf('9') > -1);
Convert to string and use one of these options:
indexOf():
(number + '').indexOf(needle) > -1;
includes():
(number + '').includes(needle);
You can use 3 ways:
Check it by string contains:
var num = 752;
num.toString().indexOf('5') > -1 //return true or false - contains or not
Check by loop
var f = 2;
while(num > 0 ){
if( num % 10 == f){
console.log("true");
break;
}
num = Math.floor(num / 10);
}
Check by regular expressions
num.toString().match(/5/) != null //return true if contains
function checkNumberIfContainsKey(number, key){
while(number > 0){
if(number%10 == key){
return true;
}
number = Math.trunc(number / 10);
}
return false;
}
console.log(
checkNumberIfContainsKey(19, 9), //true
checkNumberIfContainsKey(191, 9), //true
checkNumberIfContainsKey(912, 9), //true
checkNumberIfContainsKey(185, 9) //false
);
The most efficient solution among available answers because of the complexity of this program is just O(number of digits) if number = 10235 then the number of digits = 5
You can also use "some" function.
"Some"thing like this:
function hasFive(num){
return num.toString().split("").some(function(item){
return item === "5";
});
}
and then you can call it:
hasFive(752)
Further improved is that you make a function that takes number and digit you want to check:
function hasNumber(num, digit){
return num.toString().split("").some(function(item){
return item == digit;
});
}
And then call it in similar way:
hasNumber(1234,3) //true
hasNumber(1244,3) //false
So that way we can check any number for any digit.
I hope so "some"one will find this useful. :)
I want to check if a value is a multiple of a certain number, for example, multiples of 10, but I also want to be able to change it to whatever I want.
if (directWinner == 10){
}
You'd use the modulus operator for that :
if (directWinner % 10 === 0){
directWinner = 20;
}
Added a small dose of jQuery for no good reason at all ?
$.modu = function(check, against) {
return check % against === 0;
}
if ( $.modu(directWinner, 10) ) {
directWinner = 20;
}
You'd use the modulo operator % for that:
var certainNumber = 10;
if (directWinner % certainNumber === 0) {
// directWinner is a multiple of certainNumber
}
Use the modulo operator (assuming positive integers) :
if (directWinner % 10 === 0) {
...
}