Quickest way to achieve this sequence? - javascript

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

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 all possibilities by rotating a string in Javascript

How to rotate a string in javascript and print the rotated versions of string without using any javascript functions, only for loops.
Given a string:
"hell"
Output:
"lhel", "llhe", "ellh", "hell"
I have tried but not succeded
var str1 = "hell";
let i = 0;
let len = str1.length - 1;
let temp;
for (let j = 0; j < len+1; j++) {
temp = str1[len]
while (i < len) {
console.log(str1[i]);
temp += str1[i];
i++;
}
console.log(temp);
//console.log(typeof temp, typeof str1)
str1 = temp;
}
You are almost there ! There is one thing missing, i should be reset at each iteration of the for loop, otherwise, the while (i < len) will be "played" only once :
var str1 = "hell";
let len = str1.length - 1;
let temp;
for (let j = 0; j < len+1; j++) {
let i = 0; // <-------------------- notice this
temp = str1[len]
while (i < len) {
//console.log(str1[i]);
temp += str1[i];
i++;
}
console.log(temp);
//console.log(typeof temp, typeof str1)
str1 = temp;
}
You could take a nested loop and get the characters at the position of i and j and take the reminder operator % for preventing characters outside of the string.
var string = "hell",
i, j,
temp;
for (i = 0; i < string.length; i++) {
temp = '';
for (j = 1; j <= string.length; j++) temp += string[(i + j) % string.length];
console.log(temp);
}
You can try this method. Basically you have two loops the first loop with (i) is for the possibilities the second one is for the shifting
var strValue = "hell";
var temp;
for(var i = 0; i < strValue.length; i++){
temp = "";
for(var j = 1; j < strValue.length; j++){
temp += strValue[j];
}
temp += strValue[0]
strValue = temp;
console.log(strValue)
}
In first loop add all symbols which indexes are greater then amount of shift steps (i in this case).
And add rest symbols after it the second loop.
const str = 'hello';
for (let i = 0; i < str.length; i++) {
let shifted = '';
for (let j = i; j < str.length; j++) {
shifted += str[j];
}
for (let j = 0; j < i; j++) {
shifted += str[j];
}
console.log(shifted);
}
i know this has already been answered so.. this is how i'd do it.
maybe you can learn from it.
const str = "hell";
// this loop will set the offset. so if it's 1, "hell" will become "ellh"
for (let offset = 0; offset < str.length; offset++) {
// this will contain the final string
let output = "";
// here we iterate through all the characters
for (let index = 0; index < str.length; index++) {
// and use modulo to switch 5 to 1 (in case length is 4)
output += str[(index + offset) % str.length];
}
// there we go
console.log(output);
}
let str = 'hell';
for(let i=0;i<str.length;i++){
str = str.substring(1,str.length) + str[0];
console.log(str);
}

Where i make mistake here?

