The "drawStars" challenge - javascript

This code:
function drawStars(){
for (var i = 1; i < 4; i = i + 1){
console.log('*');
for (var l = 1; l < 6; l = l + 1){
console.log('*');
}
}
}
once run, prints stars into the console.
My question is, how can I make it print a 5 by 2 pattern of starts into the console if I type in drawStars(5,2) into the console?
It should also be able to print other patterns corresponding to what I type into the console.
P.S. Can you also fix the unnecessary stars in between the other stars?

You just need to add parameters in your method and use them in them as the loop end-conditions. Also, the unncessary stars are the one you draw in the first loop only. Here the p parameter is the pattern.
function drawStars(x, y, p){
for (var i = 0; i < x; i++){
var line = ""
for (var j = 0; j < y; j++){
line += p;
}
console.log(line);
}
}
If you call it
drawStars(5, 2, '#')
Then it will output a 5x2 rectangle filled with #:
##
##
##
##
##

Related

Pattern printing using js

How do we print pattern like this in javascript in console not with document.write()?
*
#
#
##
##
I tried this but it' not working
for(let i = 1; i <= 5: i++) {
for (let j = 1; j <= i; j++) {
if (j % 2 == 0) {
console.log("#".repeat(j))
}
else {
console.log("*".repeat(i))
}
}
}
console.log() is not intended as a general purpose output stream, there's little ability to customize the layout. You can't call it multiple times and get the output on the same line. If you want output on a single line, it has to be a single call.
Instead of the inner loop, calculate the number of repetitions of *# from i/2, and append another * when i is odd.
for (let i = 1; i <= 5; i++) {
console.log('*#'.repeat(Math.floor(i/2)) + (i % 2 ? '*' : ''));
}

Print Triangle using javascript function

