output not displaying inside the array - javascript

const pyramidOfAsterisks = function(val) {
var arr=[];
for (let m = 1; m <= val; m++) {
if (m === 7)
break;
for (let s = 1; s <= val - m; s++) {
document.write(" &nbsp");
}
for (let n = 1; n <= m; n++) {
document.write("* ");
}
for (let p = 2; p <= m; p++) {
document.write("* ");
}
document.write("<br />");
arr.push()
}
}
var pyramid = pyramidOfAsterisks(12);
document.write(pyramid);
I have tried to display the output inside the given empty array., so i pushed the function into the array , but not displaying inside the array.

You never push anything to the array arr
You never return anything in pyramidOfAsterisks which is why it prints undefined
Replace document.write with arr.push and return arr before the end of pyramidOfAsterisks.
const pyramidOfAsterisks = function(val) {
var arr=[];
for (let m = 1; m <= val; m++) {
if (m === 7)
break;
for (let s = 1; s <= val - m; s++) {
arr.push(" &nbsp");
}
for (let n = 1; n <= m; n++) {
arr.push("* ");
}
for (let p = 2; p <= m; p++) {
arr.push("* ");
}
arr.push("<br />");
//arr.push()
};
return arr
}
//REM: Be aware of array.join
var pyramid = pyramidOfAsterisks(12);
document.write(pyramid.join(''));

In the arr.push() function input the value you want to add to the array.
For example
arr.push("one")
arr.push("two")
// It will return ["one","two"]

const pyramidOfAsterisks = function(val) {
// var arr=[];
for (let m = 1; m <= val; m++) {
if (m === 7)
break;
for (let s = 1; s <= val - m; s++) {
document.write(" &nbsp");
}
for (let n = 1; n <= m; n++) {
document.write("* ");
}
for (let p = 2; p <= m; p++) {
document.write("* ");
}
document.write("<br />");
// arr.push()
}
}
var pyramid = pyramidOfAsterisks(12);
// document.write(pyramid);
This code works fine. It outputs undefined because of the document.write in the end. pyramidOfAsterisks does not return any value yet you assign the value it returns to a variable named pyramid, this is why pyramid is equal to undefined

Related

CodeWars sorting numbers and letters

I am currently doing a codewars problem, and I think I almost got it however, I ran across a problem when sorting index values with the same letter. link to problem is here. https://www.codewars.com/kata/5782dd86202c0e43410001f6
function doMath(s) {
let strSplit = s.split(' ');
let clonedArr = strSplit.slice();
for (let i = 0; i < strSplit.length; i++) {
for (let j = 0; j < strSplit[i].length; j++) {
let current = strSplit[i][j];
if (isNaN(current)) {
let letter = current;
strSplit[i] = strSplit[i].replace(letter, '');
strSplit[i] = letter + strSplit[i];
}
}
}
let sortedArr = strSplit.sort();
console.log(sortedArr);
// ["b900", "y369", "z123", "z246", "z89"]
let noLetterArr = sortedArr.map(x => {
return x.slice(1);
});
let numberArr = noLetterArr.map(y => {
return +y;
})
let firstEl = numberArr[0];
for (let i = 1; i < numberArr.length; i++) {
if (numberArr.indexOf(numberArr[i]) % 4 == 1) {
firstEl += numberArr[i];
}
if (numberArr.indexOf(numberArr[i]) % 4 == 2) {
firstEl -= numberArr[i];
}
if (numberArr.indexOf(numberArr[i]) % 4 == 3) {
firstEl *= numberArr[i];
}
}
return firstEl;
}
console.log(doMath('24z6 1z23 y369 89z 900b'));
I would like to sort the sortedArr the ones with the same letter by how they first appeared in string. So since "z246" appeared first in the original string. I would like to have that before "1z23". I had a hard time creating a function for that.
var al = [];
function doMath(s) {
var ar = s.split(" ");
for (let i = 0; i < ar.length; i++) {
for (let char of ar[i]) {
let temp = char.match(/[a-z]/i);
if (temp) {
al[i] = char;
ar[i] = ar[i].replace(char, '');
ar[i] = char + ar[i];
}
}
}
al = al.sort();
//New Sort Logic to pass above test case and others too
var n = [];
for (let i = 0; i < al.length; i++) {
for (let j = 0; j < ar.length; j++) {
if (ar[j].startsWith(al[i]) && !n.includes(ar[j])) {
n.push(ar[j]);
}
}
}
var result = parseInt(n[0].substr(1)),
count = 1;
for (let i = 1; i < n.length; i++) {
if (count == 1) {
result = result + parseInt(n[i].substr(1));
count++;
} else if (count == 2) {
result = result - parseInt(n[i].substr(1));
count++;
} else if (count == 3) {
result = result * parseInt(n[i].substr(1));
count++;
} else if (count == 4) {
result = result / parseInt(n[i].substr(1));
count = 1;
}
}
return Math.round(result);
}

