How could i get numbers instead of Nan? [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I've been doing some challenge to create Fibonacci numbers generator,and got stack. It seemed like i have a solution, but those NaN's is the last problem i cant't deal with.
function fibonacciGenerator (n) {
var output = [];
if( n === 2 ){
output.push(0,1);
}
else if( n === 1 ){
output.push(0);
}
else{
output = [0,1];
while( n > output.length){
output.push((output[output.length - 2]) + (output[output.lenght - 1]));
}
}
return output
}
So when i use function with n=3 and higher, it pushes sum of the two last numbers of output array into that array, till n< output.length. And everything works, loop stops when n=output.lenght, but i got back NaN's, not numbers. What am i doing wrong?

Mispelled length as lenght here
while( n > output.length){
output.push((output[output.length - 2]) + (output[output.lenght - 1]));
}
}

function fibonacciGenerator(n) {
var output = [];
if (n === 2) {
output.push(0, 1);
}
else if (n === 1) {
output.push(0);
}
else {
output = [0, 1];
while (n > output.length) {
// problem was here output.length was misspelld
output.push((output[output.length - 2]) + (output[output.length - 1]));
}
}
return output
}
console.log(fibonacciGenerator(5))

Related

Please help to translate code Pascal to JS? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I have task: On a sheet of paper, a rectangle is drawn along the grid lines. After that, the number of grid nodes located inside, but not on the border of the rectangles, and the number of single grid segments inside the rectangle were counted. Write a program that uses this data to determine the size of a rectangle.
I have this code in Pascal:
var
K,N,i,j:integer;
begin
readln(K,N);
for i:=1 to trunc(sqrt(K)) do
if K mod i = 0 then
begin
if i*(K div i+1)+(K div i)*(i+1)=N then writeln(i+1,' ',K div i+1);
end;
end.
And this my code in JavaScript:
const a = [1000, 2065]
function Sum(K, N) {
for (i = 1; i < Math.trunc(Math.sqrt(K)); i++) {
if (K % i === 0 && i * (Math.floor(K / (i) + 1) + Math.floor(K / i) * (i + 1)) === N) {
break;
}
}
console.log(i + 1, Math.floor(K / (i)) + 1)
}
Sum(a[0], a[1]);
Can you help why my answers in JavaScript are wrong?
Not exactely sure what you're trying to achieve but this javascript code produces the same output (26, 41) as your pascal version does:
See onlinegdb.com!
const K = 1000, N = 2065;
for (let i=1; i<Math.trunc(Math.sqrt(K)); i++)
if (K % i === 0)
if (i*(K / i+1)+(K / i)*(i+1) === N)
console.log(i+1, K / i+1);
I think you have messed something up with the brackets in Math.floor or something similar.

Check numbers in a range that contain or are divisible by 7 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I don't know what is the problem with this code I just need to know
how many number from Start to end that divide by 7 or has 7.
const divideOrHasSeven = (start, end) => {
var x = 0;
for (i = start; i <= end; i++) {
if (i % 7 || i.toString().indexOf("7")) { // if it is divide by 7 or has 7
x += 1;
}
}
return x;
};
The problem is i.toString().indexOf('7') will always return a truthy value EXCEPT (ironically) when 7 is actually in the number (inthe first position - index zero)
Change your conditional to if (i%7===0 || i.toString().indexOf('7')>-1)
You had some problems with your code.
If you compare with this, I think you will understand where.
This i.toString().indexOf('7') will return -1 if 7 is not found in string, which will be evaluated as true.
You also had some syntax errors.
const divideOrHasSeven = (start, end) => {
var x = 0;
for (i = start; i <= end; i++) {
if (i%7 === 0 || i.toString().indexOf('7') >= 0) {
x += 1;
}
}
return x
}
console.log(divideOrHasSeven(1, 200));

