Javascript Multiplication table in 2D array - javascript

I've a task to write a program that creates a multiplication table for the given variable n.
The results need to be saved to a two-dimensional array. In the console I need to display the entire table with appropriate data formatting (as below). I'm starting with Javascript and already know loops and arrays only, I haven't learnt functions yet so I need some really basic solution.
This is how the result should look like:
Here is my code that I wrote so far and I don't know what to do next:
const n = 3;
const calc = []
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
calc.push(i + " * " + j + " = " + (i * j));
}
console.log(calc)
}

You're almost there:
Not sure that you need the array calc if your aim is to print the table
Define a new variable row inside the outer loop as an empty array, [];
In the inner loop, instead of calc.push, use row.push
After the inner loop, you have a complete row, which you can output using the array .join() method
If you need to, then add the row to calc with calc.push(row); not necessary in my view.
const n = 3;
//const calc = []; //may not be necessary
for (let i = 1; i <= n; i++) {
const row = [];
for (let j = 1; j <= n; j++) {
row.push(i + " x " + j + " = " + (i * j));
}
console.log( row.join(' | ') );
//calc.push(row);//not sure if you still need this
}
/* OUTPUT
1 x 1 = 1 | 1 x 2 = 2 | 1 x 3 = 3
2 x 1 = 2 | 2 x 2 = 4 | 2 x 3 = 6
3 x 1 = 3 | 3 x 2 = 6 | 3 x 3 = 9
*/

From the code you've presented, it appears that you're yet to understand what a 2d array really is. The way you've done it, everything's just stuffed into a single 1d array.
You may think of the pixels on a screen as being part of a 2d array. The first array holds all of the horizontal lines. The horizontal lines contain the pixels.
So.. let's concentrate on that part first.
let result = [];
for (var y=0; y<n; y++)
{
result.push( [] );
for (var x=0; x<n; x++)
{
result[y].push( (x+1) * (y+1) );
}
}
First we create a result array, and then for every row in our table, we add an array that will hold the columns, then for each column in that row, we add the values.
Next, we just step through that table and turn the values into the original equations. We start by ascertaining the dimensions of the array, before we create a table the same size.
function printTable( tbl )
{
let nRows = tbl.length;
let nCols = tbl[0].length;
for (var y=0; y<nRows; y++)
{
let rowStr = '';
for (var x=0; x<nCols; x++)
{
if (x!=0) rowStr += " | ";
rowStr += `${y+1} x ${x+1} = ${tbl[y][x]}`;
}
console.log(rowStr);
}
}
Chucking it all together, I present the following code. Yes, I know you're not using functions yet - but you can still see the important concepts. You can change it so that the whole equation for each entry in the table is saved, instead of just the answer.
window.addEventListener('load', init, false);
function init()
{
let result = makeMultTable(3);
printTable(result);
}
function makeMultTable(n)
{
let result = [];
for (var y=0; y<n; y++)
{
result.push( [] );
for (var x=0; x<n; x++)
{
result[y].push( (x+1) * (y+1) );
}
}
return result;
}
function printTable( tbl )
{
let nRows = tbl.length;
let nCols = tbl[0].length;
for (var y=0; y<nRows; y++)
{
let rowStr = '';
for (var x=0; x<nCols; x++)
{
if (x!=0) rowStr += " | ";
rowStr += `${y+1} x ${x+1} = ${tbl[y][x]}`;
}
console.log(rowStr);
}
}

Here is a short version of putting those multiplications into a 2D array:
const arr=[...Array(4)].map((_,i)=>i+1),
arr2=arr.map(i=>arr.map(j=>`${i}*${j}=${i*j}`));
console.log(arr2);

Multiplication of table in two dimension array
Function name: multiplyNumber
Syntex multiplyNumber(n)
n Number to be passed to function to create table upto that number.
Snippet
function multiplyNumber(n){
let table = [];
let data = [];
for (var i = 1; i <= n; i++){
for (var j = 1; j <= n; j++){
data.push(`${i} x ${j} = ${i * j}`);
}
table.push(data); // pushing data to table.
data = []; //Resetting data array to store new data each time.
}
return table;
}
var result = multiplyNumber(3);
console.log(result);

