javascript Fibonacci sequence return undefined - javascript

I am new to javascript and I was trying to write a small function return Fibonacci sequence. Here is my code:
function fib2(n) {
let fib = [];
fib[0] = 1;
fib[1] = 1;
for (var i = 2; i < n; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return fib[i];
}
console.log(fib2(6));
but the result is undefined. I guess it's because of some closure issue but I am not sure about why. Could someone explain what happened? Thank you

After the for loop, variable i has value n, so fib[i] is out of the array.
function fib2(n) {
let fib = [];
fib[0] = 1;
fib[1] = 1;
for (var i = 2; i < n; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
return fib[n-1];
}
console.log(fib2(6));

function fib2(n) {
let fib = [];
fib[0] = 1;
fib[1] = 1;
for (var i = 2; i < n; i++) {
fib[i] = fib[i-2] + fib[i-1];
}
return fib;
}
console.log(fib2(6));
OUTPUT
(6) [1, 1, 2, 3, 5, 8]
In addition
if I were you, I am trying to change the name of the function and the name of the variable in the function for distinguishing.
function fib(n) {
let arr = [];
arr[0] = 1;
arr[1] = 1;
for(let i = 2; i < n; i++){
arr[i] = arr[i-2] + arr[i-1];
}
return arr;
}
console.log(fib(6));
If you want to get the last element of the sequence,
function lastFib(n){
let prev = 1;
let now = 1;
let temp = 0;
for(let i = 2; i < n; i++){
temp = now;
now = prev + now;
prev = temp;
}
return now;
}
console.log(lastFib(6));

Related

How do I fix this cocktail shaker sort code to work?

I'm trying to write a code that sorts random numbers with different sorting alrorithms. I have 5 algorithms so far, including bubble sort, javascript built in sort, insertion sort, selection sort, and cocktail sort. I am also writing how many swaps and how much time each sort takes. Other sorts are working just fine( I think), but it seems like cocktail sort is not working.
I tried to modify that part of the code, but none of them worked. Here is the code below. I want it to work properly while displays how many swaps and how much time it took at the console. Thank you.
NUM_ELEMENTS = 500;
numbers = [];
function setup() {
createCanvas(400, 300);
for(i=0;i<=NUM_ELEMENTS;i++) {
numbers.push(round(random(1,NUM_ELEMENTS)));
}
para1 = createElement("p","");
tempString = "";
for(i=0;i<=NUM_ELEMENTS;i++) {
console.log(numbers[i]);
tempString = tempString + numbers[i] + ",";
}
para1.html(tempString);
button1 = createButton("Bubble Sort");
button1.mousePressed(bubbleSort);
button2 = createButton("Seclection Sort");
button2.mousePressed(selectionSort);
button3 = createButton("Insertion Sort");
button3.mousePressed(insertionSort);
button4 = createButton("Javascript Bulit-in Sort");
button4.mousePressed(bSort);
}
function bubbleSort() {
total = 0
swaps = 0
t1 = millis();
console.log("sorting")
let n = numbers.length;
for(let i = 0; i < n; i++) {
for(let j = 0; j < n; j++) {
if(numbers[j] > numbers[j+1]){
let t = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = t;
swaps = swaps + 1;
}
}
}
t2 = millis();
console.log(t2-t1);
console.log("swaps :",swaps);
}
function selectionSort() {
let n = numbers.length;
console.log("Sorting...")
total = 0
t1 = millis();
swaps = 0
for(let i = 0; i < n; i++) {
let min = i;
for(let j = i+1; j < n; j++){
if(numbers[j] < numbers[min]) {
min=j;
swaps = swaps + 1;
}
}
if (min != i) {
let tmp = numbers[i];
numbers[i] = numbers[min];
numbers[min] = tmp;
swaps = swaps + 1;
}
}
t2 = millis();
console.log(t2-t1);
console.log("swaps :", swaps);
}
function insertionSort() {
console.log("sorting");
t1 = millis();
swaps = 0;
total = 0
let n = numbers.length;
for (let i = 1; i < n; i++) {
let current = numbers[i];
let j = i-1;
while ((j > -1) && (current < numbers[j])) {
numbers[j+1] = numbers[j];
swaps = swaps + 1;
j--;
}
numbers[j+1] = current;
}
t2 = millis();
console.log(t2-t1);
console.log("swaps : ", swaps);
}
function bSort() {
console.log("Sorting...")
total = 0
t1 = millis();
sort(numbers);
t2 = millis();
console.log(t2-t1);
console.log("swaps : unknown");
}
function cocktailSort() {
console.log("sorting...")
total = 0
swaps = 0
t1 = millis();
let n = numbers.length;
let sorted = false;
while (!sorted) {
sorted = true;
for (let i = 0; i < n - 1; i++) {
if (numbers[i] > numbers[i + 1]){
let tmp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i+1] = tmp;
sorted = false;
}
}
if (sorted)
break;
sorted = true;
for (let j = n - 1; j > 0; j--) {
if (numbers[j-1] > numbers[j]) {
let tmp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j+1] = tmp;
sorted = false;
}
}
}
t2 = millis();
console.log(t2-t1);
}
function draw() {
background(220);
textSize(13);
column = 10;
row = 0;
for (i=0;i<NUM_ELEMENTS;i++) {
if (i%18==0) {
column = column + 18;
row = 0;
}
text(numbers[i],column,row*15+15);
row++;
}
}

