Nested loops counting upwards and downwards with stars - javascript

I'm trying to solve task with the usage of nested loops. My code below
var n = 5;
var lineOfStars = '';
for (var i = 1; i <= 10; i++) {
for (var j = 1; j <= n; j++) {
if (j <= i) { // 1 <= 5 - 1 - 1 (3)
lineOfStars += ' * ';
} else {
lineOfStars += ' ' + j + ' ';
}
}
lineOfStars += '\n';
}
console.log(lineOfStars);
The result that im looking for is (i want to do it only with nested loops):
* 2 3 4 5
* * 3 4 5
* * * 4 5
* * * * 5
* * * * *
* * * * *
* * * * 5
* * * 4 5
* * 3 4 5
* 2 3 4 5
The code that ive shown does only half of the job. I need help. Thanks in advance

This is closer to what you are wanting, still working on it.
var n = 5;
var lineOfStars = '';
let i, j
for (i = 1; i <= 5; i++) {
for (j = 1; j <= n; j++) {
if (j <= i) {
lineOfStars += ' * ';
} else {
lineOfStars += ' ' + j + ' ';
}
}
lineOfStars += '\n';
}
console.log(lineOfStars)
for (j = 5; j <= 5; j--) {
if (j == 0) break;
for (i = 5; i <= n; i--) {
if (0 == 0) break;
if (i <= j) {
lineOfStars += ' ' + i + ' ';
} else {
lineOfStars += ' * ';
}
}
lineOfStars += '\n';
}
let rev = lineOfStars.split('\n').reverse()
for (let z = 1; z <= rev.length - 1; z++) {
if (rev[z].length != 0) {
console.log(rev[z])
lineOfStars += rev[z]
lineOfStars += '\n';
}
}
console.log(lineOfStars)

Related

How can pre-define a length of maze path when generating maze

I am trying create a maze of words with pre-defined length of found path, But have no clue about what algorithm would make it possible.
For ex: I want the length from cells start 1 to end [2] should be 11( the length of "onetwothree").
Here is the current code I am using to generate the maze:
var demotext = "onetwothree";
var widthmaze = (demotext.length + 5) / 2 + 1;
var heightmaze = (demotext.length + 5) / 2 - 1;
document.getElementById('out').innerHTML = display(maze(widthmaze, heightmaze));
function maze(x, y) {
var n = x * y - 1;
if (n < 0) {
alert("illegal maze dimensions");
return;
}
var horiz = [];
for (var j = 0; j < x + 1; j++) horiz[j] = [],
verti = [];
for (var j = 0; j < x + 1; j++) verti[j] = [],
here = [Math.floor(Math.random() * x), Math.floor(Math.random() * y)],
path = [here],
unvisited = [];
for (var j = 0; j < x + 2; j++) {
unvisited[j] = [];
for (var k = 0; k < y + 1; k++)
unvisited[j].push(j > 0 && j < x + 1 && k > 0 && (j != here[0] + 1 || k != here[1] + 1));
}
while (0 < n) {
var potential = [
[here[0] + 1, here[1]],
[here[0], here[1] + 1],
[here[0] - 1, here[1]],
[here[0], here[1] - 1]
];
var neighbors = [];
for (var j = 0; j < 4; j++)
if (unvisited[potential[j][0] + 1][potential[j][1] + 1])
neighbors.push(potential[j]);
if (neighbors.length) {
n = n - 1;
next = neighbors[Math.floor(Math.random() * neighbors.length)];
unvisited[next[0] + 1][next[1] + 1] = false;
if (next[0] == here[0])
horiz[next[0]][(next[1] + here[1] - 1) / 2] = true;
else
verti[(next[0] + here[0] - 1) / 2][next[1]] = true;
path.push(here = next);
} else
here = path.pop();
}
return {
x: x,
y: y,
horiz: horiz,
verti: verti
};
}
function display(m) {
var text = [];
for (var j = 0; j < m.x * 2 + 1; j++) {
var line = [];
if (0 == j % 2)
for (var k = 0; k < m.y * 4 + 1; k++)
if (0 == k % 4)
line[k] = '+';
else
if (j > 0 && m.verti[j / 2 - 1][Math.floor(k / 4)])
line[k] = ' ';
else
line[k] = '-';
else
for (var k = 0; k < m.y * 4 + 1; k++)
if (0 == k % 4)
if (k > 0 && m.horiz[(j - 1) / 2][k / 4 - 1])
line[k] = ' ';
else
line[k] = '|';
else
if (2 == k % 4)
line[k] = demotext[Math.floor(Math.random() * demotext.length)];
else
line[k] = ' ';
if (0 == j) {line[1] = line[3] = ' '; line[2] = '1'};
if (m.x * 2 - 1 == j) line[4 * m.y] = '2';
text.push(line.join('') + '\r\n');
}
return text.join('');
}
<pre id="out"></pre>
Moving start and end point to make the path length match with text maybe the solution but I do not know how to implement it. Any help would be great !
Ps: I would like the result can be like this:

What is the source for printing the diamond in JavaScript?

I want to create a source that can input odd numbers into the user and print out diamond-shaped * accordingly
example)
enter an odd number : 5
*
***
*****
***
*
If (example), input = 5, you just must learn, how to count:
(spaces)(stars)
2 1
1 3
0 5
1 3
2 1
let input = 7; // Number( prompt("Enter any odd integer") );
let space = " ";
/*****/
let breakPoint = Math.floor(input / 2);
let str = "", iter = 0, i = 0;
while( iter < input ) {
str += (
space.repeat( (breakPoint - i) ) +
"*".repeat( 2 * i + 1 ) +
"<br>"
);
(iter < breakPoint) ? (i++) : (i--);
iter++;
}
document.body.innerHTML = str;
body { font-family: 'Lucida Console'; } /* Monospaced font required */
One loop might be confusing. I came to it after trying two separate loops:
let input = 7;
let space = " ";
/***/
let breakPoint = Math.ceil(input / 2);
let str = "";
for( let i = 0; i < breakPoint - 1; i++ ) {
str += (
space.repeat( (breakPoint - i) ) +
"*".repeat( 2 * i + 1 ) +
"\n"
);
}
for( let i = breakPoint - 1; i >= 0; i-- ) {
str += (
space.repeat( (breakPoint - i) ) +
"*".repeat( 2 * i + 1 ) +
"\n"
);
}
console.log( str );
Or, KISS (Keep It Simple Stupid):
let input = 7;
let space = " ";
/***/
let breakPoint = Math.floor(input / 2); // 3
let str = "";
let spaces = breakPoint; // (3)
let stars = 1;
for( let i = 0; i < breakPoint; i++ ) {
str += (
space.repeat(spaces) +
"*".repeat(stars) +
"\n"
);
spaces -= 1;
stars += 2;
}
for( let i = breakPoint; i >= 0; i-- ) {
str += (
space.repeat(spaces) +
"*".repeat(stars) +
"\n"
);
spaces += 1;
stars -= 2;
}
console.log( str );
"use strict";
function diamondPattern() {
let string = "";
for (let i = 1; i <= 5; i++) {
for (let j = 5; j > i; j--) {
string += " ";
}
for (let k = 0; k < i * 2 - 1; k++) {
string += "*";
}
string += "\n";
}
for (let i = 1; i <= 4; i++) {
for (let j = 0; j < i; j++) {
string += " ";
}
for (let k = (5 - i) * 2 - 1; k > 0; k--) {
string += "*";
}
string += "\n";
}
return string;
}
console.log(diamondPattern());

Javascript Memoization in Browser Not Seeing Speed Up

