randomly split up substrings - javascript

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

Related

How to print a half pyramid in javascript

The code works but I don't want the inner for loop to take me to the new line.
for (i = 0; i < 5; i++) {
for (j = 1; j <= i; j++) {
console.log('*');
}
console.log();
}
console.log('-----------------');
console.log will automatically break the line. Concatenate to a string instead of a log. Log at the end.
let str = '';
for(i = 0; i <= 5 ; i++) {
for(j = 1; j <= i; j++) {
str += '*';
}
str += '\n';
}
console.log(str);
You can do this way, with the help of a string variable:
for (i = 0; i < 5; i++) {
var str = '';
for (j = 1; j <= i; j++) {
str+='*';
}
console.log(str);
}
console.log('-----------------');
If you want to print at the page, use like below
for (i = 0; i < 5; i++) {
let j=0;
do{document.write("*");j++;}while(j < i)
document.write("<br/>")
}
You need to break the line with the console.log you can also controle the space between * with output+='*' + " ";
function pyramid() {
var total = 5;
var output="";
for (var i = 1; i <= total; i++) {
for (var j = 1; j <= i; j++) {
output+='*' + " ";
}
console.log(output);
output="";
}
}
pyramid()
You can get rid of second for loop as follows:
var str = '';
for (i = 1; i <= 5; i++) {
str +=Array(i).join("*");
str +='\n';
}
console.log(str);
let string = "";
for (let i = 0; i < 5; i++){
string += '*';
console.log(string);
}
Output:
*
**
***
****
*****
A simple way to solve this "exercise" in JavaScript:
let width = ""
while(width.length < 6) console.log(width += `#` );
Basically, we create a string (width) and increment its value using the while loop till we hit a restriction.
I found the more typical method "bulky"(?)...plus there's the issue of not getting the exact picture of a half pyramid.
let i,j
for (i= 0; i < 6; i++){
for (j = 0; j<=i; j++){
console.log("#")
}
console.log("\n")
}
function pyramid(n){
let result = "";
for(let i=0; i<=n; i++){
result += "*".repeat(i);
result += "\n"
}
return result;
}
console.log(pyramid(5));
//OutPut
*
**
***
****
*****
As we need n number of pyramid structure with '' / '#' / any symbol. by using above code we can achieve. Here you can see we just created a function called pyramid with one parameter 'n'. and inside function we declare a variable 'result'. So inside for loop the length of 'i' is "<=n" and also you can use "repeat() method to print '' 'i' times. So if you call that function like console.log(pyramid(5)); You can able to see your Answer as expected..
shortest code:
console.log('*\n**\n***\n****\n*****');

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

Simple Javascript Christmas Tree

I created a half of the Christmas Tree but here I got blocked. Some one please help me to understand how to do the left side too.
for (var i = 0; i < 8; i++) {
for (var j = 0; j <= i; j++) {
document.write("^");
}
document.write("<br>");
}
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>
Source: http://codeforwin.org/2015/07/equilateral-triangle-star-pattern-program-in-c.html
C to JavaScript by me.
I wrote the following code for this problem.
I also added a nice extra, christmas-tree ornaments :-)
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
private static Random RND = new Random(System.currentTimeMillis()); // useful for placing balls
private static char[] BALLS = {'o','⌾','⛣','⏣','◍'}; // symbols being used as balls
public static void main (String[] args) throws java.lang.Exception
{
int w = 27; // width of the tree
int b = 10; // number of balls in the tree
String tree = ""; // this will end up containing the tree
// build tree
w = ( w % 2 == 1 ) ? w : 13; // check whether width is odd
for(int i=1;i<=w;i+=2){
int s = (w - i) / 2;
tree += repeat(' ', s) + repeat('*', i) + repeat(' ', s) + "\n";
}
// randomly replace some parts by balls
int i=0;
while(i < b){
int j = RND.nextInt(tree.length());
if(tree.charAt(j) == '*'){
tree = tree.substring(0, j) + BALLS[RND.nextInt(BALLS.length)] + tree.substring(j+1);
i++;
}
}
// build trunk
tree += repeat(' ', (w - 4) / 2) + repeat('*', 4) + "\n" + repeat(' ', (w - 4) / 2) + repeat('*', 4);
// output
System.out.println(tree);
}
// this function builds a String by repeating a given character a couple of times
private static String repeat(char c, int l){
String s = "";
for(int i=0;i<l;i++)
s += c;
return s;
}
}
The output should look something like this:
⏣
***
*o***
**⌾*o**
*****⛣**⛣
*****⌾****⏣
**◍*◍********
****
****
The keyword is think.
var x = 8;
for (let i = 0; i < x; i++) {
for (let j=x-1; j>i; j--) {
document.write("&nbsp&nbsp");
}
for (let k=0; k<=(i*2); k++) {
document.write("^");
}
document.write("<br>");
}
for (let i=0; i<2; i++) {
for (let j=0; j<(x*2)-3; j++) {
document.write("&nbsp");
}
document.write("^<br>");
}
Constraints: Only looks good starting from x = 5.
Original code by me
The answers above heavily rely on nested loops, thought I post another approach with "modern" JS (of course still using a single loop with the map function given to Array.from()):
function xmas(height) {
// add 1 more level for the trunk, e.g. height+1
return Array.from({length: height+1}, (v, i) => {
return i === height
// that's for the trunk of the tree
? '*'.padStart(Math.round((2 * i)/2), ' ')
// the actual tree "levels"
: '*'.repeat(2 * i + 1).padStart(2 * i + height-i, ' ');
}).join('\n');
}
document.write(`<pre>${xmas(10)}</pre>`);
maybe the attempt to make it work with .padStart() is not optimal because the math gets a bit ugly, but anyways, just for fun =)...
Here's a solution with a simple for loop without any nested loop.
let row = ""
let l = 9
for (let i = 0; i < l; i++) {
row += " ".repeat(l - i) + "*" + "*".repeat(i * 2) + `\n`;
}
console.log(row);
Simple christmas tree function:
function christmasTree(x) {
if(x < 3) {
return "";
}
let tree = "";
for(let i = 1; i <= x; i++) {
for(let j = 1; j <= x + x - 1; j++) {
if(j <= x - i || j >= x + i) {
tree += " ";
} else {
tree += "*";
}
}
tree += "\n";
}
return tree;
}
Incase you are looking for how to do this in a function for javascript or typescript
Use 3 for loops,
1 - Number of rows
2 - Number of spaces
3 - Number of characters
function christmas(n) {
let tree = '';
for (let i = 1; i <= n; i++) {
for (let j=0; j <= n-i; j++) {
tree += ' ';
}
for (k = 0; k< (i*2)-1; k++) {
tree += '*';
}
tree += '\n';
}
return tree;
}
console.log(christmas(3));
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>

How to print star pattern in JavaScript in a very simple manner? [closed]

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

Javascript Loto Game

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

Categories

Resources