How to insert an array to another array at each iteration of a for loop in javascript

I have a function to bubble sort and I want to save the array after each swap into another array. The bubble sort is working properly and I can log the array after each swap to the console. But I cant seem to push to the other array properly.
Here's my code :
var arr = [5, 4, 3, 2, 1];
var steps = [];
function bubbleSort() {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
var temp = arr;
console.log(temp);
steps.push(temp);
}
}
console.log(steps);
}
const swap = (a, x, y) => {
var temp = a[x];
a[x] = a[y];
a[y] = temp;
};
bubbleSort();
Here's a screenshot of the console :
screenshot of console
It's only when I try to use get a hold of the array at each step that it isn't showing properly? what do I do?
I think clonning the array could work ? var temp = [...arr];
var arr = [5, 4, 3, 2, 1];
var steps = [];
function bubbleSort() {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
var temp = [...arr];
console.log(temp);
steps.push(temp);
}
}
console.log(steps);
}
const swap = (a, x, y) => {
var temp = a[x];
a[x] = a[y];
a[y] = temp;
};
bubbleSort();
You are inserting the Reference of the Temp-Array and not the actual content. This way, you store multiple times the reference and at the End you are presented with all those reference pointing to the last version of your temp Array.
You can use the destructuring assignment of an array, to create an easy shallow copy to be stored.
var arr = [5, 4, 3, 2, 1];
var steps = [];
function bubbleSort() {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
var temp = arr;
console.log(temp);
// Changed to destructuring assignment
steps.push([...temp])
}
}
console.log(steps);
}
const swap = (a, x, y) => {
var temp = a[x];
a[x] = a[y];
a[y] = temp;
};
bubbleSort();

What am I doing wrong to find element occurring most in array?