I am attempting to memoize a function in javascript, to be run in browser, client side. Writing this function in R (the language I am most comfortable using). In R, I see significant benefits from using memoization (4 minutes run time to 0.02 seconds for P_n(7/10, 20, 15, 6, 1) ). When I rewrite the function in javascript, I see almost no benefit. What is the problem with my javascript code (or am I going about this the wrong way entirely)?
Below are the memoized functions in R and javascript respectively. The R function (first of the two) runs very fast compared to the naive recursion, while javascript essentially sees no difference. Some amount of memoization is happening, however, because if I run the exact same function call twice, i.e. P_memo(7/10, 20, 15, 6, 1) and then P_memo(7/10, 20, 15, 6, 1) again, the second call takes 0 time. The first call should be dramatically quicker due to re-use of intermediate calls in the recursion.
P_n <- (function() {
# Memoization handled through the use of cache
cache <- NULL
cache_reset <- function() {
cache <<- new.env(TRUE, emptyenv())
}
cache_set <- function(key, value) {
assign(key, value, envir = cache)
}
cache_get <- function(key) {
get(key, envir = cache, inherits = FALSE)
}
cache_has_key <- function(key) {
exists(key, envir = cache, inherits = FALSE)
}
# Initialize the cache
cache_reset()
# This is the function that gets returned by the anonymous function and
# becomes P_n
function(rho, n, i, k, s) {
nc <- paste(rho, n, i, k, s)
# Handle "vectors" by element
if(length(n) > 1){
return(lapply(n, function(n) sapply(n, P_n, rho = rho, i = 1:(n+k), k = k, s = s)))
}
if (length(i) > 1) {
return(sapply(i, P_n, rho = rho, n = n, k = k, s = s))
}
# Cached cases
if (cache_has_key(nc))
return(cache_get(nc))
# Everything else
#proposition 1
if(i == (n+k)){
#print('Proposition 1')
if(k >= s){
return((rho / (rho + 1))^n)
}else if( (k+n) <= s){
product_iter = 1
for(j in 1:n){
product_iter = product_iter * ( rho + (k + j - 1)/s )
}
out = rho^n / product_iter
cache_set(nc, out)
return(out)
}else if( k < s & s < (k + n)){
product_iter2 = 1
for(j in 1:(s-k)){
product_iter2 = product_iter2 * ( rho + (k + j - 1)/s )
}
product_denom = ((rho + 1)^(n-s+k)) * product_iter2
out = rho^n / product_denom
cache_set(nc, out)
return(out)
}
}
#proposition 2
else if(k == 0 & n == i){
#print('Proposition 2')
if(n <= s){
product_iter11 = 1
for(j in 1:n){
product_iter11 = product_iter11 * (rho + (j - 1)/s)
}
return(rho^n / product_iter11)
}else if(n > s){
product_iter12 = 1
for(j in 1:s){
product_iter12 = product_iter12 * ( rho + (j - 1)/s )
}
product_denom12 = ((rho + 1)^(n-s)) * product_iter12
out = rho^n / product_denom12
cache_set(nc, out)
return(out)
}
}
#if i = 1
else if(i == 1){
upsum = 0
for(j in 2:(n + k)){
upsum = upsum + P_n(rho, n, j, k, s)
}
out = 1 - upsum
cache_set(nc, out)
return(out)
}
#proposition 3
else if(n == 1 & 2 <= i & i <= k){
#print('Proposition 3')
if(k <= s){
begin = rho / (rho + (i - 1)/s)
product_iter13 = 1
for(j in 1:(k-i+1)){
product_iter13 = product_iter13 * (1 - rho / (rho + (k - j + 1)/s) )
}
out = begin * product_iter13
cache_set(nc, out)
return(out)
}else if(k > s & i > s){
out = rho / (rho+1)^(k-i+2)
cache_set(nc, out)
return(out)
}else if(i <= s & s <= k){
begin2 = rho / (( rho + 1 )^(k - s + 1) * ( rho + (i - 1)/s))
product_iter14 = 1
for(j in 1:(s-i)){
product_iter14 = product_iter14 * (1 - rho / (rho + (s - j)/s) )
}
out = begin2 * product_iter14
cache_set(nc, out)
return(out)
}
}
#proposition 4
else if( n >= 2 & 2 <= i & i <= (k + n - 1)){
#print('Proposition 4')
if(i>s){
begin11 = rho/(rho+1)
product_iter21 = 0
for(j in (i-1):(k+n-1)){
product_iter21 = product_iter21 + (1 / (rho+1))^(j-i+1) * P_n(rho, n-1, j, k, s)
}
out = begin11 * product_iter21
cache_set(nc, out)
return(out)
}else if(i <= s){
begin12 = rho / (rho + (i-1)/s)
summer1 = 0
for(j in (i-1):(s-1)){
product_iter22 = 1
for(h in 1:(j-i+1)){
product_iter22 = product_iter22 * (1 - rho / (rho + (j - h + 1) / s))
}
summer1 = summer1 + product_iter22 * P_n(rho, n-1, j, k, s)
}
product_iter23 = 1
for(h in 1:(s-i)){
product_iter23 = product_iter23 * (1 - rho / (rho + (s-h) / s))
}
summer2 = 0
for(j in s:(k+n-1)){
summer2 = summer2 + ((1 / (rho + 1))^(j-s+1) * P_n(rho, n-1, j, k, s))
}
bottom = product_iter23 * summer2
inner = summer1 + bottom
out = begin12 * inner
cache_set(nc, out)
return(out)
}
}
#check if missed all propositions
else{
stop("No proposition detected")
}
}
})()
var P_memo = (function() {
var memo = {};
var slice = Array.prototype.slice;
function f(rho, n, i, k, s){
var args = slice.call(arguments);
var value;
if (args in memo) {
return(memo[args]);
}else{
// NOTES ON THE UNITS OF INPUTS
//rho: ratio of lambda / tau
// n: arrival of nth customer
// i: are i customers in queue
// k : number of customers at t = 0
// s: machines in use
//proposition 1
if(i == (n+k)){
//print('Proposition 1')
if(k >= s){
return(Math.pow(rho / (rho + 1), n));
}else if( (k+n) <= s){
var product_iter = 1;
for(var j=1; j<= n; j++){
product_iter = product_iter * ( rho + (k + j - 1)/s );
}
return(Math.pow(rho, n) / product_iter);
}else if( k < s && s < (k + n)){
var product_iter2 = 1;
for(var j=1; j<= s-k; j++){
product_iter2 = product_iter2 * ( rho + (k + j - 1)/s );
}
product_denom = Math.pow((rho + 1), (n-s+k)) * product_iter2;
return(Math.pow(rho, n) / product_denom);
}
}
//proposition 2
else if(k == 0 && n == i){
if(n <= s){
var product_iter11 = 1;
for(var j=1; j<= n; j++){
product_iter11 = product_iter11 * (rho + (j - 1)/s);
}
return(Math.pow(rho, n) / product_iter11);
}else if(n > s){
var product_iter12 = 1;
for(var j=1; j<= s; j++){
product_iter12 = product_iter12 * ( rho + (j - 1)/s );
}
product_denom12 = Math.pow((rho + 1), (n-s)) * product_iter12;
return(Math.pow(rho, n) / product_denom12);
}
}
//if i = 1
else if(i == 1){
var upsum = 0;
for(var j=2; j<= (n+k); j++){
upsum = upsum + f(rho, n, j, k, s);
}
return(1 - upsum);
}
//proposition 3
else if(n == 1 && 2 <= i && i <= k){
if(k <= s){
begin = rho / (rho + (i - 1)/s);
var product_iter13 = 1;
for(var j=1; j<= (k-i+1); j++){
product_iter13 = product_iter13 * (1 - rho / (rho + (k - j + 1)/s) );
}
return(begin * product_iter13);
}else if(k > s && i > s){
return(rho / Math.pow((rho+1), (k-i+2)));
}else if(i <= s && s <= k){
begin2 = rho / (Math.pow( (rho + 1), (k - s + 1)) * ( rho + (i - 1)/s));
var product_iter14 = 1;
for(var j=1; j<= (s-i); j++){
product_iter14 = product_iter14 * (1 - rho / (rho + (s - j)/s) );
}
return(begin2 * product_iter14);
}
}
//proposition 4
else if( n >= 2 && 2 <= i && i <= (k + n - 1)){
if(i>s){
begin11 = rho/(rho+1);
var product_iter21 = 0;
for(var j=(i-1); j<= (k+n-1); j++){
product_iter21 = product_iter21 + Math.pow((1 / (rho+1)),(j-i+1)) * f(rho, n-1, j, k, s);
}
return(begin11 * product_iter21);
}else if(i <= s){
begin12 = rho / (rho + (i-1)/s);
var summer1 = 0;
for(var j=(i-1); j<= (s-1); j++){
var product_iter22 = 1;
for(var h=1; h<=(j-1+1); h++){
product_iter22 = product_iter22 * (1 - rho / (rho + (j - h + 1) / s));
}
summer1 = summer1 + product_iter22 * f(rho, n-1, j, k, s);
}
var product_iter23 = 1;
for(var h=1; h<=(s-i); h++){
product_iter23 = product_iter23 * (1 - rho / (rho + (s-h) / s));
}
var summer2 = 0;
for(var j=s; j<= (k+n-1); j++){
summer2 = summer2 + (Math.pow((1 / (rho + 1)), (j-s+1)) * f(rho, n-1, j, k, s)) ;
}
bottom = product_iter23 * summer2;
inner = summer1 + bottom;
return(begin12 * inner);
}
}
}
}
//Closure of f(), self-executing anonymous function
return f;
})();
Your memoization has two flaws:
(1) You never add results to memo.
(2) args in memo casts args to a string. That will work for an array of numbers, but it might fail for other inputs.
I'd write a generic version of memo like this:
const memo = fn => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
if(key in memo) return memo[key];
return memo[key] = fn(...args);
};
};
const memoizedF = memo(f);

