Make integer in For Loop Superscript - javascript

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 />");
}

Related

Why the Double mirror pascal star pattern is not printed?

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

Print pyramid number using JavaScript

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 />");
}

Looping javascript multi array

var size = ['s','m'];
var color = ['red','blue','black'];
var material = ['cotton','linen'];
i want result like :
array("s,red,cotton","s,red,linen","s,blue,cotton","s,blue,linen","s,black,cotton","s,black,linen");
array("m,red,cotton","m,red,linen","m,blue,cotton","m,blue,linen","m,black,cotton","m,black,linen");
would you like to help me please use javascript or jquery. Thank you :)
Three loops for each array. Just loop through every array, and append to new array.
var size = ['s','m'];
var color = ['red','blue','black'];
var material = ['cotton','linen'];
var arrayMaterials = []
for (var i = 0; i < size.length; i++) {
for (var j = 0; j < color.length; j++) {
for (var k = 0; k < material.length; k++) {
arrayMaterials.push(size[i] + "," + color[j] + "," + material[k]);
}
}
}
console.log(arrayMaterials);
As said in Comment you need 3 loops
var size = ['s','m'];
var color = ['red','blue','black'];
var material = ['cotton','linen'];
for (var a = 0; a < size.length; a++) {
for (var b = 0; b < color.length; b++) {
for (var c = 0; c < material.length; c++) {
console.log(size[a] + " , " + color[b] + " , " + material[c]);
}
}
}

This simple mergeSort code is giving an incorrect answer. Can someone find the bug?

The problem seems to be that the mergeSort partitions [300,200, 100] into [300,200] and [100]. Then it successfully merges and sorts [300,200] into [200,300]. The problem occurs now: instead of merging [200,300] with [100], the algorithm runs a sort procedure between [300] with [100]. I have a suspicion that the problem is because of Javascript's closure, because of which the value of j gets interpreted differently at some point. Can someone help me?
function mergeSort(A,start,end){
console.log("Sorting " + A + " between " + start + " and " + end)
if (start==end){
console.log("Reached singleton element: " + A[start])
return;
}
j = Math.floor((end+start)/2);
mergeSort(A,start,j);
console.log("Sorted " + A + " between " + start + " and " + j + ". Now sorting between " + (j+1) + " and " + end)
mergeSort(A,(j+1),end);
merge(A,start,(j+1),end);
return A
}
function merge(A,s,p,e){
var i = s;
var j = p;
var finalArray = [];
while(i < p && j < e+1){
if (A[i] <= A[j]){
finalArray[i+j-s-p] = A[i];
i++
}
else if (A[j] < A[i]){
finalArray[i+j-s-p] = A[j];
j++
}
}
if (i == p){
while (j < e+1 ){
finalArray[i-s+j-p] = A[j];
j++
}
}
if (j == e+1){
while (i < p ){
finalArray[i-s +j-p] = A[i];
i++
}
}
for(var q = s; q <e+1;q++){
A[q] = finalArray[q-s]
}
}
A = [300,200, 100] // Gives [ 200, 100, 300 ]
mergeSort(A, 0, (A.length-1));
It is a scoping issue. Changing the declaration of j fixes it:
let j = Math.floor((end+start)/2);
I refactored the merge function. Only reason I didn't rename the variables is that I'm on mobile. Someone with more js knowledge probably has more improvements:
function merge(A,s,p,e) {
let i = s;
let j = p;
let finalArray = [];
while(i < p && j <= e) {
if (A[i] <= A[j]) {
finalArray.push(A[i])
i++
}
else {
finalArray.push(A[j])
j++
}
}
while (j <= e) {
finalArray.push(A[j]);
j++
}
while (i < p) {
finalArray.push(A[i]);
i++
}
for(let q = s; q <= e; q++) {
A[q] = finalArray[q-s]
}
}

Quickest way to achieve this sequence?

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

Categories