Pattern printing using js - javascript

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 ? '*' : ''));
}

Related

Print sequence of numbers in javascript

I'm sure this is quite a simple programming question however, I cant seem to understand it...
I'm trying to make the console.log print out numbers like this - 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 - one for each line. I thought modulo could be used to make this happen, however, I cant seem to figure out how to use it.
Here is the code:
iteration = 16;
for (var i = 0; i < iteration; i++) {
if(i == iteration%4 )
console.log(i);
}
Yes, you need a single loop.
No, you do not need the remainder operator %. This would give you
0 1 2 3 0 1 2 3 ...
But instead you could divide the actual value by 4 and take the integer value for console.log.
const iteration = 16;
for (let i = 0; i < iteration; i++) {
console.log(Math.floor(i / 4) + 1); // offset for starting with 1
}
I suggest that you use two nested for loops, one for the rows and another one for the columns.
Here's an example of how i would do it:
const columns = 4;
const rows = 4;
//if you want to just console.log each number on a different line
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= columns; j++) {
console.log(i);
}
console.log("\n");
}
//if you want to add each number to an array, and then log the array
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
console.log(columnsArray);
}
//if you want to just log the numbers, you can spread the array
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
console.log(...columnsArray);
}
//or you could push the arrays in another one, and get a matrix!
const matrix = [];
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
matrix.push(columnsArray);
}
console.log(matrix);
It was not clear the output that you wanted, so i got a little sidetracked and made an example for the different cases that came to my mind.

For-loops and if-statements on cross referenced sheets

I've got 5 sheets - 1 main sheet and 4 sheets for data. The 4 sheets hold a column of W's and L's, and the main sheet has 8 cells to keep track of these - one cell for each # of W's and # of L's. I'm trying to do so with the following script and then calling the methods in the respective cells of the main sheet.
function totalWins(data) {
var win = 0;
for(var i = 0; i < data.length; i = + 1) {
if(data[i][0] = "W") {
win = win + 1;
}
}
return win;
}
function totalLosses(data) {
var loss = 0;
for(var i = 0; i < data.length; i = + 1) {
if(data[i][0] = "L") {
loss = loss + 1;
}
}
return loss;
}
I get the Internal error executing the custom function. error, which means the code takes longer than 30 seconds to run through the column (n = 100) in one of the four sheets. I really can't figure out why it does this. Any help is appreciated!
You need to increment i. Without you assign +1 to i and the loop takes only the first two values and loops forever with i === 1.
for (var i = 0; i < data.length; i = i + 1) {
// ^
or a bit shorter
for (var i = 0; i < data.length; ++i) {
As mentioned in the comments by TheWizEd, you assign a value if the if statement, where you should compare the value
if (data[i][0] === "W") {
// ^^ strict comparison
You placed + at wrong place in your code
for (var i = 0; i < data.length; i = + 1) {
// ^
|____ This makes acts as `+` sign
So in this case you're not actually incrementing your index so you loop keep on running
change to this
for (var i = 0; i < data.length; i += 1) {
// ^
|_____ This acts as `addition`
Or simply use i++
Fixed it by changing the counters win = win + 1 and loss = loss + 1 to win +=1 and loss +=1. Also with the above increments.

Palindrome: finding the shortest possible string

The task is the following: "Write a JavaScript program to find the shortest possible string which can create a string to make it a palindrome by adding characters to the end of it."
This is the code I am looking at:
function build_Palindrome(new_str) {
var flag;
for (var i = new_str.length;; i++) {
flag = true;
for (var j = 0; j < i - j - 1; j++) {
if (i - j - 1 < new_str.length && new_str[j] != new_str[i - j - 1]) {
flag = false;
break;
}
}
if (flag) {
for (var j = new_str.length; j < i; j++) {
new_str += new_str[i - j - 1];
}
return new_str;
}
}
}
Test:
console.log(build_Palindrome("abcddc"))
Output:
abcddcba
My question: At first it starts with j=0. If in the for loop, flag=false, then how does it proceed? Is i=7 (i++?) and is j=0 or j=1?
Yes, you can use console.log or any debugger to debug.
For your situation, you if the flag is false, it will break the loop of j and go to its outer loop (i here)
I made the demo here:
https://repl.it/repls/LoyalProfuseRouter
You can see the demo (it come with my solution), and instead of break you can use simple loop to return your string, it more readable.

The "drawStars" challenge

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 #:
##
##
##
##
##

I am trying to loop through an array of all the alphabets and capitalize every other alphabet. any solutions?

this is the code i came up with:
var alpha = "abcdefghijklmnopqrstuvwxyz".split('');
// console.log(alpha);
// console.log(alpha.length);
for(i=0; i < alpha.length + 1; i++){
if (alpha.indexOf('a', +1) % 2 === 0){
console.log(indexOf('a'));
} else {
console.log("didn't work");
}
};
A simple loop with a step:
for (var i = 0; i < alpha.length; i+=2) {
alpha[i] = alpha[i].toUpperCase();
}
alpha.join(''); // AbCdEfGhIjKlMnOpQrStUvWxYz
If aBcDeFgHiJkLmNoPqRsTuVwXyZ is what you want to achieve, than you can do something like this:
var alpha = 'abcdefghijklmnopqrstuvwxyz';
var result = '';
for (var i = 0; i < alpha.length; i++) {
if ((i + 1) % 2 === 0){
result += alpha[i].toUpperCase();
} else {
result += alpha[i];
}
}
console.log(result);
You can map your array and upper case every second character:
var alpha = "abcdefghijklmnopqrstuvwxyz".split('').map(function(ch, i) {
return i % 2 ? ch.toUpperCase() : ch;
});
console.log(alpha);
The issue with strings is that you can't edit them, once created they stay the same. Most actions on them create a new string.
To avoid doing this lots of times, we do the following
var alpha = 'abcdefghijklmnopqrstuvwxyz'.split('');
Convert the string into an an array
for (var i = 0; i< alpha.length; i++) {
if(i % 2 == 0) {
go down the array, and for every other entry (i % 2 gives us 0 every other time).
alpha[i] = alpha[i].toUpperCase();
convert it to upper case
}
}
var newString = alpha.join('');
and finally make a new string by joining all the array elements together. We have to provide a null string ie '' because if we didn't provide anything we would join with commas (,)
var alpha = "abcdefghijklmnopqrstuvwxyz".split('');
for(i=0; i < alpha.length; i++){
console.log(alpha[i].toUpperCase());
//If you want to update
alpha[i] = alpha[i].toUpperCase();
};

Categories