NaN out of matrix multiplication?

I have the code below for matrix formation out of an array and its multiplication.
But when I try to multiply two matrices like mtp(matrix(2,2,[1,2,3,4]),matrix(2,2,[1,0,0,1])) it returns NaN in all places.
Please help me out
function matrix(m, n, arr) {
var result = {};
for (t = 1; t <= m; t++) {
result[t] = {};
};
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++) result[i][j] = arr[m * (i - 1) + j - 1];
return {
"result": result,
"m": m,
"n": n
};
}
function mtp(a, b) {
if (parseInt(a.n) != parseInt(b.m)) {
return;
} else {
var result = [];
var m = parseInt(a.m);
var n = parseInt(b.n);
var k = parseInt(a.n);
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
for (p = 1; p <= k; p++) {
result[m * (i - 1) + j - 1] += (parseInt(a.result[i][p]) * parseInt(b.result[p][j]));
console.log(parseInt(a.result[i][p]) * parseInt(b.result[p][j]))
}
}
}
}
console.log(result, matrix(m, n, result).result);
}
mtp(matrix(2,2,[1,2,3,4]),matrix(2,2,[1,0,0,1]));
When you define result it is an array of zero elements
var result = [];
When you try to add a number to an element of the array, that element is not defined, Adding any number to undefined gives you NaN. There are 2 ways to solve this, either initialize your array with the right length of zeros, or default it to zero during the sum. I've chosen the latter below,
result[m * (i - 1) + j - 1] = (result[m * (i - 1) + j - 1]||0) + (a.result[i][p] * b.result[p][j]);
// Note here ---------------------------------------------^
I've got rid of all the unnecessary parseInt calls.
function matrix(m, n, arr) {
var result = {};
for (t = 1; t <= m; t++) {
result[t] = {};
};
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++) result[i][j] = arr[m * (i - 1) + j - 1];
return {
"result": result,
"m": m,
"n": n
};
}
function mtp(a, b) {
if (a.n != b.m) {
return;
} else {
var result = [];
var m = a.m;
var n = b.n;
var k = a.n;
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
for (p = 1; p <= k; p++) {
result[m * (i - 1) + j - 1] = (result[m * (i - 1) + j - 1]||0) + (a.result[i][p] * b.result[p][j]);
console.log(a.result[i][p] * b.result[p][j])
}
}
}
}
console.log(result, matrix(m, n, result).result);
}
mtp(matrix(2,2,[1,2,3,4]),matrix(2,2,[1,0,0,1]));
In your mtp() function the values of the elements inside your result array are uninitialized (that is, you've defined an array, but that array has no actual values or even a determined length), so in your inner loop when you +=, you're referencing a newly created array element which has no default value (and therefore is undefined), and adding some number to that undefined value.
An undefined value plus a number is not a number (NaN). Try preinitializing your result array.

finding prime numbers in an array from 1-200

A math problem describes a list of numbers from 1-200, you must skip the number 1, and then for each number that follows, remove all multiples of that number from the list. Do this until you have reached the end of the list.
Here's what I have so far.
var x = []; // creating an array called x with zero numbers
for ( var i = 1; i <= 200; i++ ){
x.push(i);
};
// x now should have an array that contains the intergers from 1-200.
//looping through the array.
for ( var i = 0; i <= x.length; i++ ){ //going from 1-200
if (x[i] == 1){
continue; // skipping 1
} else {
for ( var n = i+1; n <= i; n++){ // take the number 1 index bigger than x[i]
if ( n % i == 0){ //find if the modulus of x[n] and x[i] is zeor, meaning it is divisible by x[i]
x.shift(); //remove that number
console.log(x[n]);
} else {
continue;
}
}
}
};
Instead of adding number 1 to 200 and then removing non prime numbers, try only putting prime numbers into that list. Since this is a school problem (I'm guessing) I don't want to give you the answer, but if you have more questions I can answer.
Also your nested loop will never run, go over that logic again.
Another version (a minute too late, as always ;-), one with comments
// lil' helper
function nextSet(a,n){
while(a[n] == 0) n++;
return n;
}
function setPrimes(a,n){
var k, j, r;
n = n + 1;
k = n;
while(k--)a[k] = 1;
a[0] = 0; // number 0
a[1] = 0; // number 1
// get rid of all even numbers
for(k = 4; k < n; k += 2) {
a[k] = 0;
}
// we don't need to check all of the numbers
// because sqrt(x)^2 = x
r = Math.floor(Math.sqrt(n));
k = 0;
while(k < n){
k = nextSet(a,k+1);
// a test if we had them all
if(k > r){
break;
}
// unmark all composites
for(j = k * k; j < n; j += 2*k){
a[j] = 0;
}
}
return a;
}
function getPrimes(n){
// we know the size of the input
var primearray = new Array(n);
// we don't know the size of the output
// prime-counting is still an unsolved problem
var output = [];
setPrimes(primearray, n);
for(var i = 0; i < n; i++){
if(primearray[i] == 1){
output.push(i);
}
}
return output;
}
getPrimes(200);
You can go through a full implementation of that algorithm at another primesieve.
Here is, I believe, a working example of what you want:
function isPrime(num){
if(num < 2){
return false;
}
for(var i=2,l=Math.sqrt(num); i<=l; i++){
if(num % i === 0){
return false;
}
}
return true;
}
function range(f, t){
for(var i=f,r=[]; i<=t; i++){
r.push(i);
}
return r;
}
function primeRange(from, to){
var a = range(from, to), r = [];
for(var i=0,l=a.length; i<l; i++){
var v = a[i];
if(isPrime(v)){
r.push(v);
}
}
return r;
}
var prmRng = primeRange(1, 200);
console.log(prmRng);
I solved it this way:
let numbers = new Array();
for (let i = 1; i <= 200; i++) {
numbers.push(i);
}
let primeNumbers = (num) => {
let prime = new Array();
for(let i = 0; i < num.length; i++) {
let count = 0;
for (let p = 2; p <= num[i]; p++) {
if(num[i] % p === 0 && num[i] !== 2) {
count++;
} else {
if(num[i] === 2 || count === 0 && num[i]-1 === p) {
prime[i] = num[i];
}
}
}
}
return prime.filter(Boolean);
}
console.log(primeNumbers(numbers));

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
}

bruteforce string matching javascript

function search(pattern, text) {
var M = pattern.length;
var N = text.length;
for (var i = 0; i < N - M; i++) {
var j =0;
while (j < M) {
if (text.charAt(i + j) != pattern.charAt(j)) {break;}
}
if (j == M) {return i;}
}
return -1;
}
console.log(search("rf", "jdsrfan"));
I want to make an brute-force string matching algorithm in JavaScript. Can anyone tell me whats wrong with above code?
I did fixed it myself fixed code as follows:
// return offset of first match or -1 if no match
function bruteForcePatternSearch(sPattern, sText) {
var M = sPattern.length,
N = sText.length;
for (var i = 0; i <= N - M; i++) {
var j=0;
while (j < M) {
if (sText.charAt(i+j) !=sPattern.charAt(j)){
break;
}
j++;
}
if (j == M) {return i;} // found at offset i
}
return -1; // not found
}
bruteForcePatternSearch("abracadabra","abacadabrabracabracadabrabrabracad");
You're never incrementing j to start with. Hence the infinite loop.
Then, as Claudio commented, i < N - M is wrong. Should be i <= N - M.
Spoiler: here the fixed function. But I advise you not to take it as-is, but to try doing it yourself instead.
function search(pattern, text) {
var M = pattern.length;
var N = text.length;
for (var i = 0; i <= N - M; ++i) {
var matched = true;
for (var j = 0; j < M; ++j) {
if (text.charAt(i + j) != pattern.charAt(j)) {
matched = false;
break;
}
}
if (matched) {
return i;
}
}
return -1;
}
i guess this will work
for (var i = 0; i < M; i++) {
var j =0;
while (j < N) {
if (text.charAt(j) != pattern.charAt(i)) {
break;
}
j++
}
if (j == M) {return i;}
}
here is the explanation
on each pattern
match each character of text

Categories

Resources