david
david

Reputation: 4278

randomly split up substrings

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

Upvotes: 2

Views: 884

Answers (3)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340933

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

Upvotes: 2

thang
thang

Reputation: 3466

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

Upvotes: 2

ncn corp
ncn corp

Reputation: 111

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

Upvotes: 1

Related Questions