Javascript Fib series test case fails - javascript

I am trying to complete this assignment for the Javascript Fibonacci series. The logic works for input 5 and 6. But the test case for 8 fails.
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out = out+ ""+ fib[i];
console.log("i is" + i + " out is" + out);
}
return out;
}
I cannot figure out what is going wrong..

It seems like things are just getting messed up with how you are adding the items to the string. Since there is no space between out + "" + fib[i], I think that would be messing with the formatting. Once i had spaces it seems to work fine, a double digit number wouldnt mess with a string like that.
function fibonacciSequence(input) {
var fib = [];
fib[0] = 0;
fib[1] = 1;
let out = ""
out+= ` ${0} `
out+= `${1}`
for (let i=2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out+= ` ${fib[i]}`
}
return out;
}

You are comparing the input (which it seems like this is maybe the number you want to stop at) to i which (plus or minus a bit) is the number of numbers in the list. You probably want to be comparing fib[i], or something like it to input to decide whether to terminate the loop.
Edit: If that's wrong and you do want input to be the number of numbers in the list, then you could just join fib at the end:
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
//var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
//out = out+ ""+ fib[i];
//console.log("i is" + i + " out is" + out);
}
return fib.join(' ');
}
for(let j = 0; j < 9; j++)
console.log('input: ' + j + ' :: ', fibonacciSequence(j));
Unless ... I've got the wrong end of the stick and #Grant Herman's answer already does what you want?

Related

What is the minimum number of push operation in reversing A B C D in stack?

I Have coded to reverse the ABCD string with using push and pop operation in Javascript
var count = 0;
function reverse(str) {
let stack = [];
// push letter into stack
for (let i = 0; i < str.length; i++) {
stack.push(str[i]);
count++
}
// pop letter from the stack
let reverseStr = '';
while (stack.length > 0) {
reverseStr += stack.pop();
}
return reverseStr;
}
console.log(reverse("ABCD") + count);
What is the minimum number of push operation in reversing ABCD?
The maximum number should be either 3 or 4 depending on how you do it. Firstly, you should be using unshift() rather than push() as you really only need to push a character into the front of the array. So:
let count;
function reverse(str) {
count = 0;
let stack = [];
// push letter into stack
for (let i = 0; i < str.length; i++) {
stack.unshift(str[i]);
count++
}
return stack.join("");
}
let stringA = "ABCD";
console.log(stringA + " => " + reverse(stringA) + ": " + count);
However, as others have suggested, you could just move letters, going backwards from the one before the final character, and shifting them to the end:
let count;
function reverse2(str) {
count = 0;
let str2 = str.split("");
let sLength = str2.length;
for (let i = (sLength - 2); i >= 0; i--) {
let s = str2.splice(i, 1).toString();
str2.push(s);
count++
}
return str2.join("");
}
let stringB = "ABCD";
console.log(stringB + " => " + reverse2(stringB) + ": " + count);
In both cases, you could check for matching consecutive characters - eg, in good, you have two o's. But that would complicate things as you would be continually checking for this.
you don't even need the push operations if you are using JS str.split('').reverse().join('') and by the way it only takes 3 push operations.
Minimum number of Push Operation is equal to length of string as stack follows Last In First Out Order.

in my function it runs document.write 10 times what i specified