For every line I created an array line, filling it with the calculations. after the line loop I pushed it into calc.
const n = 3;
const calc = [];
for (let i = 1; i <= n; i++) {
const line = [];
for (let j = 1; j <= n; j++) {
line.push(i + " * " + j + " = " + (i * j));
}
calc.push(line);
}
console.log(calc);

Related

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

How do I create a jagged array that produces a random amount arrays inside an array with random values?

var array = [];
var list = "<ul>";
for(var i = 0; i < parseInt(Math.random() * 20); i++){
array[i] = [parseInt(Math.random() * 10)];
list += "<li>" + array[i];
for(var j = 0; j < array[i].length; j++){
array[i][j] += parseInt(Math.random() * 10);
list += " " + array[i][j];
}
list += "</li>"
}
list += "</ul>"
document.getElementById("print").innerHTML += list;
<div id="print">
</div>
My goal is to create a jagged array.
I want to initialize an array and create random sets of array inside the initial array that also contains random numbers.
The output I'm looking for is something like this:
4 2 5
1 10 3 4 5 6
7 1 4 8
6 9
1
4 6 7
..but when I run the code I have so far I only receive two columns of random integers every time I run the program. How can I fix this?
When you do:
array[i] = [parseInt(Math.random() * 10)];
array[0] is assigned an array of length 1 and containing a single digit integer, assume it's 5 so that array looks like [[5]]. Then later:
for(var j = 0; j < array[i].length; j++){
Note here array[i].length is 1.
array[i][j] += parseInt(Math.random() * 10);
So this adds a number to the value at array[0][0], which was 5 and now might be say 8, so you have an array like:
[[8]]
Since the length of array is still only 1, and j is incremented to 1 also, the loop ends.
Note that if you use:
array[i][j].push(parseInt(Math.random() * 10));
you'll have an infinite loop since you will increment the length of the array at the same rate you increment j and it will always be j + 1. You need to set j to a static value, e.g.
for (var j=0, jLimt = parseInt(Math.random()*10); j<jLimt; j++)
This code should generate the type of array you are looking for.
function createRandomArray(){
//Create empty Array
var out=[];
//random element count for outer array
var outerLength=parseInt(Math.random()*20)+1;
//fill outer array with random arrays
for(var i=0;i<outerLength;i++){
//inner element count and initialisation
var innerLength=parseInt(Math.random()*10)+1;
var inner=[];
for(var j=0;j<innerLength;j++){
//fill the inner array with random numbers
inner.push(parseInt(Math.random()*10)+1);
}
//add the inner array to the outer array
out.push(inner);
}
return out;
}
Edit
I will try to explain why your code does not work
for(var i = 0; i < parseInt(Math.random() * 20); i++){
In every loop iteration the Math.random part is executed again. You should save it in an extra variable.
array[i] = [parseInt(Math.random() * 10)];
You initialize the sub-array with one random number
for(var j = 0; j < array[i].length; j++){
And iterate over this sub array(which has only one element). So this loop is only called once per sub-array. Because of this every Array has exactly 2 elements
I think you are running into trouble because your recalculating a random value every iteration of the for loop.
It's even easier. One thing I noticed is your code is doing too much. It's creating random arrays, creating a random array of random arrays, creating HTML, string concatenating the HTML, and mutating the DOM. That's a lot for one conceptual function to do. How about breaking up the logic into single responsibility functions and compose them together:
function randomValue(offset) {
return Math.floor(Math.random() * (offset || 10));
}
function randomArray(size, valueFn) {
var i, arr = [];
size = randomValue(size || 20) + 1;
for (i = 0; i < size; i++) {
arr.push(valueFn());
}
return arr;
}
function randomJaggedArray(size, offset) {
return randomArray(size, function() {
return randomArray(size, function() {
return randomValue(offset);
});
});
}
function toHTML(arr) {
var html = '<ul>';
html += arr.map(function(value) {
var li = '<li>';
if (typeof value === 'number') {
li += '' + value;
} else {
li += value.join(' ');
}
li += '</li>';
return li;
}).join('');
html += '</ul>';
return html;
}
document.getElementById('print').innerHTML = toHTML(randomJaggedArray(20, 10));
<div id="print"></div>

Javascript WW2 Flag Stars

I'm having trouble and have been stuck on this program for a while. Basically I need to use for loops in order to make the stars in a flag on the webpage. The order is 48 stars going 8 across and 6 down. My pseudocode is
class WW2Flag
main()
//Declarations//
str j
str x
for j = 1 to 6
for x = 1 to 8 step 1
output "x "
endfor
output break
endClass
My program that I have currently is
var row = "&#10029";
var x = 48;
for (x=0;x<8;x+1){
document.getElementById("stars").innerHTML += row;
if (x==8){
break;
document.write("&#10029");
}
else {
j = 0;j<6;j + 1;
document.write("&#10029");
}
x++;
}
You just need to nest your column loop within your row loop, like this.
var stars = [], star = '&#10029';
for (var i=0; i<6; i++) {
for (var j=0; j<8; j++) {
stars.push(star);
}
stars.push('<br />\n');
}
document.getElementById('stars').innerHTML = stars.join('');
<div id="stars"></div>

Filling up a 2D array with random numbers in javascript

I'm really sorry if anything like this has been posted here before but I couldn't find anything, I'm kinda new to the site still!
So for a while now I've been learning a bit about game development through html5 and javascript and I stumbled upon making tileset maps, I now have a tileset and an 2D array that I want to put certain tiles in (the number varies between 6 and 10 in this case).
I figured it could be a cool function to make the map choose between a small set of similar tiles so I don't have to specifically number every tile in the array(just define the type)
The method I have currently is probably the best for being able to define types but I want something that looks a bit cleaner and/or information to why my "cleaner" version dosen't work.
var ground = [
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()]];
function tile() {
var y = (Math.random() * 5 | 0) + 6;
return y;
}
This is the code I've been using so far, I have to edit every element of the code with the tile() function to get a random number in each one, what I wanted to have was something like this:
for (var i = 0 ; i < 15; i++) {
for (var j = 0; j < 9; j++) {
ground[[i],[j]] = (Math.random() * 5 | 0) + 6;
}
}
to fill the array without having to add the function to each spot.
I have a feeling that I'm missing a return function or something along those lines but honestly I have no idea.
You were thinking in the right direction but there are some errors in your code ;)
You have to initialize the array first before you can push elements into it.
And you were counting i++ twice
Javascript
var ground = []; // Initialize array
for (var i = 0 ; i < 15; i++) {
ground[i] = []; // Initialize inner array
for (var j = 0; j < 9; j++) { // i++ needs to be j++
ground[i][j] = (Math.random() * 5 | 0) + 6;
}
}
Maybe even better (reusable)
function createGround(width, height){
var result = [];
for (var i = 0 ; i < width; i++) {
result[i] = [];
for (var j = 0; j < height; j++) {
result[i][j] = (Math.random() * 5 | 0) + 6;
}
}
return result;
}
// Create a new ground with width = 15 & height = 9
var ground = createGround(15, 9);
Here's a quick example. I've created a function that will take in a width and height parameter and generate the size requested. Also I placed your tile function inside generate ground to keep it private, preventing other script from invoking it.
var ground = generateGround(10, 10); //Simple usage
function generateGround(height, width)
{
var ground = [];
for (var y = 0 ; y < height; y++)
{
ground[y] = [];
for (var x = 0; x < width; x++)
{
ground[y][x] = tile();
}
}
return ground;
function tile()
{
return (Math.random() * 5 | 0) + 6;
}
}
http://jsbin.com/sukoyute/1/edit
Try removing the comma from...
ground[[i],[j]] = (Math.random() * 5 | 0) + 6;
...in your 'clean' version. Also, your incrementing 'i' in both for loops:
for (var i = 0 ; i < 15; i++) {
for (var j = 0; j < 9; i++) {
Hopefully these changes make it work for you :)

2D array improperly filled and undefined in JavaScript

I am writing a function with two sub-functions: one to print a 2D array from two values in the form and the other to print out the 2D array. At this point, I have been trying to use variables with integer values to fill in the 2D array, but they are not being filled properly. The min variable seems to have the value of 0 within the function instead of what is being passed.
Anyways after I create the 2D array, I try to test print the 2D array 'twoDarray', but it comes up as undefined?
function isValid(frm) {
var xValue = document.getElementById("X").value;
var yValue = document.getElementById("Y").value;
if (xValue <= yValue)
{
/* Draw out the multiplication table. */
function gen2Darray(min, max)
{
var lengthOf2Darray = (max - min);
var twoDarray = new Array(lengthOf2Darray);
for (var i = 0; i < lengthOf2Darray; i++)
{
twoDarray[i] = new Array(lengthOf2Darray);
for (var j = 0; j < lengthOf2Darray; j++)
{
twoDarray[i][j] = ((min + i) * (min + j)); // only takes i
}
}
}
gen2Darray(xValue, yValue);
function print_2d_string_array (array)
{
// print twoDarray, but twoDarray undefined here
}
I have created a jsfiddle account, but it does not work the same way on the site: http://jsfiddle.net/imparante/5yTEv/.
Fix:
function isValid(frm) {
var xValue = document.getElementById("X").value;
var yValue = document.getElementById("Y").value;
var lengthOf2Darray = (yValue - xValue);
var twoDarray = new Array(lengthOf2Darray);
if (xValue <= yValue) {
/* Draw out the multiplication table. */
function gen2Darray(min, max) {
// var lengthOf2Darray = (max - min);
// var twoDarray = new Array(lengthOf2Darray);
for (var i = 0; i < lengthOf2Darray; i++) {
twoDarray[i] = new Array(lengthOf2Darray);
for (var j = 0; j < lengthOf2Darray; j++) {
twoDarray[i][j] = ((min + i) * (min + j));
$("#table").append(twoDarray[i][j] + " ");
}
}
return twoDarray;
}
gen2Darray(xValue, yValue);
function print_2d_string_array(array){
// print twoDarray
}
You're getting undefined on twoDarray because the array is declared and created inside gen2Darray() but you are trying to access it from print_2d_string_array().
If you move your var twoDarray = new Array(); up to you xValue and yValue declarations that should solve the undefined error.
Bin example
function isValid(frm) {
var xValue = document.getElementById("X").value;
var yValue = document.getElementById("Y").value;
var lengthOf2Darray;
var twoDarray = [];
if (xValue <= yValue){
/* Draw out the multiplication table. */
gen2Darray(xValue, yValue);
print_2d_string_array(twoDarray);
}
function gen2Darray(min, max){
lengthOf2Darray = (max - min);
twoDarray = [lengthOf2Darray];
for (var i = 0; i < lengthOf2Darray; i++){
twoDarray[i] = new Array(lengthOf2Darray);
for (var j = 0; j < lengthOf2Darray; j++){
twoDarray[i][j] = ((min + i) * (min + j)); // only takes i
}
}
}
function print_2d_string_array(array){
console.log(array);
}
}
The declarating of the functions were a bit wrong, also the function gen2Darray was not actually returning anything, so the variable twoDarray would only be available in the scope of the function.
Please see fixed code here: http://jsfiddle.net/CC5vP/
I moved the two functions out of the main function declaration and then added a return in gen2Darray(min, max)
It appears to be working, you will want to modify print_2d_string_array(a) to display the data instead of logging it to the console.

Categories

Resources