Good day,
I need to make a method that makes the multiplication table in console.log.
This method should receive a number to which it outputs the multiplication table.
The table should be appeared in the console (console.log). For example, if the number 5 came to the input, we get:
Important note:
In the last line between the numbers, exactly one space should be output.
In each column, the numbers should be aligned to the right.
I have searched everywhere, but I have not found a similar solution to this particular problem anywhere.
I don't quite understand how we can indent and add numbers on the sides. I only got it this way:
function multiplicationTable(value) {
let table = '';
for (let i = 1; i <= value; i++) {
let tableString = '';
for (let j = 1; j <= value; j++) {
tableString += ' ' + (i * j) + ' ';
}
tableString += '\n';
table += tableString;
}
return table;
}
console.log(multiplicationTable(5));
Try something like this :
function multiplicationTable(value) {
let table = '\n';
let maxLength = (value * value).toString().length;
for (let i = 0; i <= value; i++) {
let tableString = '';
for (let j = 0; j <= value; j++) {
let product = i * j;
let padding = ' '.repeat(maxLength - product.toString().length + 1);
tableString += padding + (product || ' ');
}
table += tableString + '\n';
}
console.log(table);
}
multiplicationTable(5);
Explanation :
let table = '\n'; creates an empty string with a newline character, which will be used to store the multiplication table.
let maxLength = (value * value).toString().length; finds the length of the largest number that will appear in the table, which is value * value. This length will be used to set the width of each column in the table.
for (let i = 0; i <= value; i++) creates a for loop that will iterate value + 1 times, where i is the row number. The 0 in i = 0 is because we want the first row to display the column headers (i.e. the numbers 0, 1, 2, ..., value).
let tableString = ''; creates an empty string that will be used to store each row of the table.
for (let j = 0; j <= value; j++) creates a nested for loop that will iterate value + 1 times, where j is the column number. The 0 in j = 0 is because we want the first column to display the row headers (i.e. the numbers 0, 1, 2, ..., value).
let product = i * j; calculates the product of the row and column numbers, which is the number that will appear in the table at that position.
let padding = ' '.repeat(maxLength - product.toString().length + 1); adds spaces to the left of the product so that each column has the same width. maxLength is the width of each column, and product.toString().length is the length of the product. The + 1 in maxLength - product.toString().length + 1 adds an extra space to the left of each product.
tableString += padding + (product || ' '); adds the padding and product (or an empty string, ' ', if i or j is 0) to the tableString. This creates the row of the table.
table += tableString + '\n'; adds the tableString and a newline character to the table. This creates a new row in the table.
Related
I'm a really beginner and for now im preparing for JavaScript bootcamp. Unfortunately i stuck with one of pre-work excercises.
My task is to do muliplication table, put it into empty 2D Array and print it precisely in this form:
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
On start I have 2 var declared:
const n = 3;
const calc = [];
I know i have to start with 'for' loop - and i have no idea whats next;
for (let i = 1; i <= n; i++) {
}
EDIT:
Thanks for help, correct code below:
const n = 3;
const calc = [];
for(let i = 0; i < n; i++){
calc[i] = [];
for(let k = 0; k < n; k++){
calc[i][k] = (i + 1) + ' * ' + (k + 1) + ' = ' + (i + 1) * (k + 1);
}
}
for(let i = 0; i < calc.length; i++){
console.log(String(calc[i]).replaceAll(',', ' | '));
}
You need two 'for' loops to fill the array in 2D. After that you need another 'for' loop to print each row (for example in a paragraph tag).
Working example:
const n = 3;
const calc = [];
for(i = 0; i < n; i++){
calc[i] = []; //add the inner arrays (the second dimension)
for(k = 0; k < n; k++){
calc[i][k] = (k + 1) + ' x ' + (i + 1) + ' = ' + (k + 1) * (i + 1);
}
}
for(i = 0; i < calc.length; i++){
const p = document.createElement("p");
//convert each inner array to a string
p.innerHTML = String(calc[i]).replaceAll(',', ' | ');
document.querySelector('#container').appendChild(p);
}
<div id="container"></div>
This is what I have come up with...
n = 3;
// create table array
table = [];
for(row=0; row<n;row++){
// generate an array for each row
table.push([])
for(col=0; col<n;col++){
// add the multiplication to each column in the row
// Notice that the column and row numbers start at zero in an array so 1 is added before multiplying
table[row].push((col+1) + ' x ' + (row+1) + ' = ' + (col+1)*(row+1));
}
}
// print the array to the console for fun
console.log(table);
// go through each row in table array, convert it to a string and replace ',' with ' | ' and printing it to the log
// Notice that in the replace argument you have to use /,/g instead of ',' in order to replace all commas and not just the first one
for(row=0; row<table.length;row++){
console.log(String(table[row]).replace(/,/g, ' | '))
}
I have added a bit of commenting. Hopefully you can see what is going on.
Here is the code I would write to solve your problem.
function generate(num, fn) {
var a = Array(num), b = 0;
while (b < num) a[b] = fn(b++);
return a;
}
const table = (num, fn, separator) => generate(num, fn).join(separator);
const entry = (a, b) => `${a} x ${b} = ${a * b}`;
const result = table(3, row => table(3, col => entry(row + 1, col + 1), ' | '), '\n');
console.log(result);
generate returns an array like [fn(0), fn(1), fn(2), ..., fn(num-1)]. There's more than one way to do this but what I provided here is pretty quick.
table calls generate, but with the elements joined together into a string with a separator between them.
entry formats the text of one entry in the table like: 2 x 3 = 6
The result is a table of tables (a two-dimensional table) with | delimiting the columns and \n delimiting the rows.
Note:
If you insist on having a complete 2D array, you could defer the joins until later like this, but it's slower:
function generate(num, fn) {
var array = Array(num), i = 0;
while (i < num) array[i] = fn(i++);
return array;
}
const entry = (a, b) => `${a} x ${b} = ${a * b}`;
const array2d = generate(3, row => generate(3, col => entry(row + 1, col + 1)));
const result = array2d.map(row => row.join(' | ')).join('\n');
console.log(result);
1 Loop for Rows and 1 Loop for Columns
OP wasn't specific about what said output of the multiplication table should be in -- HTML, text, ponies...?
A table can be generated by an outer loop and an inner loop:
The outer loop generates an array rows of a table.
[row 1, row 2, row 3]
The inner loop generates an array of cells (forming a column) for each row.
[col 1, col 2, col 3]
So a 2D array looks like one or more arrays within an array.
[ row 1[col 1, col 2, col 3], row 2[col 1, col 2, col 3], row 3[col 1, col 2, col 3] ]
The example below is a function that will pass a number (num) through and return a table with the same amount of rows and columns as the parameter passed (num). Each cell will contain the text of a simple formula:
row number * col number = X
Each col is delimited by a pipe |, and each row is delimited by a new line.
Details are commented in Snippet
// Pass a number [num]
function mTable(num) {
// Declare [row] array [rData]
const rData = [];
// for each [row] until [num] is reached...
for (let row = 1; row <= num; row++) {
//... declare [col] array [cData]...
const cData = [];
//... then for each [col] until [num] is reached...
for (let col = 1; col <= num; col++) {
//... generate the text✱ repesenting the product of the row and column numbers...
const cell = `${row} X ${col} = ${row*col}`;
//... next, push it to the [cData] array
cData.push(cell);
}
// Once the [cData] is created, convert it into a formatted line of text delimited by pipes '|'
const data = cData.join(' | ');
// Push the [cData] array into the [rData] array
rData.push(data);
}
// After the last [cData] array is pushed into the [tData] array, output [tData] as a formatted line of text delimited by new lines✱
return rData.join(`
`);
}
// Generate a 3x3 table
console.log(mTable(3));
// Generate a 8x8 table
console.log(mTable(8));
/*
✱The special syntax wrapped in grave ticks `...` is called template literals see References
*/
References
for Loop
.push()
.join()
Template Literals
I am trying to create a script that allows the user to enter a certain amount of rows which will then print a large letter X, so far I am able to print it as a v shape but am struggling to get the rest of the x together.
rows = 0;
space = " ";
var user_input = parseFloat(prompt("Enter how many rows:", 0));
while (rows < user_input) {
space_counter = 0;
while (space_counter < rows) { //process1
document.write(space);
space_counter++;
}
document.write("x"); //process2
rows++;
midspace_counter = 0;
while (midspace_counter < user_input - rows) { //process3
document.write(space + space);
midspace_counter++;
}
document.write("x<br>"); //process4
rows++;
}
How i would do that:
let result = "";
const maxRow = +prompt("how many rows?");
// Knowing the half size of our x might be useful
const half = (maxRow - 1) / 2;
for(let row = 0; row < maxRow; row++){
// For e.g. maxRow = 7 this will be 3 2 1 0 1 2 3
const midspace = Math.abs(half - row);
const pad = maxRow - midspace - 1;// 1 = "x"
// \n means newline
result += " ".repeat(pad) + "x" + " ".repeat(midspace * 2) + "x\n";
}
Then you just need to append that to the document.
I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.
I have to create an array using a for loop to produce the numbers 0-24. Then print these numbers in order in a 5x5 "table" using a for loop.
The output should be: 0 1 2 3 4 x 5 6 7 8 9 x 10 11 12 13 14 x... 20 21 22 23 24
I can't figure out how to create the table.
Here is my code:
// Calculate numbers 0-24
var numbers = [];
for (var 0; i < 25; i++) {
numbers[i] = i;
}
// Create table
for (var row = 0; row < 4; row++) {
document.write('<tr>');
for (var col = 0; col < 4; col++) {
document.write('<td>' + numbers + '</td>');
}
document.write('</tr>');
}
The problem is that you are accessing the array without any index. Try this instead:
var numbers = [];
for ( var 0; i<25; i++)
{
numbers[i]= i;
}
//Create table
var i = 0;
var table = "<table>";
for (var row=0; row<5; row++) //Changed from 4 to 5
{
table += "<tr>";
for (var col=0; col<5; col++) //Changed from 4 to 5
{
table += "<td>" + numbers[i] + "</td>"; //numbers to numbers[i]
i++;
}
table += "</tr>";
}
table += "</table>";
document.write(table);
Update: Taking from what #Jon P answered I updated my answer to only write once.
This looks like a homework assignment so I'll make some suggestions instead of an out right answer.
Dont use document.write.
Create a table stub on the page using HTML and give it an ID. Find out how to get element by id. Find out how to update the inner html of that element. Only update the document once.
Use a tool like Firebug for Firefox or Developer tools for Chrome to inspect what is rendered to the page so you can work out what went wrong (or right).
Start your search for knowledge here: https://developer.mozilla.org/en-US/docs/Web/JavaScript
For an added bonus you may be able to do this without nested for loops with the help of the % operator
Supremely overkill, but maybe you will find these functions useful!
// creates an array that contains a sequence of numbers from 0 to size-1
function range(size) {
size = Math.max(0, size);
var result = [];
while (size--) { result.unshift(size); }
return result;
}
// splits an array into chunks of a certain size.
function chunk(array, size) {
if (!array || !array.length || size < 1) { return array };
return [array.slice(0, size)].concat(chunk(array.slice(size), size));
}
// takes a 2D array and converts it to an HTML table.
function createHTMLTable(table) {
var html = table.map(function(row) {
row = row.map(function(cell) { return "<td>"+ cell +"</td>"; });
row = row.join('');
return "<tr>"+ row +"</tr>";
});
html = html.join('');
return "<table>"+ html +"</table>";
}
function renderHTML(html) {
document.write(html);
}
var numbers = range(25);
var table = chunk(numbers, 5);
var tableHTML = createHTMLTable(table);
renderHTML(tableHTML);
I'm trying to code a simple piece of javascript that reads in a CSV (pasted into a textarea on a webpage) and generates SQL insert statements but I keep getting undefined values when I reference the 2D array..
Please help!
var ret = "";
//alert("called");
//split the textarea into rows of text
var lines = text.split("\n");
//the first line of text is the table name
var table = lines[0];
//the second line of text is an array of the attribute names
var attrnames = lines[1].split(",");
var values = new Array();
//create a new array for each attribute
for (var i = 0; i < attrnames.length; i++) {
//the length of each array is the total number of rows
//of text - 2 (title row and attr row)
values.push(new Array(lines.length - 2));
}
//for each subsequent row, push the values to the appropriate arrays
for (var i = 2; i < lines.length; i++) {
//get the current row (value, value, value, value)
var thisrow = lines[i].split(",");
for (var j = 0; j < attrnames.length; j++) {
//add the j-th attribute (thisrow[j]) to its array (values[j])
values[j].push(thisrow[j]);
}
}
var insertIntoTable = "";
var tableName = "";
var attrList = "";
var valueList = "";
var lead = "";
//loop through each row
for (var k = 2; k < lines.length; k++) {
// --- ONE STATEMENT ---
//create the statements
insertIntoTable = "insert into table `";
tableName = table;
attrList = "` (";
valueList = "(";
for (var i = 0; i < attrnames.length; i++){
attrList += "`" + attrnames[i] + "`,";
}
//trim the last comma, then add the closing parenthesis.
attrList = attrList.substring(0, attrList.length-1) + ") ";
lead = insertIntoTable + tableName + attrList;
for (var i = 0; i < attrnames.length; i++) {
//this always points to undefined
valueList += "'" + values[i][k-2] + "', ";
}
lead += (" values " + valueList);
lead = lead.substring(0, lead.length-2) + ");\n";
ret += lead;
}
alert(ret);
In JavaScript you do not need to set the length of arrays. They are more like ArrayLists or something; read more at MDN's documentation.
When you do
var x = new Array(10); // array with "length" set to 10
x.push("somevalue");
then the value will be inserted at x[10] - at the end of the list. Log it in the console to see it yourself.
So either you drop the push() and use absolute indizes instead, or initialize the array as empty - best with the array literal syntax: []. The relevant area of your code should then look like this:
//create a new empty array for each attribute
for(var i = 0; i<attrnames.length; i++){
values.push([]);
}
You are making an array of length n, where n is the number of rows, and then you are pushing on n more elements of data. Start with 0 length arrays and you will be fine:
//create a new array for each attribute
for(var i = 0; i<attrnames.length; i++){
values.push(new Array(0)); // or '[]' -> the length of each array **will be** the total number of rows of text-2 (title row and attr row)
}
I would add caution that pasted data will be prone to lots of errors and potential security issues, such as SQL injection attacks. Aside from that, what happens if you have extra \ns at the end of your data? You will end up with more undefined data.