Printing Triangle star(*) pattern in javascript using Recursion [duplicate] - javascript

This question already has answers here:
Is there any way to console.log without a newline?
(5 answers)
Closed 3 months ago.
I have been trying to solve printing down left side star(*) pattern in Javascript using recursion, i think my logic is correct but my syntax and concept might be wrong
// * * * * *
// * * * *
// * * *
// * *
// *
This is my code solution so far
var triangle = function (row, col) {
if(row == 0){
return
}
if(col < row){
console.log("*")
triangle(row, col + 1)
}else{
console.log("\n")
triangle(row - 1, 0)
}
}
triangle(4, 0)
output
*
*
*
*
*
*
*
*
*
*
But i want the output to be
* * * * *
* * * *
* * *
* *
*

console.log() closes the output stream automatically, the "line break" is because it is the next output session. You will see its true form if you use document.write.
var triangle = function (row, col) {
if(row == 0){
return
}
if(col < row){
document.write("*")
triangle(row, col + 1)
}else{
document.write("<br/>")
triangle(row - 1, 0)
}
}
triangle(4, 0)
But if you insist to use console.log(), some modification must be made:
var triangle = function (row, col, stream = '') {
if(row == 0){
return
}
if(col < row){
stream += '*'
triangle(row, col + 1, stream)
}else{
console.log(stream)
stream = ''
triangle(row - 1, 0, stream)
}
}
triangle(4, 0)

check this solution
function triangle(row){
var print="";
if(row==0){
return;
}
for(var i=0;i<row;i++){
print+="* "
}
console.log(print);
triangle(row-1);
}
triangle(5);

Related

How to print out a simple horizontal chart? JavaScript

So I just started learning a JS and I can't figure out how to print the asterisks like this:
* * * * *
* * *
* * * * * * *
I could use some help since I am a complete beginner at JS.
I tried based on this example but I can't make it work:
// Square Rectangle
function print_rectangle(x, y) {
var a, b;
for (a = 1; a <= x; a++) {
for (b = 1; b <= y; b++) {
if (a == 1 || a == x || b == 1 || b == y)
document.write("*");
else
document.write(" ");
}
document.write("<br>");
}
}
var rows = 5,
columns = 5;
print_rectangle(rows, columns);
First, think about what your input needs to be. If you want to make a chart of some data, then you should be passing your function an array.
With that array, your function should loop over every element and print that many asterisks. If your array has very high numbers, you might want to add a scale parameter, then divide each number by the scale. Like this:
function plot(scale, data) {
let ret = ''
for (let el of data) {
ret += '*'.repeat(Math.floor(el/scale));
ret += '\n';
}
return ret;
}
console.log(plot(1, [1, 2, 3]));
console.log(plot(1, [5, 1, 4]));
console.log(plot(100, [400, 100, 300]));

How to concatenate the result of two functions in Javascript?