JavaScript- get sum of values inside a for loop

I'm trying to sum all the variables,
as many times as they appear in the loop,
that is- for example if hitpoints appears
3 times(as in my code) sum -12 + -12 + -12;
And then at the end I need a final result - a
sum of all of the variable values as many
times as they appear.
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
console.log( i + "-" + hitpoints);
} else if ((i % 3 === 0) && (i% 5 ===0)) {
console.log( i + "-" + pointsx);
} else if (i %3 ===0) {
console.log ( i + "-" + points3);
} else if (i%5 ===0) {
console.log( i + "-" + points5);
} else {
console.log( i + "-" + points1);
}
}
}
calculate(30);
I assume you want the sum of the points.
Declare a variable sum and keep incrementing
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
var sum=0;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
sum += hitpoints;
} else if ((i % 3 === 0) && (i% 5 ===0)) {
sum += pointsx;
} else if (i %3 ===0) {
sum += points3;
} else if(i%5 ===0) {
sum += points5;
} else {
sum += points1;
}
}
console.log(sum)
}
calculate(30);

Pyramide of Stars Javascript

How could I create Pyramide of Stars that increase every row by 2 like that:
*
* * *
* * * * *
* * * * * * *
My currently code:
for (var x = 0; x < 5; x++) {
for (var y = 0; y <= x; y = y + 1) {
document.write(" * ");
}
document.write("<br>");
}
It's possible just to increment in your loop by 2.
for(var i = 1; i < 20; i += 2) {
console.log( Array(i).fill('*').join(' ') );
}
Otherwise just multiply inside your loop
for(var i = 0; i < 10; i++) {
console.log( Array(i*2 + 1).fill('*').join(' ') );
}
You may also need to polyfill Array.fill depending on your target.
Other answers recreate the entire row each time. This solution just extends the row each time to have another star.
function pyramid(n) {
let result = '', str = '', add = '*';
for (var i = 0; i < n; i++) {
str += add;
add = ' *';
if (!(i % 2)) result += str + '\n';
}
return result;
}
console.log(pyramid(5));
You can do like this.
function generate() {
var totalNumberofRows = 5;
var output="";
for (var i = 1; i <= totalNumberofRows; i++) {
for (var j = 1; j <= i; j++) {
if(j==1)
output+="*";
else
output+=" "+ "*" + " "+ "*";
}
console.log(output);
output="";
}
}
generate()
Hope so this is also beneficial for you....
$(document).ready(function () {
var NumberofRows = 5,arr;
for (var i = 1; i <= NumberofRows; i++) {
pyramid = [];
for (var j = 1; j <= i; j++) {
pyramid.push('*');
}
console.log(pyramid.join(" ") + "\n");
}
});
``

Categories

Resources