I am trying to debug one online coding platform problem. The problem I am facing is to return element occurring most often in array. I am interested in correcting my current code than trying other methods.
function findMostOccured(M, A) { //value of elements in A should not be greater than M
var N = A.length;
var count = new Array(M + 1);
var i;
for (i = 0; i <= M; i++)
count[i] = 0;
var maxOccurence = 1;
var index = -1;
for (i = 0; i < N; i++) {
if (count[A[i]] > 0) {
var tmp = count[A[i]];
if (tmp > maxOccurence) {
maxOccurence = tmp;
index = i;
}
count[A[i]] = tmp + 1;
} else {
count[A[i]] = 1;
}
}
return A[index];
}
Given M = 3 and A = [1, 2, 3, 3, 1, 3, 1]. It should return 3 or 1.
var arr = [1, 2, 3, 3, 1, 3, 1];
var M = 3;
function findMostOccured(M, arr) {
var obj = {};
var result = [];
for (let i = 0; i < arr.length; i++) {
if (obj[arr[i]]) {
obj[arr[i]] = obj[arr[i]] + 1;
} else {
obj[arr[i]] = 1;
}
}
for (var key in obj) {
if (obj[key] === M) {
result.push(parseInt(key));
}
}
return result;
}
console.log(findMostOccured(3, arr));

Generate arrays of numbers in certain algorithm

So I need few arrays:
array 1 = [1,9,17,25,33,41];
array 2 = [2,10,18,26,34,42];
etc.
So each array adds up 8 to the last item.
But, I need to generate this dynamically (using functions in JavaScript).
var initValue = 5;
var diff = 8;
var len = 5;
function makeDiffArray(initValue, diff, len) {
for (var i = 0, arr = []; i < len; i++) {
arr.push(initValue);
initValue += diff;
}
return arr;
}
console.log(makeDiffArray(initValue, diff, len));
Something like this?
for(var i = 1; i<10;i++){
eval("var array" + i + " = [" + i + "];");
for(var j = 1; j<10; j++){
eval("array" + i + ".push(array" + i + "[array" + i + ".length] + 8);");
}
}
You can also try dynamic variable names
var arrayCount = 2;
var initValue = 5;
var diff = 8;
var len = 5;
for(var i=1; i<=arrayCount; i++) {
window['array'+i] = makeAnArray(i,diff,len);
alert(window['array'+i]);
}
function makeAnArray(initValue) {
var anArray = [];
for (var j = 0, init = initValue; j < len; j++) {
anArray.push(init);
init += diff;
}
return anArray;
}
I know this has already been accepted, just wanted to add the ES6 version here.
let [init, diff, len] = [5, 8, 5], tmp = init;
let arr = Array(len).fill(init).map( (x, i) => (i) ? tmp += diff : x );
console.log(arr)

How to program Pascal's Triangle in Javascript - confusion re Arrays