The first two functions produce numbers, and the third should join them, but I'm unsure as to why joinNums() doesn't work.
// random number between specified params
function randInteger() {
let min = 1;
let max = 10;
const randomInteger = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInteger);
}
function randDecimal() {
let decimal = 100;
let integral = 100;
const randomDecimal =
Math.floor(
Math.random() * (integral * decimal - 1 * decimal) + 1 * decimal
) /
(1 * decimal);
console.log(randomDecimal);
}
function joinNums() {
let randomDecimal;
let randomInteger;
randInteger();
randDecimal();
console.log("" + randomDecimal + randomInteger);
}
You're not assigning the function results to the variables.
Your functions should return the result, not console.log it.
You need to call joinNums() (you don't seem to be).
So (see ***):
// random number between specified params
function randInteger() {
let min = 1;
let max = 10;
const randomInteger = Math.floor(Math.random() * (max - min + 1)) + min;
return randomInteger; // ***
}
function randDecimal() {
let decimal = 100;
let integral = 100;
const randomDecimal =
Math.floor(
Math.random() * (integral * decimal - 1 * decimal) + 1 * decimal
) /
(1 * decimal);
return randomDecimal; // ***
}
function joinNums() {
let randomDecimal = randDecimal(); // ***
let randomInteger = randInteger(); // ***
console.log(`${randomDecimal}${randomInteger}`);
}
joinNums(); // ***
Or of course, you can just call them directly rather than writing to variables first:
function joinNums() {
console.log(`${randDecimal()}${randInteger()}`); // ***
}
// random number between specified params
function randInteger() {
let min = 1;
let max = 10;
const randomInteger = Math.floor(Math.random() * (max - min + 1)) + min;
return randomInteger; // ***
}
function randDecimal() {
let decimal = 100;
let integral = 100;
const randomDecimal =
Math.floor(
Math.random() * (integral * decimal - 1 * decimal) + 1 * decimal
) /
(1 * decimal);
return randomDecimal; // ***
}
function joinNums() {
console.log(`${randDecimal()}${randInteger()}`);
}
joinNums(); // ***

Adding all columns together?

function subTotals() {
var otTableTotal = 0;
var sTableTotal = 1;
var r = parseFloat($('#rate').val());
$('.ot').each(function(index) {
if ($(this).data('mins') !== undefined) {
otTableTotal += $(this).data('mins');
}
});
$('#ot_subtotal').html(convertToHours(otTableTotal));
$('#otE_subtotal').text((((otTableTotal / 60) * r) * 1.5).toFixed(2));
var hoursTableTotal = 0;
$('.hours').each(function(index) {
if ($(this).data('mins') !== undefined) {
hoursTableTotal += $(this).data('mins');
}
});
$('.sick').each(function(index) {
sTableTotal += parseInt($(this).val());
});
$('#s_subtotal',this).html(sTableTotal);
$('#hours_subtotal').html(convertToHours(hoursTableTotal));
//$('#tE_subtotal').text(((hoursTableTotal / 60) * r).toFixed(2));
$('#tE_subtotal').text(((((hoursTableTotal / 60) * r)) +(((otTableTotal / 60) * r) * 1.5)).toFixed(2));
$('#rE_subtotal').text((((hoursTableTotal / 60) * r)).toFixed(2));
}
I am having trouble getting my sick column to add up and display where totals is. (The first 2 zeroes are for Hours and Overtime Hours which I have working.) I just can't get this darned sick thing to work.
Try removing the context (this) here:
$('#s_subtotal',this).html(sTableTotal);

Triple conditioned do while loop

I'm trying to assign three random numbers to three variables (random1, random2, random3), and then assign these random variables to three elements. But I don't want any of them to be equal to the variable Sum which is the addition of two numeric innerHTML values.
So I have done that using do...while loop, but unfortunately the do...while loop doesn't work as expected .
Here is my code :
setTimeout(function () {
z.innerHTML = Math.floor((Math.random() * 3) + 1);
setTimeout(function applySUM() {
var Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
}, 500);
do {
var random1 = Math.floor((Math.random() * 3) + 1);
var random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
var random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
setTimeout(function func() {
ch2.innerHTML = random1;
}, 1000);
setTimeout(function func() {
ch3.innerHTML = random2;
}, 1500);
setTimeout(function func() {
ch4.innerHTML = random3;
}, 2000);
}, 2000);
Looking at the code above, it seems to be impossible for the ch2.innerHTML, ch3.innerHTML and ch4.innerHTML to be equal to Sum, but when I test it the reality says something else. Why is this?
First thing, as many people mentioned, the sum variable is local to ApplySum so the rest of your code is referencing a global Sum variable instead (and it is "undefined" by default)
Another problem is that right now your do-while loop runs immediately, without waiting the 500 ms timeout and before Sum is assigned to a value. You can fix this by putting your code inside the settimeout callbacks:
z.innerHTML = Math.floor((Math.random() * 3) + 1);
setTimeout(function applySUM() {
var Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
do {
var random1 = Math.floor((Math.random() * 3) + 1);
var random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
var random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
setTimeout(function func() {
ch2.innerHTML = random1;
}, 500);
setTimeout(function func() {
ch3.innerHTML = random2;
}, 1000);
setTimeout(function func() {
ch4.innerHTML = random3;
}, 1500);
}, 500);
(I also decreased 500ms from the other settimeouts to compensate for them being moved inside the first timeout)
Another tiny change you could consider is doing a separate loop for each variable instead of a single one for all of them.
var random1, random2, random3;
do { random1 = Math.floor((Math.random() * 3) + 1); } while (random1 == Sum);
do { random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4; } while (random2 == Sum);
do { random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7; } while (random3 == Sum);
The comments about scope seem like they're on the right track. Here's the relevant part of your code:
setTimeout(function applySUM() {
var Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
}, 500);
// Outside of your applySum function, Sum has no meaning
do {
var random1 = Math.floor((Math.random() * 3) + 1);
var random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
var random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
// Outside of your loop body, random1, random2, and random3 have no meaning
// undefined == undefined => true
Perhaps if you changed it to this:
var Sum = 0;
setTimeout(function applySUM() {
Sum = parseInt(document.getElementById('fir').innerHTML) +
parseInt(document.getElementById('sec').innerHTML);
ch1.innerHTML = Sum;
}, 500);
var random1 = random2 = random3 = undefined;
do {
random1 = Math.floor((Math.random() * 3) + 1);
random2 = Math.floor(Math.random() * (6 - 4 + 1)) + 4;
random3 = Math.floor(Math.random() * (10 - 7 + 1)) + 7;
} while (random1 == Sum || random2 == Sum || random3 == Sum);
Then your variables might have scope in the appropriate spots. Just a hunch, there might be something else wrong with this.

How can I generate a random number between 1 - 10 except that the random number can't be 3

How can I generate a random number between 1 - 10 except that the random number can't be 3
Get a random number between 1 and 9 and then add one if it's 3 or greater, or
better, just change any 3s into 10s.
function getNumber() {
return (n = 9 * Math.ceil(Math.random())) === 3? 10: n;
}
Based on this nice answer:
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var rand;
while((rand = getRandomInt(1, 10)) == 3);
// rand is now your random number
function rand(begin, end) {
var result = Math.floor( Math.random() * (end - begin + 1) ) + begin;
return result === 3 ? rand(begin, end) : result;
}
function rand(){
var r = Math.ceil(Math.random() * 10);
if (r==3){
return rand()}
else
return r;
}
Here's a short, quick solution, using a self-executing function, that does what you need exactly but is only useful for the specific circumstance you describe:
var randOneToTenButNotThree = function () {
var result = Math.floor(Math.random() * 10) + 1; // PICK A NUMBER BETWEEN 1 AND 10
return (result !== 3) ? result : randOneToTenButNotThree(); // IF THE NUMBER IS NOT 3 RETURN THE RESULT, OTHERWISE CALL THIS FUNCTION AGAIN TO PICK ANOTHER NUMBER
}
var result = randOneToTenButNotThree(); // RESULT SHOULD BE A NUMBER BETWEEN 1 AND 10 BUT NOT 3
However, you could abstract this out to produce a random number in any given range, excluding any number of your choice:
var randExcl = function (lowest, highest, excluded) {
var result = Math.floor(Math.random() * (highest - lowest)) + lowest;
return (result !== excluded) ? result : randExcl();
}
var result = randExcl();
Just don't forget that if the function is renamed, you should also change the reference to it from within at the end of that return statement so that it can keep calling itself whenever it produces the excluded number.
This should work.
var r = 3;
while(r == 3) r = Math.ceil(Math.random() * 10);
function r(){a = Math.floor(Math.random() * 10) + 1; if (a==3) a++; return a;}

Categories

Resources