Here is the my javascript code for printing the pattern shown below in the image.
please check the code and solve the error.
<script>
var n = prompt("Enter the number of n you want to print");
//rows = Math.floor(n / 2)
let str = ""
var i, j, k
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){
str += "*"
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(j = 1; j <= i; j++){
str += "*"
}
str += "\n"
}
for(i = 1; i <=n + 2; i++){
for(j = n + 2; j > i; j--){
str += "*"
}
for(k = 1; k <= i; k++){
str = " "
}
for(k = 1; k <= i; k++){
str = " "
}
for(j = n + 2; j > i; j--){
str += "*"
}
str += "\n"
}
console.log(str)
</script>
I want Output like this :
but I got just 2 spaces in output
Convert your input to Number:
n = Number(n);
and then change your code as #TomLV mentioned:
var n = prompt("Enter the number of n you want to print");
//rows = Math.floor(n / 2)
n = Number(n);
let str = ""
var i, j, k
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){
str += "*"
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(j = 1; j <= i; j++){
str += "*"
}
str += "\n"
}
for(i = 1; i <=n + 2; i++){
for(j = n + 2; j > i; j--){
str += "*"
}
for(k = 1; k <= i; k++){
str += " "
}
for(k = 1; k <= i; k++){
str += " "
}
for(j = n + 2; j > i; j--){
str += "*"
}
str += "\n"
}
console.log(str)
You are setting str equal to " " in both "k loops" in the second "i for loop".
e.g:
for(k = 1; k <= i; k++){
str = " "
}
for(k = 1; k <= i; k++){
str = " "
}
If you update those to += it works.
Some issues:
prompt returns a string, you need to convert it to a number. You can use the unary plus for that.
str = " " occurs at two places where you should have done str += " "
The generated pattern has two spaces in the center line, while you are asked to only have one space there. To make that happen have the k loops make one iteration less, and add str += " " as a separate statement outside of those loops.
The output has an empty line at the very end. This is because the second i loop is making one iteration too many.
Not a problem, but:
Use semi-colons to separate statements. Although JavaScript provides automatic semi-colon insertion, you wouldn't be the first to fall into one of the pitfalls. It is better to take control of this yourself and have the habit of adding the semi-colons.
There really is no need here to declare loop variables at the top. Just declare them at the moment you need them with only the scope they need to have.
I'll assume that the number of lines in the output is supposed to be n*2+1 and that there was no error concerning that aspect.
Corrected code:
// Convert string to number using unary plus:
const n = +prompt("Enter the number of n you want to print");
let str = "";
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= i; j++) {
str += "*";
}
// Reduced the number of iterations here:
for (let k = n; k >= i; k--) {
str += " ";
}
// Add one space for the center column
// that is the only column without asterisks
str += " ";
// Reduced the number of iterations here:
for (let k = n; k >= i; k--) {
str += " ";
}
for (let j = 1; j <= i; j++) {
str += "*";
}
str += "\n";
}
// Reduced number of iterations. i should not become equal to n + 2
for (let i = 1; i <= n + 1; i++) {
for (let j = n + 2; j > i; j--) {
str += "*";
}
// Reduced the number of iterations here:
for (let k = 1; k < i; k++) {
str += " "; // Fixed assignment
}
// Add one space for the center column
// that is the only column without asterisks
str += " ";
// Reduced the number of iterations here:
for (let k = 1; k < i; k++) {
str += " "; // Fixed assignment
}
for (let j = n + 2; j > i; j--) {
str += "*";
}
str += "\n";
}
console.log(str);
Note that JavaScript has functions that can facilitate this proces, like "*".repeat(i) can be used instead of a loop to produce the same string.
So then it becomes:
const n = +prompt("Enter the number of n you want to print");
let str = "";
for (let i = 1; i <= n + 1; i++) {
str += "*".repeat(i) + " ".repeat(2*n + 3 - 2*i) + "*".repeat(i) + "\n";
}
for (let i = n; i >= 1; i--) {
str += "*".repeat(i) + " ".repeat(2*n + 3 - 2*i) + "*".repeat(i) + "\n";
}
console.log(str);
And you could also reuse the results of the first loop to derive the second half of the output by storing the lines in an array. You can then reverse that array to get the second half (without the middle line):
const n = +prompt("Enter the number of n you want to print");
const arr = Array.from({length: n + 1}, (_, i) =>
"*".repeat(i+1) + " ".repeat(2*(n-i)+1) + "*".repeat(i+1)
);
console.log([...arr, ...arr.reverse().slice(1)].join("\n"));
Related
I'm trying to print a pyramid that has odd numbers for edges. For example output should be:
.......5
...3,4,3
1,2,3,2,1
(dots are here just to show formating)
I managed to write:
function p(n){
let string = "";
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n - i; j++) {
string += " " ;
}
for (let k = 1; k <= 2*i-1; k++) {
string += n-k +1;
}
string += "\n";
}
console.log(string);
}
p(5);
But I'm not sure how to continue to get wanted result
You can try it :
function p(n){
let string = ""
for (let i = 0; i <= n/2; i++) {
let k = n - 2 * i
for (let j =0; j < Math.floor(n/2)*2 + 1; j++) {
if(j < Math.floor(n/2) - i) {
string += " ";
}
if( j >= Math.floor(n/2) - i && j <= Math.floor(n/2) + i) {
string += k;
j < Math.floor(n/2) ? k++ : k--
}
if(j > Math.floor(n/2) + i ) {
string += " ";
}
}
string += "\n";
}
console.log(string);
}
p(7);
Okay, so obviously you can't make an integer a superscript since it's a number. I need you guys. How would I take the integer from the loop and make it into a string so I can .sup() it. I'm open to using an array.
Here is the original
var n;
for (let i = 0; i <= 31; i++) {
n = Math.pow(2, i);
document.write("2 ^ " + i + " = " + n + "<br>");
}
Here is with an array (NOT FUNCTIONING!)
var n, myArray = [];
for (let i = 0; i <= 31; i++) {
myArray.push(Math.pow(2, i));
}
for (var j = 0; j <= 31; j++) {
document.write("2" + myArray[j].sup() + " = " + n + "<br />");
}
Thoughts?
sup is a method on String. So, you have to convert the number to a String first:
myArray[j].toString().sup()
Note: in many cases anything is converted to String implicitly, but not when you call a method on an object.
var n, myArray = [];
for (let i = 0; i <= 31; i++) {
myArray.push(Math.pow(2, i));
}
for (var j = 0; j <= 31; j++) {
document.write("2" + myArray[j].toString().sup() + " = " + n + "<br />");
}
I want to create a pyramid number structure. Can anyone explain me how?
for (i = 1; i <= 5; i++) {
var k = ' ';
var myspace = '';
for (j = 0; j < i - 0; j++) {
k += i;
myspace += ' ';
}
console.log(myspace + k);
}
I want make it like this:
1
2 2
3 3 3
4 4 4 4
Try below code:
function createPyramid(rows) {
for (var i = 0; i < rows; i++) {
var output = '';
for (var j = 0; j < rows - i; j++) output += ' ';
for (var k = 0; k <= i; k++) output += (i + 1) + ' ';
console.log(output);
}
}
createPyramid(4);
Try below method.
var a;
var n = 5;
for (var i = 1; i <= n; i++) {
for (var j = 1; j <= i; j++) {
document.write(j + " ");
}
document.write("<br />");
}
I'm trying to create a simple algorithm that builds an array with a dynamic length.
Then, it will, one by one, replace an item, and then two, then three and so on until the only items left are the first and last.
like this:
12345
1*345 // it never touches the first
12*45
123*5 // it doesn't ever touch the last item
1**45
12**5
1***5 // done, nowhere else to go
I put together a simple demo to show what I'm trying to do.
var length = 6,
array = [],
log = document.getElementById("log"),
edited,
j,
i;
for (i = 1; i <= length; i++) {
array.push(i);
}
log.innerHTML += array.join(" ") + "<br><br>";
for (i = 1; i < (length - 1); i++) {
edited = array.concat();
for (j = i; j < (length - 1); j++) {
edited[j] = "*";
log.innerHTML += edited.join(" ") + "<br>";
}
log.innerHTML += "<br>";
}
Fiddle
It works fine, the only problem is it's out of order.
Right now it seems to only iterate by number of asterisks, then by index. I need it to do the opposite.
// it does this
12345
1*345
1**45
1***5
12*45
12**5
123*5 // out of order
If someone could help that would be great because I am really at a loss!
This should get it done.
var a = 6, // array length
b = [], // array
log = document.getElementById("log"),
c,
d,
e;
for (c = 1; c <= a; c++) {
b.push(c);
}
log.innerHTML += b.join(" ") + "<br><br>";
//the size of the asterisk chunk
for(i = 1; i < b.length - 1; i ++)
{
//position to start asterisk chunk
for(j = 1; j < b.length - i; j ++)
{
var tempArr = b.concat();
//the position inside of the asterisk chunk
for(k = 0; k < i; k ++)
{
tempArr[k + j] = "*";
}
log.innerHTML += tempArr.join(" ") + "<br>";
}
}
JSFiddle
This seems to work well:
str = "1234567"
len = str.length;
for(var stars = 1; stars < len - 1; stars++) {
for(var pos = 1; pos < len - stars; pos++) {
var s = str.substr(0, pos)
+ new Array(stars + 1).join("*")
+ str.substr(pos + stars);
document.write(s + "<br>");
}
}
so this is my problem:
i have 2 Strings "myTestTomorrow" and "ThisIsmyTesttoday". I need to get the part which both strings contain, in this case "myTest". How can i do this?
You can do this with two for loops and indexOf, like this
var text1 = "myTestTomorrow", text2 = "ThisIsmyTesttoday";
outer: for (var i = text1.length; i >= 0; i -= 1) {
for (var j = 0; j + i < text1.length; j += 1) {
if (text2.indexOf(text1.substr(j, i)) !== -1) {
console.log("Result is '" + text1.substr(j, i) + "'");
break outer;
}
}
}
Output
Result is 'myTest'