I'm having a little trouble with my attempt at this problem. Code Below:
function pasc(n){
var result = [[1]];
for (var row = 1; row < n; row++){
for (var col = 1; col <= row; col++){
result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
}
}
return result;
}
pasc(10)
for (var i = 0; i < result.length; i++){
document.write(result[i]+"<br>");
}
It seems the problem hinges on assigning values to an array using an expression like myArray[1][1] = "foo"
I'm confused about this because I can do this: var myArray = []; myArray[4] = "foo" which seems to suggest that an element can be created at an arbitrary position in a 1 dimensional array, but not with 2 dimensions.
Any help with clearing up my misconceptions appreciated.
The Pascal's Triangle can be printed using recursion
Below is the code snippet that works recursively.
We have a recursive function pascalRecursive(n, a) that works up till the number of rows are printed. Each row is a element of the 2-D array ('a' in this case)
var numRows = 10,
triangle,
start,
stop;
// N is the no. of rows/tiers
// a is the 2-D array consisting of the row content
function pascalRecursive(n, a) {
if (n < 2) return a;
var prevRow = a[a.length-1];
var curRow = [1];
for (var i = 1; i < prevRow.length; i++) {
curRow[i] = prevRow[i] + prevRow[i-1];
}
curRow.push(1);
a.push(curRow);
return pascalRecursive(n-1, a); // Call the function recursively
}
var triangle = pascalRecursive(numRows, [[1]]);
for(var i = 0; i < triangle.length; i++)
console.log(triangle[i]+"\n");
JavaScript doesn't have two-dimensional arrays. What it does have is arrays that happen to contain other arrays. So, yes, you can assign a value to any arbitrary position in an array, and the array will magically make itself big enough, filling in any gaps with 'undefined'... but you can't assign a value to any position in a sub-array that you haven't explicitly created yet. You have to assign sub-arrays to the positions of the first array before you can assign values to the positions of the sub-arrays.
Replacing
for (var row = 1; row < n; row++){
for (var col = 1; col <= row; col++){
with
for (var row = 1; row < n; row++){
result[row] = [];
for (var col = 1; col <= row; col++){
should do it. Assuming all of your indexing logic is correct, anyway. You've got some problems there, too, since your initial array only contains a single value, so result[row][col] = result[row - 1][col] + result[row - 1][col - 1]; is accessing at least one cell that has never been defined.
Thanks Logan R. Kearsley. I have now solved it:
function pasc(n){
var result = [];
result[0] = [1];
result[1] = [1,1];
for (var row = 2; row < n; row++){
result[row] = [1];
for (var col = 1; col <= row -1; col++){
result[row][col] = result[row-1][col] + result[row-1][col-1];
result[row].push(1);
}
}
return result;
}
for (var i = 0; i < pasc(10).length; i++){
document.write(pasc(10)[i]+"<br>");
console.log(pasc(10)[i]+"<br>");
}
you can create Pascal's triangle using below code:
function pascal(n) {
var arr = [];
if (n == 1) {
arr[0] = [];
arr[0][0] = 1;
} else if (n == 2) {
arr[0] = [];
arr[0][0] = 1;
arr[1] = [];
arr[1][0] = 1;
arr[1][1] = 1;
} else if (n > 2) {
arr[0] = [];
arr[1] = [];
arr[0][0] = 1;
arr[1][0] = 1;
arr[1][1] = 1;
for (i = 2; i < n; i++) {
arr[i] = [];
arr[i][0] = 1;
for (j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr[i][j] = 1;
}
}
console.log(arr);
for (i = 0; i < arr.length; i++) {
console.log(arr[i].join(' '))
}
}
function pascal(n) {
var arr = [];
if (n == 1) {
arr[0] = [];
arr[0][0] = 1;
} else if (n == 2) {
arr[0] = [];
arr[0][0] = 1;
arr[1] = [];
arr[1][0] = 1;
arr[1][1] = 1;
} else if (n > 2) {
arr[0] = [];
arr[1] = [];
arr[0][0] = 1;
arr[1][0] = 1;
arr[1][1] = 1;
for (i = 2; i < n; i++) {
arr[i] = [];
arr[i][0] = 1;
for (j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr[i][j] = 1;
}
}
console.log(arr);
for (i = 0; i < arr.length; i++) {
console.log(arr[i].join(' '))
}
}
pascal(5)
This function will calculate Pascal's Triangle for "n" number of rows. It will create an object that holds "n" number of arrays, which are created as needed in the second/inner for loop.
function getPascalsTriangle(n) {
var arr = {};
for(var row = 0; row < n; row++) {
arr[row] = [];
for(var col = 0; col < row+1; col++) {
if(col === 0 || col === row) {
arr[row][col] = 1;
} else {
arr[row][col] = arr[row-1][col-1] + arr[row-1][col];
}
}
}
return arr;
}
console.log(getPascalsTriangle(5));
Floyd triangle
You can try the following code for a Floyd triangle
var prevNumber=1,i,depth=10;
for(i=0;i<depth;i++){
tempStr = "";j=0;
while(j<= i){
tempStr = tempStr + " " + prevNumber;
j++;
prevNumber++;
}
console.log(tempStr);
}
You can create arbitrary 2d arrays and store it in there and return the correct Pascal.
JavaScript does not have a special syntax for creating multidimensional arrays. A common workaround is to create an array of arrays in nested loops.
source
Here is my version of the solution
function pascal(input) {
var result = [[1], [1,1]];
if (input < 0) {
return [];
}
if (input === 0) {
return result[0];
}
for(var j = result.length-1; j < input; j++) {
var newArray = [];
var firstItem = result[j][0];
var lastItem = result[j][result[j].length -1];
newArray.push(firstItem);
for (var i =1; i <= j; i++) {
console.log(result[j][i-1], result[j][i]);
newArray.push(sum(result[j][i-1], result[j][i]));
}
newArray.push(lastItem);
result.push(newArray);
}
return result[input];
}
function sum(one, two) {
return one + two;
}
Here is the code i created for pascal triangle in javascript
'use strict'
let noOfCoinFlipped = 5
let probabiltyOfnoOfHead = 2
var dataStorer = [];
for(let i=0;i<=noOfCoinFlipped;i++){
dataStorer[i]=[];
for(let j=0;j<=i;j++){
if(i==0){
dataStorer[i][j] = 1;
}
else{
let param1 = (j==0)?0:dataStorer[i-1][j-1];
let param2 = dataStorer[i-1][j]?dataStorer[i-1][j]:0;
dataStorer[i][j] = param1+param2;
}
}
}
let totalPoints = dataStorer[noOfCoinFlipped].reduce((s,n)=>{return s+n;})
let successPoints = dataStorer[noOfCoinFlipped][probabiltyOfnoOfHead];
console.log(successPoints*100/totalPoints)
Here is the link as well
http://rextester.com/TZX59990
This is my solve:
function pascalTri(n){
let arr=[];
let c=0;
for(let i=1;i<=n;i++){
arr.push(1);
let len=arr.length;
if(i>1){
if(i>2){
for(let j=1;j<=(i-2);j++){
let idx=(len-(2*i)+j+2+c);
let val=arr[idx]+arr[idx+1];
arr.push(val);
}
c++;
}
arr.push(1);
}
}
return arr;
}
let pascalArr=pascalTri(7);
console.log(pascalArr);
here is the pattern for n = 3
#
##
###
here is js code to print this.
function staircase(n) {
for(var i=0 ; i<n ; i++) {
for(var j=n-1 ; j>i ; j--)
process.stdout.write(" ");
for(var k=0 ; k<=i; k++) {
process.stdout.write("#");
}
process.stdout.write("\n");
}
}
class PascalTriangle {
constructor(n) {
this.n = n;
}
factoriel(m) {
let result = 1;
if (m === 0) {
return 1;
}
while (m > 0) {
result *= m;
m--;
}
return result;
}
fill() {
let arr = [];
for (let i = 0; i < this.n; i++) {
arr.push([]);
}
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j <= i; j++) {
arr[i].push(this.factoriel(i) / (this.factoriel(j) * this.factoriel(i - j)));
}
}
return arr;
}
}
var m = prompt("enter number:");
var arrMain = new Array();
for (var i = 0; i < m; i++) {
arrMain[i] = [];
}
for (var i = 0; i < m; i++) {
if (i == 0) {
arrMain[i] = [1];
} else if (i == 1) {
(arrMain[i]) = [1, 1];
} else {
for (var j = 0; j <= i; j++) {
if (j == 0 || j == arrMain[i - 1].length) {
arrMain[i][j] = 1;
} else {
arrMain[i][j] = arrMain[i - 1][j] + arrMain[i - 1][j - 1];
}
}
}
document.write(arrMain[i] + "<br>");
}
This is my take on this problem by gaining access to the previous row.
const generate = numRows => {
const triangle = [[1]]
for (let i = 1; i < numRows; i++) {
// Previous row
const previous = triangle[i - 1]
// Current row
const current = new Array(i + 1).fill(1)
// Populate the current row with the previous
// row's values
for (let j = 1; j < i; j++) {
current[j] = previous[j - 1] + previous[j]
}
// Add to triangle result
triangle.push(current)
}
return triangle
}

Categories

Resources