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");
}
});
``
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have tried the code below but it's output is not proper!
for(i=5;i>=1;i--) {
for(j=i;j>=1;j--){
console.log(j);
}
console.log("\n");
}
for(var i=1; i<=4; i++){
console.log("* ".repeat(i));
}
/*
Output is:
"*"
"* *"
"* * *"
"* * * *"
*/
for (var line = "#"; line.length < 8; line += "#")
console.log(line);
<html>
<head>
<script type="text/javascript">
var i,j;
for(i=1; i <= 5; i++)
{
for(j=1; j<=i; j++)
{
document.write('*');
}
document.write('<br />');
}
</script>
</head>
<body>
</body>
</html>
/** --------------
*
**
***
****
*****
******
*******
********
*********
----------------*/
let y = 10;
let x = 10;
let str = "";
for(let i = 1; i < y; i++ ){
for(let j = 1; j < x; j++){
if(i + j >= y){
str = str.concat("*");
}else{
str = str.concat(" ")
}
}
str = str.concat("\n")
}
console.log(str)
/**_______________________
*********
********
*******
******
*****
****
***
**
*
_______________________*/
let str2 = "";
for(let i = 1; i < y; i++ ){
for(let j = 1; j < x; j++){
if(i <= j ){
str2 = str2.concat("*");
}else{
str2 = str2.concat(" ")
}
}
str2 = str2.concat("\n")
}
console.log(str2)
/**----------------------
*
**
***
****
*****
******
*******
********
-------------------------*/
let str3 = "";
for(let i = 1; i < y; i++ ){
for(let j = 1; j < x; j++){
if(i >= j ){
str3 = str3.concat("*");
}
}
str3 = str3.concat("\n")
}
console.log(str3)
/**-------------------------
*********
********
*******
******
*****
****
***
**
*
---------------------------*/
let str4 = "";
for(let i = 1; i < y; i++ ){
for(let j = 1; j < x; j++){
if( j >= i ){
str4 = str4.concat("*");
}
}
str4 = str4.concat("\n")
}
console.log(str4)
/**--------------------
Diamond of Asterisks
*
***
*****
*******
*********
*******
*****
***
*
---------------------*/
let str5 = "";
for(let i = 1; i < y; i++ ){
for(let j = 1; j < x; j++){
if(i <= y / 2 && j >= (y / 2) - (i - 1) && j <= (y / 2) + (i - 1) ){
str5 = str5.concat("*");
}else if(i >= y / 2
&& j > ((y / 2) - i) * (-1)
&& j < (y - ((y / 2) - i) * (-1))){
str5 = str5.concat("*");
}
else {
str5 = str5.concat(" ");
}
}
str5 = str5.concat("\n");
}
console.log(str5)
This is the simplest solution which I came across using only one for loop.
var a = '';
var n = 5;
var m = (n-1);
for(i=1; i <= n; i++)
{
a = a.trim();
a = ' '.repeat(m) + a + (i > 1 ? ' ' : '') + '*';
console.log(a);
m--;
}
Output:
/**------------------------
*
* *
* * *
* * * *
* * * * *
---------------------------*/
for (var i = 7; i >= 1; i--) {
var str = "";
for (var j = i; j <= 7; j++) {
str += "*";
}
console.log(str);
}
// This is example
// You can do this with any string and without using the function.
It's very simple, Try this code as below:
for(var i = 1; i <= 5; i++) {
for(var j = 1; j<= i; j++) {
document.write("*");
}
document.write("<br/>");
}
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= i; j++) {
document.write('*');
}
document.write('<br />');
}
As I understand from your code, you are actually trying to print stair pattern rather than star.
Your main error consists in that console.log function prints every time on the next line.
for (var i = 5; i >= 1; i--) {
var str = "";
for (var j = i; j >= 1; j--) str += j;
console.log(str);
}
JSFiddle for you: http://jsfiddle.net/99wL8cbt/2/
Just try it out
**Your Pyramid will be downwards like: **
4 3 2 1
3 2 1
2 1
1
function stars(n){
var str = '';
for(var i=n; i>=1; i--){
for(var k=n; k>=i; k--){
str += "\t";
}
for(var j=i; j>=1; j--){
str += j+"\t\t";
}
console.log(str);
str = "";
}
}
stars(3);
Your Pyramid will be upwards like :
*
* *
* * *
function stars(n){
var str = '';
for(var i=1; i<=n; i++){
for(var k=1; k<=n-i; k++){
str += "\t";
}
for(var j=1; j<=i; j++){
str += "*\t\t";
}
console.log(str);
str = "";
}
}
stars(3);
function pyramid(n) {
for(i=1 ;i<=n;i++) {
let str = ' '.repeat(n-i);
let str2 = '*'.repeat(i*2-1);
console.log(str + str2 + str);
}
}
pyramid(5)
the log will output to a new line every time it is called, in chrome if it's the same it will just keep a count (not sure about other browsers). You want to collect the number of stars per line then output that after the inner loop has run
for (var i = 5; i >= 1; i--) {
var ouput = "";
for (var j = i; j >= 1; j--) {
ouput += "*"
}
console.log(ouput);
}
Try this. Maybe it will work for you:
<html>
<head>
<script type="text/javascript">
var i, j;
//outer loop
for(i = 0;i < 5; i++){
//inner loop
for(j = 0;j <= i; j++){
document.write('*');
}
document.write('<br/>');
}
</script>
</head>
<body>
</body>
</html>
for(i=0;i<=5;i++)
{
for(j=0;j<=i;j++)
{
document.write('*');
}
document.write('<br>')
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="test"></p>
</body>
<script>
//Declare Variable
var i;
for(i = 0; i <= 5; i++){
document.write('*'.repeat(i).concat("<br>"))
}
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
//Declare Variable
var i,j;
//First Way
for(i = 5; i >= 0; i--){
for(j = 0; j <= i; j++){
document.write('*');
}
document.write('<br>');
}
//Second Way
for(i = 5; i >= 0; i--){
document.write('*'.repeat(i).concat('<br>'))
}
</script>
</head>
<body>
</body>
</html>
for(var a=1;a<8;a++){
var o="";
for(var b=1;b<=a;b++){
o +="#";
}
debug(o);
}
Try above code.
Output:
--> #
--> ##
--> ###
--> ####
--> #####
--> ######
This below code worked for me
for(i= 0; i< n; i++){
col = i;
for(j = 0; j< n- col;j++){
process.stdout.write('');
}
for (j = 1;j< col+2;j ++){
process.stdout.write('#');
}
process.stdout.write('\n');
}
<html>
<head>
<script>
//Declare Variable
var i, j;
//outer loop
for(i = 0; i <= 25; i++){
//inner loop
for(j = 0; j <= i; j++){
document.write("*");
}
document.write('<br>');
}
</script>
</head>
<body>
</body>
</html>
<!-- end snippet -->
Here is the solution in javascript while loop:
> var i = 0, out = '';
> while( i <= 4)
> {
> out = out + '* ';
> document.write('<br> '+ out);
> i++;
> }
>
> document.write('<br>');
Try this one for diamond pattern in javascript
<head>
<style>
p{text-align:center;margin-left:20px;}
</style>
</head>
<body>
<h1>JavaScript patterns</h1>
<p id="demo"></p>
<script>
var x=function(n){
document.write("<center>");
var c="";
for(var i=0; i<n; i++){
c=c+"#";
document.write(c);
document.write("<br>");
}
for(var k=n;k>0;k--){
for(var j=0; j<(k-1); j++){
document.write("#");
}
document.write("<br>");
}
}
document.getElementById("demo").innerHTML = x(10);
</script>
You can try this
var x, y, space = "",
star = "",
n = 4,
m = n - 1;
for (x = 1; x <= n; x++) {
for (y = m; y >= 1; y--) {
space = space + (" ");
}
m--;
for (let k = 1; k <= x * 2 - 1; k++) {
star = star + "*"
}
console.log(space + star)
space = '';
star = "";
}
I'm creating a form where users can input a range. They are allowed to input letters and numbers. Some sample input:
From: AA01
To: AZ02
Which should result in:
AA01
AA02
AB01
AB02
And so on, till AZ02
And:
From: BC01
To: DE01
Should result in:
BC01
BD01
BE01
CC01
CD01
CE01
Etc
I managed to get it working for the input A01 to D10 (for example)
jsFiddle
However, i can't get it to work with multiple letters.
JS code:
var $from = $('input[name="from"]');
var $to = $('input[name="to"]');
var $quantity = $('input[name="quantity"]');
var $rangeList = $('.rangeList');
var $leadingzeros = $('input[name="leadingzeros"]');
$from.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$to.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$leadingzeros.on('click', function () {
updateQuantity();
});
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
if (xl != null && yl != null && xl[0].length > 0 && yl[0].length > 0) {
xl = xl[0].toUpperCase();
yl = yl[0].toUpperCase();
$rangeList.html('');
var a = yl.charCodeAt(0) - xl.charCodeAt(0);
for (var i = 0; i <= a; i++) {
if (!isNaN(x) && !isNaN(y)) {
if (x <= y) {
var z = (y - x) + 1;
$quantity.val(z * (a + 1));
$rangeList.html('');
for (var b = z; b > 0; b--) {
var c = ((y - b) + 1);
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(String.fromCharCode(65 + i) + c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
}
} else if (!isNaN(x) && !isNaN(y)) {
if (x < y) {
var z = (y - x) + 1;
$quantity.val(z);
$rangeList.html('');
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
$rangeList.html('');
for (var i = 0; i < result.length; i++) {
$rangeList.append(result[i] + '<br />');
}
}
function leadingZeroes(number, size) {
number = number.toString();
while (number.length < size) number = "0" + number;
return number;
}
This is perfect for a recursive algorithm:
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
return result;
}
Called as follows:
createRange('BC01', 'DE02'); // Generates an array containing all values expected
EDIT: Amended function below to match new test case (much more messy, however, involving lots of type coercion between strings and integers).
function prefixZeroes(value, digits) {
var result = '';
value = value.toString();
for (var i = 0; i < digits - value.length; i++) {
result += '0';
}
return result + value;
}
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
if (from.charCodeAt(0) < 65) {
fromInt = parseInt(from);
toInt = parseInt(to);
length = toInt.toString().length;
var innerRange = createRange(from.substring(length), to.substring(length));
for (var i = fromInt; i <= toInt; i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(prefixZeroes(i, length) + innerRange[j]);
}
}
} else {
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
}
return result;
}
Please note that because of your strict logic in how the value increments this method requires exactly 4 characters (2 letters followed by 2 numbers) to work. Also, this might not be as efficient/tidy as it can be but it took some tinkering to meet your logic requirements.
function generate(start, end) {
var results = [];
//break out the start/end letters/numbers so that we can increment them seperately
var startLetters = start[0] + start[1];
var endLetters = end[0] + end[1];
var startNumber = Number(start[2] + start[3]);
var endNumber = Number(end[2] + end[3]);
//store the start letter/number so we no which value to reset the counter to when a maximum boundry in reached
var resetLetter = startLetters[1];
var resetNumber = startNumber;
//add first result as we will always have at least one
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
//maximum while loops for saefty, increase if needed
var whileSafety = 10000;
while (true) {
//safety check to ensure while loop doesn't go infinite
whileSafety--;
if (whileSafety == 0) break;
//check if we have reached the maximum value, if so stop the loop (break)
if (startNumber == endNumber && startLetters == endLetters) break;
//check if we have reached the maximum number. If so, and the letters limit is not reached
//then reset the number and increment the letters by 1
if (startNumber == endNumber && startLetters != endLetters) {
//reset the number counter
startNumber = resetNumber;
//if the second letter is at the limit then reset it and increment the first letter,
//otherwise increment the second letter and continue
if (startLetters[1] == endLetters[1]) {
startLetters = '' + String.fromCharCode(startLetters.charCodeAt(0) + 1) + resetLetter;
} else {
startLetters = startLetters[0] + String.fromCharCode(startLetters.charCodeAt(1) + 1);
}
} else {
//number limit not reached so just increment the number counter
startNumber++;
}
//add the next sequential value to the array
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
}
return results;
}
var results = generate("BC01", "DE01");
console.log(results);
Here is a working example, which uses your second test case
Using #Phylogenesis' code, i managed to achieve my goal.
jsFiddle demo
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
var r = createRange(xl[0], yl[0]);
var z = (y - x) + 1;
if (x <= y) {
for (var j = 0; j < r.length; j++) {
var letters = r[j];
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
if (i == z) {
r[j] = letters + c + '<br />';
} else {
j++;
r.splice(j, 0, letters + c + '<br />');
}
}
}
} else {
for (var i = 0; i < r.length; i++) {
r[i] += '<br />';
}
}
$quantity.val(r.length);
$rangeList.html('');
for (var i = 0; i < r.length; i++) {
$rangeList.append(r[i]);
}
}
This works for unlimited letters and numbers, as long as the letters are first.
Thanks for your help!
How can I check for matching numbers in this script, stuck here, I need to compare the array of user numbers with the array of lotto numbers and display how many numbers they got correct if any along with their prize value.
function numbers() {
var numbercount = 6;
var maxnumbers = 40;
var ok = 1;
r = new Array(numbercount);
for (var i = 1; i <= numbercount; i++) {
r[i] = Math.round(Math.random() * (maxnumbers - 1)) + 1;
}
for (var i = numbercount; i >= 1; i--) {
for (var j = numbercount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])) ok = 0;
}
}
if (ok) {
var output = "";
for (var k = 1; k <= numbercount; k++) {
output += r[k] + ", ";
}
document.lotto.results.value = output;
} else numbers();
}
function userNumbers() {
var usersNumbers = new Array(5);
for (var count = 0; count <= 5; count++) {
usersNumbers[count] = window.prompt("Enter your number " + (count + 1) + ": ");
}
document.lotto.usersNumbers.value = usersNumbers;
}
Here is a lotto numbers generator and a scoring system. I'm going to leave it to you to validate the user input.
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
function scoreIt(){
var usersNumbers = document.getElementsByName('usersNumbers').item(0);
usersNumbers = String(usersNumbers)
usersNumbers = usersNumbers.split(' ');
var matches = 0;
for(var i = 0; i<6; i++){
if(lottoNumbers.indexOf(usersNumbers[i]) != -1){matches++;}
}
return matches;
}
Hi I'm new to this and trying to learn off my own back so obviously I'm no expert but the code above makes a lot of sense to me, apart from the fact I can't get it to work.. I tried to console.log where it says RETURN so I could see the numbers but it just shows an empty array still. I assumed this was to do with it being outside the loop..
I've tried various ways but the best I get is an array that loops the same number or an array with 6 numbers but some of which are repeated..
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
Lotto JS: CODEPEN DEMO >> HERE <<
(function(){
var btn = document.querySelector("button");
var output = document.querySelector("#result");
function getRandom(min, max){
return Math.round(Math.random() * (max - min) + min);
}
function showRandomNUmbers(){
var numbers = [],
random;
for(var i = 0; i < 6; i++){
random = getRandom(1, 49);
while(numbers.indexOf(random) !== -1){
console.log("upps (" + random + ") it is in already.");
random = getRandom(1, 49);
console.log("replaced with: (" + random + ").");
}
numbers.push(random);
}
output.value = numbers.join(", ");
}
btn.onclick = showRandomNUmbers;
})();
I am trying to split up substring charaters from a string from what i have tryed so far has failed even looping within a loop.
An example result from string "1234567890" the output could look like as follows
12
345
6
7890
.
var randomChar = ""
var str = "123456789";
for (var j = 0; j < str.length; j++) {
randomChar = Math.floor(Math.random() * 3) + 1;
console.log(str.substr(j, randomChar));
}
here you go:
var substrSize;
while (str.length) {
substrSize = Math.floor(Math.random()*3)+1; // at most 4?
if (substrSize >= str.length)
randomChar = str;
else
randomChar = str.substr(0,substrSize);
str = str.substr(randomChar.length);
console.log(randomChar);
}
or alternatively:
var j = 0;
while (j < str.length) {
var n= j+Math.floor(Math.random() * 3) + 1;
if (n> str.length) n= str.length;
console.log(str.substring(j, n));
j = n;
}
or alternatively:
var j = 0;
while (j < str.length) {
var n= Math.floor(Math.random() * 3) + 1;
if (j+n> str.length) n= str.length-j;
console.log(str.substr(j, n));
j += n;
}
The problem with your code is that you always iterate str.length times. After cutting out for example first 3 random characters you should start from 4th, not from 2nd.
And here is an elegant recursive solution, much different from yours:
function randString(s) {
if(s.length > 0) {
var pivot = Math.ceil(Math.random() * 3);
console.info(s.substring(0, pivot));
randString(s.substring(pivot));
}
}
var randomChar = ""
var str = "123456789";
var j = 0;
while (j < str.length) {
randomChar = Math.floor(Math.random() * 3) + 1;
console.log(str.substr(j, randomChar));
j += randomChar;
}
Here is my javascript code
for (var i = 1; i <= _MAXPAGECOUNT - 2; i++) {
e = document.getElementsByName("q" + i + "[]");
for (var j = 0; j <= e.length - 1; j++) {
if (e[j].checked) {
result = result + "," + i + ":" + e[j].value;
// break;
}
}}
The problem is this, it shows result like this 1:2,1:3,1:4,2:3,2:4,2:5
here in code i means question number and j means answer number, but I want to result as like this 1:2,3,4 ; 2:3,4,5
Try this
for (var i = 1; i <= _MAXPAGECOUNT - 2; i++) {
result = result+i+":";
e = document.getElementsByName("q" + i + "[]");
for (var j = 0; j <= e.length - 1; j++) {
if (e[j].checked) {
result = result + e[j].value;
// break;
}
}
if(i<_MAXPAGECOUNT - 2)
{
result = result+" ; ";
}
}