function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
for (var j = 1; j <= i; j++) {
line += "*";
}
}
return line + "\n";
}
console.log(makeLine(2));
I am trying to print triangle, i dont know where i am doing wrong, can some please explain the logic behind printing triangle using nested loops
*
**
***
After you finish printing a line, you need to add a newline "\n" so that you move to the next line. You could do this as below :
function makeLine(length) {
// length has the number of lines the triangle should have
var line = "";
for (var i = 1; i <= length; i++) {
// Enter the first for loop for the number of lines
for(var j=1; j<=i; j++){
// Enter the second loop to figure how many *'s to print based on the current line number in i. So the 1st line will have 1 *, the second line will have 2 *s and so on.
line += "*";
}
// Add a newline after finishing printing the line and move to the next line in the outer for loop
line+="\n";
}
// Print an additional newline "\n" if desired.
return line + "\n";
}
console.log(makeLine(2));
don't forget about .repeat()
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
line+="*".repeat(i)+"\n";
}
return line;
}
console.log(makeLine(3));
The \n was at an incorrect position.
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
for (var j = 1; j <= i; j++) {
line += "*";
}
line += "\n";
}
return line;
}
console.log(makeLine(5));
function hashTriangle(length)
{
let str="";
for(let i=0;i<length;i++)
{
str+="#";
console.log(str);
}
}
hashTriangle(7);
console.log() prints a new line. So it is not necessary for nested loops and confusing newline characters to be appended to our string.
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
for (var j = 1; j <= i; j++) {
line += "*";
}
// add new line after loop is completed
line = line + "\n"
}
return line + "\n";
}
console.log(makeLine(5));
you need to add \n to line when the inner loop is completed
const printTriangle=(symbol,gapSymbol,num) =>{
// const num =25;
let gap = 1;
const Sgap = symbol+' ';
for(i= num-1;i>=0;i--){
let prefixSuffix=''
prefixSuffix = gapSymbol.repeat(i);
let line = ''
if(i == num -1){
   line = gapSymbol.repeat(i)+symbol+gapSymbol.repeat(i);
}
if(i != num -1 && i !=0){
     line = gapSymbol.repeat(i)+symbol+gapSymbol.repeat(gap)+symbol+gapSymbol.repeat(i);
    gap = gap+2;
}
if(i<1){
    line = ''+Sgap.repeat(1)+Sgap.repeat(num-2)+Sgap.repeat(1);
}
console.log(line)
}
}
printTriangle('*','.',15)
This is a JavaScript function that generates a triangle shape using the console.log method. The function takes in three parameters:
symbol: the character to be used to draw the triangle
gapSymbol: the character to be used as a gap in between the symbols
num: the size of the triangle (the number of symbols on the base)
The function starts by initializing the variable gap with the value 1 and Sgap as a string of symbol followed by a space. It then uses a for loop to iterate num number of times, starting from num - 1 down to 0.
For each iteration of the loop, the function uses a single line variable to store the string to be logged. The prefixSuffix variable is used to store the repeated gapSymbols, which are used in each iteration of the loop.
The logic for each iteration is controlled by conditional statements, which determine the shape to be drawn based on the value of i. If i is equal to num - 1, the line is constructed using a single symbol surrounded by repeated gapSymbols. If i is not equal to num - 1 and i is not equal to 0, the line is constructed using repeated gapSymbols, a symbol, a gap of repeated gapSymbols, and another symbol, all surrounded by repeated gapSymbols. If i is less than 1, the line is constructed using repeated Sgaps.
Finally, the constructed line is logged using the console.log method.
Simple solution using padStart, padEnd, repeat method for printing right and left triangle
Left triangle
const printLeftTriangle = (n) => {
let output='';
for (let i = 1; i <= n; i++) {
output +="*".repeat(i).padStart(n) + "\n";
}
return output;
}
console.log(printLeftTriangle(5));
Right triangle
const printRightTriangle = (n) => {
let output='';
for (let i = 1; i <= n; i++) {
output +="*".repeat(i).padEnd(n) + "\n";
}
return output;
}
console.log(printRightTriangle(5));
try this solution please:
const halfTriangle = N => {
for (let row = 0; row < N; row++) {
let line = "";
for (let col = 0; col <= N; col++) {
if (col <= row) {
line += '#';
} else {
line += ' '
}
}
console.log(line);
}
}
halfTriangle(4)
// creates a line of * for a given length
function makeLine(length) {
let line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "\n";
}
// your code goes here. Make sure you call makeLine() in your own code.
function buildTriangle(length) {
// Let's build a huge string equivalent to the triangle
var triangle = "";
//Let's start from the topmost line
let lineNumber = 1;
for (lineNumber = 1; lineNumber <= length; lineNumber++) {
// We will not print one line at a time.
// Rather, we will make a huge string that will comprise the whole triangle
triangle = triangle + makeLine(lineNumber);
}
return triangle;
}
// test your code
console.log(buildTriangle(10));
Center Tringle
let line='';
for(let i=1; i<=5;i++){
line += ' '.repeat(5-i)
line += '*'.repeat(i+i-1)+'\n'
}
console.log(line);

How can I make hollow squares in javascript?

Okay so I need the output to print hollow squares and I'm at a loss right now. I don't want the answer but I would like some hints to help get me on the right track. Thanks!
"use strict"
if (process.argv.length < 3) {
console.log("Not enough command-line arguments given.");
console.log("Usage: node lab13_4.js num");
process.exit();
}
var width = parseInt(process.argv[2]);
function makeLine(width) {
var L = "";
for(var w = 0; w < width; w += 1) { // repeated width many times
L = L + ".";
}
return L;
}
// print the line some number of times.
function printLines(line, howMany) {
// print the right number of lines
for (var i = 0; i < howMany; i += 1) { // repeated height many times
console.log(line);
}
}
for (var x = 0; x <= width; x += 1) {
var line = makeLine(x);
printLines(line, x);
}
If LENGTH be the length of the sides of the square.
You have to make nested loop and check boundary conditions.
for (var i = 0; i < LENGTH; i++) {
for (var j = 0; j < LENGTH; j++) {
if (i == 0 || i == LENGTH - 1 || j == 0 || j == LENGTH - 1) {
process.stdout.write("*")
} else {
process.stdout.write(" ")
}
}
process.stdout.write("\n")
}
We are looking for a solution like this:
*****
* *
* *
* *
*****
The top and bottom sides of the square have the full amount of stars.
All lines in between will only have one star in the beginning of the line and one star at the end of the line.
I use the following function:
function square(input) {
// top line
console.log('*'.repeat(input));
// middle lines
for(let i = 1; i < input - 1; i++) {
console.log('*' + ' '.repeat(input-2) + '*');
}
// bottom line
console.log('*'.repeat(input));
};
square(5);
hope this makes sense :)

