function evenNumbers(minNumber, maxNumber){
var str = minNumber;
for (i=minNumber; i<=maxNumber; i++){
if (minNumber%2 ==0){
str += ',' + i;
}
}
return str;
}
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4,13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3,10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8,21));
So, what I want the code to do is that in the given numbers in console.log,
for example, (4,13) it should print all the numbers that are EVEN between 4 and 13. However, instead of giving all the even numbers, the function gives me all the numbers that are between 4,13. How Could I fix the problem?
p.s is there any strcmp in javascript?
Wrong variable in if statement inside for loop.
if (minNumber%2 ==0){
str += ',' + i;
}
Should be
if (i%2 ==0){
str += ',' + i;
}
I presume you want to show the numbers between the min and max but not including either the min or max. In other words, evenNumbers(4,8) should just show 6. I also presume that both the min and max values will be integers.
I put all the logic in the for loop parameters, with the for loop body just placing those numbers and a comma into the output string. The final return value removes the last comma.
function evenNumbers(minNumber, maxNumber){
let str = '';
for (let i = Math.ceil((minNumber + 0.5) / 2) * 2; i < maxNumber; i += 2) {
str += `${i},`;
}
return str.slice(0,-1);
}
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4,13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3,10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8,21));
console.log('evenNumbers(-8,5) returns: ' + evenNumbers(-8,5));
console.log('evenNumbers(-7,-2) returns: ' + evenNumbers(-7,-2));
console.log('evenNumbers(5,6) returns: ' + evenNumbers(5,6));
console.log('evenNumbers(10,2) returns: ' + evenNumbers(10,2));
Related
I gave an example of using .tofixed() with math, functions, and arrays, to a beginner coder friend who has been reviewing these topics in his class.
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
};
bananaDivision();
They were understanding and following along no problem.
Then they asked me - "What if we put a decimal in the .toFixed ?"
So I ran:
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
let bananaFixed1 = bananaDivided.toFixed(.69420);
let bananaFixed2 = bananaDivided.toFixed(1.69420);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
console.log("After using .toFixed(.69420) : " + bananaFixed1 + '\n');
console.log("After using .toFixed(1.69420) : " + bananaFixed2 + '\n');
};
bananaDivision();
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
Am I correct? For my own curiousity, is there a crazy way to break .toFixed() so that it actually uses decimals? I'm experimenting atm but wanted to know if someone already figured that out.
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
This would be correct. That is essentially what happens.
For full correctness, the input of toFixed() will be converted to an integer. The specification states that the argument must first be converted to a number - NaN will be converted to a zero. Numbers with a fractional part will be rounded down.
Which means that if you pass any number, you essentially get the integer part of it.
It also means that non-numbers can be used:
const n = 3;
console.log(n.toFixed("1e1")); // 1e1 scientific notation for 10
You're close, since toFixed() expects an integer it will handle converting decimal numbers before doing anything else. It uses toIntegerOrInfinity() to do that, which itself uses floor() so the number is always rounded down.
Most of Javascript handles type conversion implicitly, so it's something you should really understand well if you don't want to run into problems. There's a free book series that explains that concept and a lot of other important Javascript knowledge very well, it's called You Don't Know JS Yet.
just a demo how .tofixed works !!!!!!
function roundFloat(x, digits) {
const arr = x.toString().split(".")
if (arr.length < 2) {
return x
}else if(arr[1] === ""){
return arr[0]
}else if(digits < 1){
return arr[0]
}
const st = parseInt(x.toString().split(".")[1]);
let add = false;
const rudgt = digits
const fX = parseInt(st.toString().split("")[rudgt]);
fX > 5 ? add = true : add = false
nFloat = parseInt(st.toString().split("").slice(0, rudgt).join(""))
if (add) {
nFloat += 1
}
const repeat0 = (() => {
if (rudgt - st.toString().length < 0) {
return 0
}
return rudgt - st.toString().length
})()
const output = x.toString().split(".")[0] + "." + nFloat.toString() + "0".repeat(repeat0);
return output
}
console.log(roundFloat(1.200, 2))
I'm trying to solve the following Kata:
a 2 digit number, if you add the digits together, multiply by 3, add 45 and reverse.
I'm unable to figure out how to return the data from my function so that I can later assign the value to an HTML element.
This is my code.
function daily() {
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
}
} else {
console.log("Not a 2 digit Number!!");
}
}
teaser(j);
}
}
From your question I'm guessing you need reversal value on function daily for loop.
Would recommend you to take out function teaser from inside for-loop, this will make code much cleaner and easy to understand and you can do like:
function daily() {
for(var j = 10; j < 100; j++) {
var teaser = teaser(j);
// Can now use anything returned from teaser function here
}
}
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
return reversal;
}
} else {
console.log("Not a 2 digit Number!!");
return false;
}
}
If don't want to take function out then you can do this:
function daily() {
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
return reversal;
}
} else {
console.log("Not a 2 digit Number!!");
return false;
}
}
var teaser = teaser(j);
// Can now use anything returned from teaser function here
}
}
Returning something from a function is very simple!
Just add the return statement to your function.
function sayHello(name) {
return 'Hello ' + name + '!';
}
console.log(sayHello('David'));
okay, so my issue has been solved! Thanks all of you, especially krillgar, so I had to alter the code you gave me krillgar, a little bit in order to populate the results array with only the numbers (one number in this case) that satisfy the parameters of the daily tease I was asking about. yours was populating with 89 undefined and on number, 27 because it is the only number that works.
One of my problems was that I was expecting the return statement to not only save a value, but also show it on the screen, but what I was not realizing was that I needed a place to store the value. In your code you created a result array to populate with the correct numbers. And also, I needed a variable to store the data for each iteration of the for loop cycling through 10 - 100. Anyways, you gave me what I needed to figure this out and make it do what I wanted it to do, and all is well in the world again.
Anyway, thank you all for your help and input, and I will always remember to make sure I have somewhere to store the answers, and also somewheres to store the value of each loop iteration in order to decide which numbers to push into the results array and save it so it can be displayed and/or manipulated for whatever purpose it may be. I guess I was just so busy thinking about the fact that when I returned num it didn't show the value, instead of thinking about the fact that I needed to store the value. Here is the final code for this problem and thanks again peoples!
function daily() {
var results = [];
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
return num;
// Here you have one that is correct, so return it:
} else {
console.log(num + " does not fulfill function parameters");
// This is just so you can visualize the numbers
return null;
}
}
}
var answer = teaser(j);
if(answer != null) {
results.push(answer);
}
}
return results;
}
As was said in the comments of the question, because you're going to (most likely) have multiple answers that match your condition, you will need to store those in an array. Your teaser function returns individual results, where daily will check all the numbers in your range.
function daily() {
var results = [];
for(var j = 10; j < 100; j++) {
function teaser(num) {
var x = num;
var y = x.toString().split("");
if(y.length == 2) {
var sum = parseInt(y[0]) + parseInt(y[1]);
if(sum * 3 == x) {
console.log(x + " is equal to 3 times " + sum);
var addFortyFive = x + 45;
console.log("Adding 45 to " + x + " gives " + addFortyFive);
var reversal = parseInt(addFortyFive.toString().split('').reverse().join(''));
console.log("'The 2 digit number " + x + ", is 3 times the sum (" + sum + ") of its digits. If 45 is added to " + x + ", the result is " + addFortyFive + ". If the digits are reversed, the number is... " + reversal + ".");
// Here you have one that is correct, so return it:
return num;
} else {
// Make sure we don't return undefined for when the sum
// times three doesn't equal the number.
return null;
}
} else {
console.log("Not a 2 digit Number!!");
return null;
}
}
var answer = teaser(j);
if (answer !== null) {
results.push(answer);
}
}
return results;
}
I am currently trying to complete an assignment for an intro2Javascript course. The question basically asks me to return a string of multiples of 2 parameters (num, numMultiple). Each time it increments the value i until i = numMultiple. For example:
5 x 1 = 5\n
5 x 2 = 10\n
5 x 3 = 15\n
5 x 4 = 20\n
This was my attempt:
function showMultiples(num, numMultiples) {
var result;
for (i = 1; i <= numMultiples; i++) {
result = num * i
multiples = "" + num + " x " + i + " = " + result + "\n"
return (multiples)
}
}
...and because the assignment comes with pre-written console logs:
console.log('showMultiples(2,8) returns: ' + showMultiples(2, 8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3, 2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5, 4));
console.log('\n');
This is my output:
showMultiples(2,8) returns: 2 x 1 = 2
Scratchpad/1:59:1
showMultiples(3,2) returns: 3 x 1 = 3
Scratchpad/1:60:1
showMultiples(5,4) returns: 5 x 1 = 5
UPDATE
You were doing two things incorrectly:
1) You were returning after the first iteration through your loop
2) You were assigning to multiples instead of appending to it.
Since you want to gather all the values and then show the final result first, I add all of the values to an array, and then use unshift() to add the final element (the result) to the beginning of the array. Then I use join() to return a string representation of the desired array.
function showMultiples(num, numMultiples) {
var result;
var multiples = [];
for (let i = 1; i <= numMultiples; i++) {
result = num * i
multiples.push("" + num + " x " + i + " = " + result + "\n")
}
multiples.unshift(multiples[multiples.length-1]);
return (multiples.join(''))
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2, 8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3, 2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5, 4));
console.log('\n');
You need to declare all variables, because without you get global variables (beside that it does not work in 'strict mode').
The second point is to use multiples with an empty string for collecting all intermediate results and return that value at the end of the function.
For keeping the last result, you could use another variable and append that value at the end for return.
function showMultiples(num, numMultiples) {
var i,
result,
multiples = "",
temp = '';
for (i = 1; i <= numMultiples; i++) {
result = num * i;
temp = num + " x " + i + " = " + result + "\n";
multiples += temp;
}
return temp + multiples;
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2, 8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3, 2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5, 4));
As other answers say, your problem is in multiple.
You are clearing multiple every iteration and storing the new value, but you do not want that, you want to add the new result, and to do so you use this code:
multiples = multiple + "" + num + " x " + i + " = " + result + "\n"
which can be compressed in what the rest of the people answered:
multiples += "" + num + " x " + i + " = " + result + "\n"
Probably you already know, but to ensure:
a += b ---> a = a + b
a -= b ---> a = a - b
a *= b ---> a = a * b
and there are even more.
So I technically already solved this issue, but I was hoping for a better solution using some funky regex.
The issue is:
We got strings this:
2+{2+(2)},
10+(20+2)+2
The goal is to match the 'plus' signs that are not in any sort of bracket.
i.e. in the previous strings it should match
2 + {2+(2)} ,
10 + (20+2) + 2
at the moment what I am doing is matching all plus signs, and then checking to see if the sign has any bracket in front of it (using regex), if it does then get rid of it.
I was hoping for a neater regex solution, is that possible?
To reiterate, I need the location of the strings, at the moment I am using javascript to do this, so ideally a js solution is preferred, but the pattern is really what I am looking for.
You could perhaps just replace everything inside () or {} with spaces:
'10 + (20+2) + 2'.replace(/\([^)]*?\)|\{[^}]*?\}/g, m => ' '.repeat(m.length));
This would result in
10 + + 2
Meaning the position of the strings aren't changed.
Note: It won't work well with nested things of the same type, ex (1 + (1 + 1) + 1), but it works with (1 + { 1 + 1 } + 1).
Bigger solution, using the same logic, but that works with nested stuff
var input = '10 + { 1 + (20 + (1 + { 3 + 3 } + 1) + 2) + 2 }';
var result = [];
var opens = 0;
for (var i = 0; i < input.length; ++i) {
var ch = input[i];
if (/\(|\{/.test(ch)) {
opens++;
result[i] = ' ';
}
else if (/\)|\}/.test(ch)) {
opens--;
result[i] = ' ';
}
else {
if (!opens) result[i] = input[i];
else result[i] = ' ';
}
}
result = result.join('');
// "10 + "
I want a function like
string getAlphabetEncoding(num){
//some logic
return strForNum;
}
input: 1 output: a, input: 5 output: e, input: 27 output: aa, input: 676 output: YZ, input: 677 output: za...
I think you are trying to convert from Base 10 to Bijective Base 26 (spreadsheet column notation), otherwise known as the hexavigesimal system.
You list JavaScript as a language of interest, so I have targeted it. The code below performs that conversion, but note that the outputs are not what you suggest in your question. I have verified them with my spreadsheet program and found them to be correct, so I am assuming the values in our question are wrong.
Number.prototype.toBijectiveBase26 = (function () {
return function toBijectiveBase26() {
n = this
ret = "";
while(parseInt(n)>0){
--n;
ret += String.fromCharCode("A".charCodeAt(0)+(n%26));
n/=26;
}
return ret.split("").reverse().join("");
};
}());
Number(1).toBijectiveBase26(); //Returns A
Number(5).toBijectiveBase26(); //Returns E
Number(27).toBijectiveBase26(); //Returns AA
Number(676).toBijectiveBase26(); //Returns YZ
Number(677).toBijectiveBase26(); //Returns ZA
Give this a try:
var ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function getNameFromNumber(num) {
var numeric = (num - 1) % 26;
var letter = ABC[numeric];
var num2 = parseInt((num - 1) / 26);
if (num2 > 0) {
return getNameFromNumber(num2) + '' + letter;
} else {
return letter;
}
}
var data = document.getElementById('data');
data.innerHTML += 1 + ' -> ' + getNameFromNumber(1) + '<br>'; //A
data.innerHTML += 5 + ' -> ' + getNameFromNumber(5) + '<br>'; //E
data.innerHTML += 27 + ' -> ' + getNameFromNumber(27) + '<br>'; //AA
data.innerHTML += 676 + ' -> ' + getNameFromNumber(676) + '<br>'; //YZ
data.innerHTML += 677 + ' -> ' + getNameFromNumber(677) + '<br>'; //ZA
<div id=data></div>