JavaScript coding problem called FizzBuzz [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to figure out what I am doing wrong with this problem. I seem to be missing something that is not allowing my code to work. I need to use a function to create an array that takes one number n, and that loops through an array from the numbers 1 - 16, while also replacing all the numbers divisible by 3 with the string 'fizz', and all divisible by 5 with the word 'buzz', and any number that is divisible by both must be replaced by the string 'fizzbuzz'.
I have gone over this several times but for some reason keep coming up with just an empty array for my result when it is logged to the console. I would greatly appreciate it if someone could give me some tips as to why my code isn't working so that I can understand the concept easier. Here is my code:
const results = [];
const fizzbuzz = (n) => {
var results = []
for (let n = 1; results.length < 16; n++) {
if (n % 3 === 0 && n % 5 === 0) {
results.push('FizzBuzz')
} else if (n % 3 === 0) {
results.push('fizz');
} else if (n % 5 === 0) {
results.push('buzz')
} else {
results.push(n)
}
}
return results
};
fizzbuzz(16);
console.log(results);
This is what it is supposed to come out to:
[1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16]
But this is what I keep getting as an answer:
[]
Your fizzbuzz function returns results, so just assign that to a variable and log it:
var results = fizzbuzz(16);
console.log(results);
You are playing with another results inside the function, and outside the function result will remain empty. If you remove the variable which is inside the function now every manipulation will be on the same variable.
const results = [];
const fizzbuzz = (num) => {
for(let n=1; n<num; n++){
if(n%3 === 0 && n % 5 === 0){
results.push('FizzBuzz')
}
else if(n % 3 === 0){
results.push('fizz');
}
else if(n % 5 === 0){
results.push('buzz')
}
else {
results.push(n)
}
}
};
fizzbuzz(16);
console.log(results);
Your first issue is that the results variable declared outside your function and the results variable declared inside your function are totally different variables. You only need to declare the variable in the function, then you can make a new variable to hold the function result:
const res = fizzbuzz(16);
console.log(res);
or even simpler:
console.log(fizzbuzz(16));
The second issue is in your for loop, you are reassigning n when you should be making a new variable (most commonly called i). You also use a static number (16) as your limit in the expression results.length < 16, when you should use the variable n:
for (let i = 0; results.length < n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
results.push('FizzBuzz')
} else if (i % 3 === 0) {
results.push('fizz');
} else if (i % 5 === 0) {
results.push('buzz')
} else {
results.push(i)
}
}
Overall you are taking the correct approach, but you should review variables and for loops as you are using both a bit incorrectly.
There are two glaring issues with your code.
You define the variable results twice, one as a constant and one as var.
If you remove the var results = [] definition, your code will work, as it's able to store the results through closures. Basically, the scope of your const results encapsulates the scope of your function, so your function will have access to const results = []
Your function isn't returning anything. This wouldn't be a problem if you were attempting to store the results via closures, but looking at your code, that wasn't your intention. What you should've done is store the results in a variable, as
const results = fizzbuzz(16)
This is my FizzBuzz implementation that uses Array.from() to generate an array with the fizz/buzz/number according to the rules:
const fizzbuzz = length => Array.from({ length }, (_, i) => {
if (i % 3 === 0 && i % 5 === 0) return 'FizzBuzz';
if (i % 3 === 0) return 'fizz';
if (i % 5 === 0) return 'buzz';
return i;
})
const results = fizzbuzz(16); // assign the return value of the function to results
console.log(results);

Find extra character between two strings [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can I find an extra character between two strings in an optimal way.
Ex1: S1 - 'abcd', S2 - 'abcxd', output - 'x'
Ex2: S1 - '100001', S2 - '1000011', output - '1'
We can do this by traversing linearly and comparing each character in O(n). I want this to be done in much more optimal way, say in O(logn)
Baseline method (O(n)): Just comparing chars and narrowing in on both sides each cycle.
function findDiffChar(base, baseExtraChar) {
let extraLastIndex = base.length;
let lastIndex = extraLastIndex - 1;
for (let i = 0; i < extraLastIndex / 2; i++) {
console.log(`Loop: ${i}`);
if (base[i] !== baseExtraChar[i])
return baseExtraChar[i];
if (base[lastIndex - i] !== baseExtraChar[extraLastIndex - i])
return baseExtraChar[extraLastIndex - i];
}
return false;
}
console.log(findDiffChar('FOOOOOAR', 'FOOOOOBAR')); // B
Improved method using binary search (O(log n)): Compare halves until you've narrowed it down to one character.
function findDiffChar(base, baseExtraChar) {
if (baseExtraChar.length === 1) return baseExtraChar.charAt(0);
let halfBaseLen = Number.parseInt(base.length / 2) || 1;
let halfBase = base.substring(0,halfBaseLen);
let halfBaseExtra = baseExtraChar.substring(0,halfBaseLen);
return (halfBase !== halfBaseExtra)
? findDiffChar(halfBase, halfBaseExtra)
: findDiffChar(base.substring(halfBaseLen),baseExtraChar.substring(halfBaseLen));
}
console.log(findDiffChar('FOOOOAR', 'FOOOOBAR')); // B
console.log(findDiffChar('---------', '--------X')); // X
console.log(findDiffChar('-----------', '-----X-----')); // X
console.log(findDiffChar('------------', '---X--------')); // X
console.log(findDiffChar('----------', '-X--------')); // X
console.log(findDiffChar('----------', 'X---------')); // X

Math.pow() floating point number as exponent [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I want to pass a floating-point number as the second argument (exponent) to Math.pow(). I always get NaN when the passed number is not a whole number, like 0, 2, 7, you name it. Is there a working way in javascript to make this work?
(function () {
var notice = document.getElementById('notice');
var value = 0.0;
var interval = 0.02;
var timeInterval = 10;
function interpolation(x) {
var y = Math.pow(Math.e, x); // <<< HERE >>>
console.log(x, y);
return y;
}
function animation() {
var callAgain = true;
if (value >= 1) {
value = 1.0;
callAgain = false;
}
notice.style['opacity'] = interpolation(value);
notice.style['marginTop'] = (value * 20 + 20) + 'px';
value += interval;
if (callAgain) {
setTimeout(animation, timeInterval);
}
}
animation();
})();
PS: Please don't comment, that an opacity greater than 1 doesn't make any sense. I know that e^x; x > 0 will yield values greater than 1. I'll insert a proper function when I got this working.
The constant is Math.E, not Math.e

Categories