JavaScript program crashes page

I made a simple program in JavaScript to find a matrix of the cofactors of a 3X3 matrix. However, the program is crashing my page repeatedly, and I cannot find any logical error in the program. Here's my code :
var matrixA = {
a11:"",
a12:"",
a13:"",
a21:"",
a22:"",
a23:"",
a31:"",
a32:"",
a33:""
};
function determinant (given,order) {
if(order==3){
var det = (given.a11*((given.a22*given.a33)-(given.a23*given.a32)))-
(given.a21*((given.a12*given.a33)-(given.a13*given.a32)))+
(given.a31*((given.a12*given.a23)-(given.a13*given.a22)));
}
else if(order==2){
var det = (given.a11*given.a22)-(given.a21*given.a12);
}
return det;
}
function cofactors(given){
var multiplier;
var temp = {
a11:"",
a12:"",
a21:"",
a22:""
};
var found_cofactor_matrix = {};
for (var i = 1; i <4; i++) {
for (var j = 1; i < 4; j++) {
if(((i+j)%2)==0){
multiplier = 1;
}
else if(((i+j)%2)==1){
multiplier = -1;
}
//Check whether row or column number is the same to make a 2X2 matrix
for(var a = 1; a < 4; a++){
for (var b = 0; b < 4; b++) {
if((a==i)||(b==j)){
} //do nothing
else{
if(temp.a11==""){
temp.a11 = given["a"+a+b];
}
else if(temp.a12 == ""){
temp.a12 = given["a"+a+b];
}
else if(temp.a21 == ""){
temp.a21 = given["a"+a+b];
}
else if(temp.a22 == ""){
temp.a22 = given["a"+a+b];
}
}
};
};
found_cofactor_matrix["a"+i+j] = multiplier*determinant(temp,2);
};
};
return found_cofactor_matrix;
}
Here, the parameter "given" is an object sent to it from the place where the function is called, and is the original matrix (matrixA) whose cofactors have to be found. I basically create a 2X2 matrix first, find its determinant and multiply it with 1 or -1 as required. I then write this value into the appropriate position in the matrix.
for (var j = 1; i < 4; j++) { should be for (var j = 1; j < 4; j++) {.
Remove semicolons at the end of for loop. And add your determinant function.
Did you open your console? Running this code in Chrome's console yields Uncaught ReferenceError: found_cofactor is not defined. You are trying to define the ["a"+i+j] property of an undefined object. It should be found_cofactor_matrix.
Besides, the determinant() function may be undefined (it does not appear in your piece of code)

Google chrome developer tool is inconsistent in nested for loop

While trying to solve this project euler problem (using Google chrome - snippets feature in developer tools to code and execute) , I encountered a strange behavior.
var palFound = false;
isPal = function (word) {
var wordCount = word.length;
for (i = 0; i < wordCount; i++) {
if (word[i] != word[wordCount - i - 1]) {
return false;
}
}
return true;
}
for (var k = 999; k >= 100; k--) {
for (var j = 999; j >= 100; j--) {
var prod = k * j,
prodString = prod + '';
if (isPal(prodString)) {
console.log(prod, k, j);
palFound = true;
break;
}
}
if (palFound) {
break;
}
}
Above code should ideally display the first encountered palindrome product and should break.But when executed the above code displays a wrong answer 580085 which is a product of 995 and 583.
But when the for loops limit are changed to 999 to 900 (as shown below), correct answer is displayed - 906609 which is a product of 993 and 913.
for(var k=999;k >=900;k--){
for(var j=999;j>=900;j--)
ideally, 993 and 913 should be encountered first, instead of 995 and 583. I am curious to know why is this happening?.
For each k value in your outer loop your inner loop counts down from 999 to 100, so when k is 995 then j counts down to 583 finds a palindrome and the code breaks out of your loop.
When you amend j to only count down to 900 it does not reach 583 and so the first palidrome you now reach is 993 * 913.

Categories