when I try to run
function thing(number) {
for (i = 1; i < number+1; i++){
document.write(i + ' ');
}
}
var otherthing = prompt("");
thing(otherthing);
when it loops document.write(i); it loops 10 times more than specified
I've messed around a bit and can't get it. i'm also kind of new to JavaScript and i'm open to any other tips or feedback
Tell me if this works for you.
function thing(aNumber) {
aNumber = Number(aNumber) + 1;
for (i = 1; i < aNumber; i++){
document.write(i + ' ');
}
}
var otherthing = prompt("");
thing(otherthing);
Edit: The reason why the code wasn't working before is because the input from the prompt was being interpreted as a string, not a number. So the Number(aNumber) part is really what makes this edit work, as that explicitly tells JavaScript that the variable is a number, not a string. Also, I suspect 'number' is a keyword that can't be used for variables, just like you can't use the words 'function' or 'var' as variables. So I changed it to 'aNumber' instead of 'number'.
Try this you forget to parse it into integer
function thing(number) {
for (i = 1; i < number+1; i++){
document.write(i + ' ');
}
}
var otherthing = parseInt(prompt(""));
thing(otherthing);
Otherwise you can use like this as well
function thing(number) {
for (i = 1; i < number+1; i++){
document.write(i + ' ');
}
}
var otherthing = prompt("");
thing(+otherthing);
as explained by Jaromanda X, data type of number argument on function thing is string not int, float or other number data type. So you need to change it to number first. Something like this :
function thing(number) {
for (let i = 1; i < Number(number)+1; i++){
document.write(i + ' ');
}
}
var otherthing = prompt("");
thing(otherthing);
Use Number for convert string to number :
for (i = 1; i < Number(number) + 1 ; i++) {
function thing(number) {
for (i = 1; i < Number(number) +1 ; i++) {
document.write(i + ' ');
}
}
var otherthing = prompt("");
thing(otherthing);

Calling concatenated variables in Javascript

Is there a way to include variables in each iteration of a javascript loop? For example if I put this code into a loop
if (e1) {item_text += '{id:"' + id[1] + '",lvl:' + e1lvl + '},<wbr>'}
if (e2) {item_text += '{id:"' + id[2] + '",lvl:' + e2lvl + '},<wbr>'} // etc
and do something like
for (n = 0; n < id.length; n++) {
if (e/*concat var e w/var n?*/) {
item_text += '{id:"' + id[1] + '",lvl:' + e/*concat var e w/var n?*/lvl + '},<wbr>'
}
}
Is there a way to change the number in the var names (e1 -> e2 etc) each iteration or do i just have to keep it the long way and write everything out on its own line?
It would be possible, though highly not recommended, to use eval to come up with the variable name:
const e1lvl1 = 'foo';
const e2lvl1 = 'bar';
for (let i = 1; i < 3; i++) {
console.log(eval('e' + i + 'lvl1'));
}
But it would be better to fix your script's architecture so that this isn't necessary: put each e#lvl into an array, and then access the appropriate index of the array on each iteration:
const elvl = [
'foo',
'bar'
];
let item_text = '';
for (let i = 0; i < elvl.length; i++) {
item_text += 'lvl: ' + elvl[i] + '\n';
}
console.log(item_text);
Arrays/Objects exist in javascript for a reason! Simplify your code. There is no reason to have e1, e1l, e2... as variables. Add them to an object and access them by key, or add them to an array, and loop through them. There are many javascript functions as well that will allow you to ensure all elements match a certain condition.
function submit() {
var e = {};
var idx = 28;
for (var i = 0; i <= 24; i++) {
e[i] = {};
e[i].key = document.getElementById(`ench${i}`).checked
e[i].value = $.trim(form.elements[idx].value)
idx += 2;
}
// Check condition
if (Object.values(e).some(e => e.key)) {
//One of the checked items was true
}
}
I would agree that you should change your code to use arrays.
To answer your question though, since your e1 and e1lvl variables look to be global scope, you can access them like this
window["e1"]
window["e1lvl"]
Give this a try
for (n = 0; n < id.length; n++) {
if (window["e" + n]) {
item_text += '{id:"' + id[n] + '",lvl:' + window["e" + n + "lvl"] + '},<wbr>';
}
}

Need for/while/do while loops to repeat asterisks

I have this problem, to repeat 30 asterisks for 3 lines. I made this example code but it repeats 30 numbers (1..30) from 1 number for first line, up to 30 numbers for the last line. So, I'd need the code to repeat 30 asterisks, for 3 lines each but not quite like within this code.
Sorry for bad elaboration.
var text = "";
var max = 30;
for(i = 0; i < max; i++)
{
for(j = 0; j <= i; j++)
{
text += (j+1)+" ";
}
text += "<br />";
}
A more re-usable solution will be to make a generic repeatString function that simply makes multiple copies of any string.
function repeatString(s, times) {
for (var i = 0, r = ''; i < times; i++) {
r += s;
}
return r;
}
var line = repeatString('*', 30) + '<br />',
content = repeatString(line, 3);
http://jsfiddle.net/611y2vmz/1/
Repeat the loop three times, like this:
for ( var i = 0; i < 3; i++ ) { // this is the line loop
for ( var j = 0; j < 30; j++ ) { //this is the asterix loop
document.write('*');
}
document.write('<br>');
}
Here's a simple demo
If you are using ES2015 (ES6) syntax you can leverage repeat function and string templating. Using those features your code will look like this
let text = (`${'*'.repeat(30)}<br/>`).repeat(3);
Here is an example of ES2015 (ES6) code
if you are using ES5 then you can do this way:
String.prototype.repeat = function(count) {
return count < 1 ? '' : new Array(count + 1).join(this);
};
var text = ('*'.repeat(30) + '<br/>').repeat(3);
Here is an example of ES5 code
You need your outer loop to iterate 3 times, and your inner loop to iterate 30 times. Each iteration of your inner loop should add an asterisk (instead of adding j+1 like you are doing now). This will produce 3 rows of 30 asterisks.
var TEXT = "*";
var LINE_SEPARATOR = "<br/>";
var TEXT_COUNT = 30;
var LINE_COUNT = 3;
var output = "";
for (line = 1; line <= LINE_COUNT; ++line) {
for (text = 1; text <= TEXT_COUNT; ++text) {
output += TEXT;
}
output += LINE_SEPARATOR;
}
document.write(output);
An alternative would be to use recursion:
function stars(num) {
return num > 0 ? stars(num - 1) + '*' : '';
}
var content = stars(30) + '<br/>' + stars(30) + '<br/>' + stars(30);
DEMO

Getting all variables with a name

I'd like to display each variable created by
while (i < document.getElementById("box").value.split("").length) {
this["numb_" + i] = document.getElementById("box").value.split("")[i];
i++;
};
to display in document.getElementById("text").innerHTML to make a result that looks like this in the webpage :foo + variable1created + foo + variable2created + foo + variable3created etc...The whole goal is to take numbers from the text box, split the digits, and display each digit separately (means with other text between), all automatically. End result text is loopable.
Here is my codepen so you can take a look at it (I made the code very simple :) here http://codepen.io/ninivert/pen/bdEYqx
I guess this is what you are looking for
var i = 0;
var num = this["numb_" + i];
while (!!num) {
process(num);
num = this["numb_" + (++i)];
};
Thanks to Katerina Tort for the help !
Updated the codepen to contain answer.
http://codepen.io/ninivert/pen/bdEYqx
function myFunction() {
var i = 0;
while (i < document.getElementById("box").value.split("").length) {
this["numb_" + i] = document.getElementById("box").value.split("")[i];
i++;
};
fillText();
}
function fillText(){
var i = 0;
var num = this["numb_" + i];
var result = '';
while (!!num) {
console.log(num)
result += process(num);
num = this["numb_" + (++i)];
}
document.getElementById("text").innerHTML = result;
}
function process(num) {
return 'foo' + num;
}

Categories

Resources