draw a Triangle in numbers (javascript) [duplicate] - javascript

This question already has answers here:
How to display pyramid using JavaScript?
(34 answers)
Closed 4 years ago.
I wrote this method that draw a Triangle. For example if you call drawTriangle(5) you get the following output:
this is my code :-
function drawTriangle(t){
for (let i=1; i <= t; i++)
{
for (let j=1; j<=i; j++)
{
console.log(j+" ");
}
console.log("\n");
}
}
let t = 5 ;
drawTriangle(t);
and i get this output
I can not make them in a line I don't Know where is the problem .

console.log() will print a new line every time, store each line in a variable and print it at the end of innerLoop
function drawTriangle(t){
for (let i=1; i <= t; i++)
{
let eachLine = ''
for (let j=1; j<=i; j++)
{
eachLine += j + " "
}
eachLine = eachLine.trim();
console.log(eachLine);
}
}
let t = 5 ;
drawTriangle(t);

Refer to this. You can use string concatenation in your inner for loop.

Well other answer has already specified what you missed in your code.
I am adding it in case you want to see a alternate solution
let n = 1;
let op = ''
while(n<=5){
op+=new Array(n).fill(0).map( (e,i) => i+1 ).join(' ') + '\n'
n++
}
console.log(op)

Here's a solution with linear time complexity--just console.log(draw(n)), where n is an integer, to see the result:
function draw(n) {
let triangle = '';
let prev;
for (let i = 1; i <= n; i++) {
if (prev) {
triangle += '\n';
prev = prev + ' ' + i;
} else {
prev = i;
}
triangle += prev;
}
return triangle;
}

Related

Javascript Multiplication table in 2D array

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);

creating a for-loop that prints # signs instead of number values [duplicate]

This question already has answers here:
How to print a half pyramid in javascript
(9 answers)
How to print star pattern in JavaScript in a very simple manner? [closed]
(22 answers)
Closed 1 year ago.
im trying to write a code that outputs lines of '#' signs that increase by one for each value until the input number is reached.
for example, when triangles(3) is called my desired output is:
'#'
'##'
'###'
ive learned how to create this sequence with number values instead of the '#' signs but not sure how to achieve this output displayed above. thanks!
function triangles(num) {
let number = '';
for (let i = 1; i <= num; i++) {
console.log(number += i);
}
}
triangles(5)
this outputs:
'1'
'12'
'123'
'1234'
'12345'
You can use String.prototype.repeat() to repeat the pound (#) character as specified by the current value of i, without needing to declare a new variable to store it:
function triangles(num) {
for (let i = 1; i <= num; i++) {
console.log('#'.repeat(i));
}
}
triangles(5);
function triangles(num) {
let symbol = "#";
for (let i = 1; i <= num; i++) {
console.log(Array(i).fill(symbol).join(""));
}
}
triangles(5);
function triangles(num) {
const c = "#";
for (let i = 1; i <= num; i++) {
console.log(c.repeat(i));
}
}
triangles(5)
You don't have to use console.log to print number += i specifically. If you want to print '#' multiple times, you can use #Terry's answer (which is shorter) or you can use another for loop in your code (this approach could be simpler for beginners).
function triangles(num) {
let number = '';
for (let i = 1; i <= num; i++) {
number++;
let poundkeys = '';
// dont use i again, name it something else (like j or k)
for (let j = 1; j <= number; j++) {
// just like you do number += i, add a pound symbol to poundkeys
poundkeys += '#';
}
// now, log poundkeys
console.log(poundkeys);
}
}
triangles(5);
Also, a quick tip. Generally, it is better not to log number += i. Instead of:
console.log(number += i);
It is encouraged and more readable if you separate them:
number += i;
console.log(number);

Javascript Fib series test case fails

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?

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);

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

Categories

Resources