Hello everyone i have a problem with my code and i'm not sure how to do this , i need to write code that draw this in console:
Draw '*' in every even number
For that i need to use nested loops.
So far i have only this:
var n = 5;
var stars = '';
for (var i = 1; i <= n; i++) {
var starsline = '';
for (var j = 1; j <= n; j++) {
console.log(i + j);
}
if ( i % 2 === 0){
starsline += '2';
} else {
starsline += '1'
}
stars += starsline;
}
console.log(stars);
This numbers 2 and 1 are only to check if the number is even or odd.
Just a few things:
1) you got some weird bracket here:
/*}*/ if ( i % 2 === 0){
which causes a syntax error later on.
2) you actually log the right thing:
console.log(i + j)
but you dont use it. Just put that into your condition:
if((i + j) % 2 === 0)
and you are done :)
let size = 5, stars = "";
for (var row = 1; row <= size; row++) {
var starsline = "";
for (var col = 1; col <= size; col++){
if ((row + col) % 2 === 0){
starsline += '*';
} else {
starsline += ' ';
}
stars += starsline + "\n";
}
console.log(stars);
I think what you tried to do is something like this:
var n = 5;
var stars = '';
for (var i = 1; i <= n; i++) {
var starsline = '';
for (var j = 1; j <= n; j++){
if ( (i + j) % 2 === 0){
// used three spaces for consistency in the drawing
starsline += ' ';
} else {
starsline += ' * '
}
}
stars += starsline + '\n';
}
console.log(stars);
Try this:
var n = 5;
var stars = '';
for (var i = 1; i <= n; i++)
{
var starsline = '';//<-- reset the value of line
if ( i % 2 === 0)//<--this identifies which line will the stars be created
{
starsline += '* * *';//<--creating the stars on each line
}
else
{
starsline += ' * * ';//<--creating the stars on each line
}
stars += starsline+'\n';//<-- '\n' add line breaks for each lines
}
console.log(stars);//<-- print the stars

Array loop in javascript

I try to develop a simple program that prints all numbers in between 1 and 100 that divide by 3 without any residual and calculate the total sum
I did it with for loop:
var sum = 0;
for (var i = 3; i <= 100; i = i + 3) {
document.write("<br/>" + i);
sum = sum + i;
}
document.write("<br/>sum = " + sum); //1683
But I failed when I wanted to do it with array:
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
Use it like this,
Array indexes should start from 0, that is why I have introduced another variable j=0
var numbers = [];
var sum = 0;
for (var i = 0, j = 0; i <= 100; i = i + 3, ++j) {
numbers[j] = i;
}
Update
First Issue:
In your code, ie. below code of yours,
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
In the first iteration,
i = 0;
numbers[0-1] = i // i.e numbers[-1] = 0;
and in your second loop, you are starting the index from 0
for (var index = 0; index < 100; index++) {
Second issue:
Also, if you don't use a sequential counter to fill the Array, you will end with undefined values for the ones you did not fill.
If you notice, the output after the loop, it says numbers.length = 99 which is wrong it will not have that many items in it.
Third Issue:
In below code, even if you introduce a sequential counter, this is still wrong
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
because i should start with 3 instead of 0, otherwise you will end up with 34 elements in the array because numbers[0] will be 0;
Fourth Issue:
In this code,
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
You don't actually have to loop it till 100, you already have the numbers array filled, so you just need to use numbers.length, like this
var len = numbers.length;
for (var index = 0; index < len; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
A better way to write this
var numbers = [];
for (var i = 3, j=0; i <= 100; i = i + 3, j++) {
numbers[j] = i;
}
var sum = numbers.reduce((a, b) => a+b);
console.log(sum);
The line var sum = numbers.reduce((a, b) => a+b); uses Array.reduce() method.
adding number to array
var numbers = [];
for(var i = 3; i <= 100; i = i +3){
numbers.push(i);
}
summation and printing values
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
document.write("<br/>" + numbers[i]);
sum = sum + numbers[i];
}
document.write("<br/>sum = " + sum); //1683
There are few issues in your code.
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
1: array is 0 based. so first insertion into the array goes for a toss.
2: the number array created will have skipping index like 3, 6 ,9
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
3: Here you are iterating index till 100 , you should iterate it till the length of the numbers array only.
when index is 1,2
number[index] will become undefined.
4: sum = sum + i (i ??????)
You should try like this or you can also use push()
var numbers = [];
var sum = 0;
for (var i = 0,j=0; i <= 100; i = i + 3, j= j+1) {
numbers[j] = i; // array is 0 based.
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + numbers[index];
}
document.write("<br/>sum = " + sum);
Indexes in an array begin with zero.
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i; // In the first iteration, there will be numbers[-1] = i;
}
You have several issues i suppose.
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers.push(i);
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
Also for array you can use:
for (var i in array) {
console.log(array[i]);
}
And I'm pretty sure, that array of number sequence is absolutely useless, if there is no other information in it.
Try this
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers[(i-3)/3] = i;
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + numbers[index];
}
document.write("<br/>sum = " + sum);
Here is the fiddle i tried
https://jsfiddle.net/4ncgnd7c/
This should work using a single loop
var numbers = [];
var sum = 0;
for (var i = 3; i <= 100; i = i + 3) {
numbers[i] = i;
document.write("<br/>" + i);
sum = sum + i;
}
document.write("<br/>sum = " + sum);

Finding the rank of the Given string in list of all possible permutations with Duplicates

I was trying to find the Rank of the given string in the list of permutations and was hoping someone can find the bug.
function permute() {
var W = $('input').val(),
C = [];
for (var i = 0; i < 26; i++) C[i] = 0;
var rank = 1;
for (var i = 0; i < W.length; i++) {
C[W.charCodeAt(i) - 'a'.charCodeAt(0)]++;
}
var repeated= 1;
for (var i = 0; i < C.length; i++) {
if(C[i] > 0) {
repeated *= fact(C[i]);
}
}
if (W !== '') {
for (var i = 0; i < W.length; i++) {
//How many characters which are not used, that come before current character
var count = 0;
for (var j = 0; j < 26; j++) {
if (j == (W.charCodeAt(i) - 'a'.charCodeAt(0))) break;
if (C[j] > 0) count++;
}
C[W.charCodeAt(i) - 'a'.charCodeAt(0)] = 0;
rank += ( count * fact(W.length - i - 1) );
}
rank = rank/ repeated;
}
var pp = 'Rank of :: ' + W + ' -- ' + rank;
$('div').append('<p>' + pp + '</p>');
}
function fact(n) {
if (n == 0 || n == 1) return 1;
else return fact(n - 1) * n;
}
$('button').click(permute);
Check Fiddle
A use case for this might be
bookkeeper is supposed to give a rank of 10743.
Here's the demo:
For each position check how many characters left have duplicates, and use the logic that if you need to permute n things and if 'a' things are similar the number of permutations is n!/a!

Categories