How do I generate pseudo random array? - javascript

I need to generate array from letters A,H,O,J and numbers 0-9. I want to generate letters into new array in order AHOJ. The individual characters can appear elsewhere in new array but always in AHOJ order and they dont need to follow each other. Remaining indexes of new array will be filled with digits. Examples - A123H85O2J3, AHOJ9854273, 012AH851OJ3 and so on. The order of AHOJ must not be randomized within new array. I have this code, but is probably completly wrong. It only works as expected when condition equal to 7 is met.
let letters = ['A','H','O','J'];
let newArray =new Array(11);
let lastIndex = 10;
for (let i = 0; i < letters.length; i++) {
newIndex = Math.floor(Math.random() * lastIndex);
console.log(newIndex);
if (newIndex == 7) {
for (let j = 0; j < letters.length; j++) {
newArray.splice(j + 7,1,letters[j]);
}
for ( let k = 0; k < 7; k++) {
newArray.splice(k,1,Math.floor(Math.random() * 10).toString());
}
break;
}
else if (newIndex > 7) {
lastIndex = Math.floor(Math.random() * 6);
newArray.splice(lastIndex,1,letters[i]);
}
else {
newArray.splice(newIndex,1,letters[i]);
}
console.log(letters[i]);
}
console.log(newArray);

It can be simplified to one loop :
let letters = ['A','H','O','J'];
for (let l = 5; l < 12; l++) // for random indexes from 4 to 11
{
let position = Math.floor(Math.random() * l);
let digit = Math.floor(Math.random() * 10);
letters.splice(position, 0, digit);
}
console.log( letters.join(''), letters.length );

for (let i = 0; i < 100; i += 1) {
console.log(generate('AHOJ', 11))
}
function generate(word, length) {
// create array [0, 1, 2, ..., length - 1]
const indexes = [...Array(length).keys()]
// get unique random indexes for each character of the word
const reserved = [...word].map(() => {
// random index of indexes array
const index = Math.floor(Math.random() * indexes.length)
// remove the number at index from indexes array
const res = indexes.splice(index, 1)
// return removed number
return res[0]
})
const result = []
for (let i = 0, w = 0; i < length; i += 1) {
// if index is reserved, push a letter from word
if (reserved.includes(i)) {
result.push(word[w])
w += 1
// push random digit otherwise
} else {
result.push(Math.floor(Math.random() * 9))
}
}
return result.join('')
}

Related

Check if two following values exist in an array

I have a nested array like this:
[ [5, 10, 5, 15, 5, 10], [10, 15, 50, 200] ]
So basically I have index 0 that also has an array with the values [5,10,5,15,5,10] and index 1 with an array with values [10,15,50,350].
let array = [[],[]];
let x = 0;
let y = 0;
for (let i = 0; i < 10; i++) {
x = ... generate random number ...
y = ... generate random number ...
while (array[0].includes(x,y) {
x = ... generate new random number ...
y = ... generate new random number ...
}
array[0].push(x,y);
}
Is there a way for me to find if for example index 0 in the array already contains the two generated values in the same order they are being pushed?
For example, I'm adding value 5,15 to the array. And the array already contains index 0 with 5 and index 1 with, 15 in that order. So I want to generate a new number if the numbers already exist in that order.
I've tried looking for solutions, but haven't found anything that helps me with what I wanna do.
I recommend making a function that checks for a specific sequence of numbers, this way if you need it to find a X number sequence you're ready.
const max = 100;
let array = [[], []];
let x = 0,
y = 0;
for (let i = 0; i < 1000; i++) {
x = Math.floor(Math.random() * max);
y = Math.floor(Math.random() * max);
while (containsSequence(array[0], [x, y])) {
console.log(`Sequence ${x},${y} already exists.`);
x = Math.floor(Math.random() * max);
y = Math.floor(Math.random() * max);
}
array[0].push(x, y);
}
/**
* #param {Array<Number>} arr
* #param {Array<Number>} sequence */
function containsSequence(arr, sequence) {
if(arr.length === 0) { return false; }
const first = sequence[0];
let index = arr.indexOf(first, 0);
while(index > -1) {
if(sequence.every((v, i) => arr[index + i] === v)) {
return true;
}
index = arr.indexOf(first, index);
if(index == -1) { return false; }
index++;
}
return false;
}
You are putting x and y one after each other in the list, if you connect them to an object or an array, you can iterate over the outer array more easily:
for (let i = 0; i < 10; i++) {
x = ... generate random number ...
y = ... generate random number ...
while (array[0].filter(i=>i.x == x && i.y == y).length) {
x = ... generate new random number ...
y = ... generate new random number ...
}
array[0].push({x,y});
}
it will also make it more simle. Of course,only if you can make this change to the array structure
Assuming that this is just a general structural question as mentioned in the comments, you can adapt your code as below.
for (let i = 0; i < 10; i++) {
int index = 1;
while (index < array[0].length){
if ((array[0][i][index-1].includes(x) && array[0][i][index].includes(y)) {
x = ... generate new random number ...
y = ... generate new random number ...
index = 0;
}
else{
index++;
}
}
array[0].push(x,y);
}
}

Find longest sequence of zeros in binary representation of an integer in JavaScript?

Well in this question I have to find the longest sequence of zeros in the binary representation of an integer.
After a lot of hard work, I'm able to find the longest sequence of zeros with my logic which I changed many times.
I have one problem with my logic which is if I input an integer that has no gap in it has to give me an answer 0 which I tried to make by myself but I failed.
Right now if I input an integer that has no gap it gives me output infinity.
I want my answer to print 0 when the binary representation of an integer has no gap in it.
var dn = prompt("Enter a number: ");
var bn = new Array();
var i = 0;
var binary = [];
while (dn != 0) {
bn[i] = dn % 2;
dn = Math.floor(dn / 2);
i++;
}
for (var j = i - 1; j >= 0; j--) {
binary.push(bn[j]);
}
console.log(binary.join(""));
var currentGap = 0;
var gaps = [];
var len = binary.length;
for (var k = 0; k < len; k++) {
if (binary[k] == 0) {
currentGap++;
if (binary[k + 1] == 1) {
gaps.push(currentGap);
currentGap = 0;
}
}
}
console.log(Math.max(...gaps));
You could add initialize gaps with 0, or add condition when gaps remains empty to print 0 else max of gaps.
var dn = prompt("Enter a number: ");
var bn = new Array();
var i = 0;
var binary = [];
while (dn != 0) {
bn[i] = dn % 2;
dn = Math.floor(dn / 2);
i++;
}
for (var j = i - 1; j >= 0; j--) {
binary.push(bn[j]);
}
console.log(binary.join(""));
var currentGap = 0;
//var gaps = []
var gaps = [0];
var len = binary.length;
for (var k = 0; k < len; k++) {
if (binary[k] == 0) {
currentGap++;
if (binary[k + 1] == 1) {
gaps.push(currentGap);
currentGap = 0;
}
}
}
//if (gaps.length === 0)
// console.log(0)
//else
// console.log(Math.max(...gaps));
console.log(Math.max(...gaps));
You can simply print 0 if your gaps array has no length.
var dn = prompt("Enter a number: ");
var bn = new Array();
var i = 0;
var binary = [];
while (dn != 0) {
bn[i] = dn % 2;
dn = Math.floor(dn / 2);
i++;
}
for (var j = i - 1; j >= 0; j--) {
binary.push(bn[j]);
}
console.log(binary.join(""));
var currentGap = 0;
var gaps = [];
var len = binary.length;
for (var k = 0; k < len; k++) {
if (binary[k] == 0) {
currentGap++;
if (binary[k + 1] == 1) {
gaps.push(currentGap);
currentGap = 0;
}
}
}
console.log(gaps.length ? Math.max(...gaps) : 0); // <-- This
I apologize if I'm misunderstanding your question, but would this satisfy your problem?
const s = prompt("Enter a number:");
const longest = Math.max(...parseInt(s).toString(2).split('1').map(s=>s.length));
console.log(longest);
just change var gaps = [];
to var gaps = [0];
You can also do that...
let dn = parseInt(prompt("Enter a number: "))
if (isNaN(dn)) console.log('Not a Number!')
else
{
let
dnStr = dn.toString(2) // binary convertion
, count = 0
, zVal = '0'
;
while (dnStr.includes(zVal) )
{
count++
zVal += '0'
}
console.log( `${dnStr}\n--> ${count}` )
}
If you want to do your own binary convertion, prefert o use Javasscript binary opérators:
let dn = parseInt(prompt("Enter a number: "))
if (isNaN(dn)) console.log('Not a Number!')
else
{
let gap = [0]
let Bin = []
let count = 0
for (;;)
{
Bin.unshift( dn & 1 ) // --> dn % 2
if (dn & 1)
{
gap.push(count)
count = 0
}
else count++
dn >>>=1 // --> dn = Math.floor(dn / 2)
if (!dn) break // --> if (dn === 0 )
}
console.log(Bin.join(''))
console.log(Math.max(...gap))
}
I had a go at this and this is what I came up with as a function:
function binaryGap(N){
let binary = Math.abs(N).toString(2); // Convert to Binary string
let binarySplit = binary.split("1"); // Split the string wherever there is "1"
let tempBinaryArr = []; // create an empty array to store the element from Splice
let max = 0; // Setting the max length to zero to compare with each element
// Removing the zeros at the end
if(binarySplit[binarySplit.length -1] == 0){
tempBinaryArr = binarySplit.splice(binarySplit.length -1, 1);
}
//Looping through each element of binarySplit to compare with variable max
for(let j=0; j < binarySplit.length; j++){
if(max < binarySplit[j].length){
max = binarySplit[j].length;
}
}
return `Longest Sequence of Zeros: ${max}`;
}
If I understood the task correctly, you can arrange the logic in something like this. In case if the input comes as a string you don't need the .toString() part
function splitByZero(str) {
const eachSubstr = str
.toString()
.split(1)
.filter((e) => e); //to remove empty values in the new array
let maxLength = 0;
for (const substr of eachSubstr) {
if (maxLength < substr.length) {
maxLength = substr.length;
}
}
console.log(maxLength);
}
splitByZero(111011100011);
function findLongestDistance(){
findGap("1000100100001");
findGap("1000100");
findGap("000100");
findGap("10000");
findGap("000001");
findGap("111111")
}
function findGap(n){
var split = n.split(/1/g);
var longestZeros = 0;
if(split.length>2){
for(var i in split){
var len = split[i].length;
if(len>longestZeros){
longestZeros = len;
}
}
console.log(longestZeros);
return longestZeros;
}
console.log(0);
return 0;
}

Not able to get value after Do...While loop

Question: Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21
513 ==> 531
2017 ==> 2071
//nextBigger(num: 12) // returns 21
//nextBigger(num: 513) // returns 531
//nextBigger(num: 2017) // returns 2071
I am trying to compare two Array and get correct array as answer. In do...while loop I am comparing the two array by increment second array by one.
function nextBigger(n){
let nStrg = n.toString();
let nArr = nStrg.split('');
function compareArr(Ar1,Ar2){
if(Ar2.length>Ar1.length){
return false;
}
for(let i=0; i<Ar1.length; i++){
let num = Ar1[i];
for(let j=0; j<Ar2.length; j++){
if(Ar2.lastIndexOf(num) !== -1){
Ar2.splice(Ar2.lastIndexOf(num), 1);
break;
}
else{
return false;
break;
}
}
}
return true;
}
let nextNumArr;
let m = n;
do{
let nextNum = m+1
m=nextNum
let nextNumStrg = nextNum.toString();
nextNumArr = nextNumStrg.split('')
console.log(compareArr(nArr, nextNumArr))
}
while(compareArr(nArr, nextNumArr) == false)
console.log(nextNumArr)
return parseInt(nextNumArr.join())
}
nextBigger(12);
This gives me empty array at the end;
[2,0,1,7].join() will give you '2,0,1,7', can use [2,0,1,7].join('') and get '2017'
All looks a bit complicated. How about:
const nextLarger = num => {
const numX = `${num}`.split(``).map(Number).reverse();
for (let i = 0; i < numX.length; i += 1) {
if ( numX[i] > numX[i + 1] ) {
numX.splice(i, 2, ...[numX[i+1], numX[i]]);
return +(numX.reverse().join(``));
}
}
return num;
};
const test = [...Array(100)].map(v => {
const someNr = Math.floor(10 + Math.random() * 100000);
const next = nextLarger(someNr);
return `${someNr} => ${
next === someNr ? `not possible` : next}`;
}).join('\n');
document.querySelector(`pre`).textContent = test;
<pre></pre>
See also
function nextbig(number) {
let nums = []
number.toString().split('').forEach((num) => {
nums.push(parseInt(num))
})
number = nums
n = number.length
for (var i = n - 1; i >= 0; i--) {
if (number[i] > number[i - 1])
break;
}
if (i == 1 && number[i] <= number[i - 1]) {
return 'No greater possible'
}
let x = number[i - 1];
let smallest = i;
for (let j = i + 1; j < n; j++) {
if (number[j] > x &&
number[j] < number[smallest])
smallest = j;
}
let temp = number[smallest];
number[smallest] = number[i - 1];
number[i - 1] = temp;
x = 0
for (let j = 0; j < i; j++)
x = x * 10 + number[j];
number = number.slice(i, number.length + 1);
number.sort()
for (let j = 0; j < n - i; j++)
x = x * 10 + number[j];
return x
}
console.log(nextbig(12))
console.log(nextbig(513))
console.log(nextbig(2017))
In compareArr you are deleting elements as you find them, which is correct to do, to make sure duplicates actually occur twice etc. However, that also deletes the elements from nextNumArr in the calling context, because the array is passed by reference and not by value. You need to do a manual copy of it, for example like this: compareArr(nArr, [...nextNumArr]).
I have used a different approach, first I search for all possible combinations of the given numbers with the permutator function. This function returns an array of possible numbers.
Then I sort this array of combinations and look for the index of the given number in the main function.
Once I have this index I return the position before the given number.
function nextbig(num){
function permutator(inputArr){
let result = [];
const permute = (arr, m = []) => {
if (arr.length === 0) {
result.push(m)
} else {
for (let i = 0; i < arr.length; i++) {
let curr = arr.slice();
let next = curr.splice(i, 1);
permute(curr.slice(), m.concat(next))
}
}
}
permute(inputArr)
return result;
}
let arrNums = num.toString().split('')
let combinations = permutator(arrNums).map(elem => parseInt(elem.join("")))
combinations.sort((a, b) => {
return b - a
})
let indexOfNum = combinations.findIndex(elem => elem === num)
let nextBigIndex = indexOfNum <= 0 ? 0 : indexOfNum - 1
return (combinations[nextBigIndex])
}
console.log(nextbig(12))
console.log(nextbig(517))
console.log(nextbig(2017))

Largest Triple Products without using sort?

I implemented the Largest Triple Products algorithm, but I use sort which makes my time complexity O(nlogn). Is there a way to implement it without a temporary sorted array?
The problem:
You're given a list of n integers arr[0..(n-1)]. You must compute a list output[0..(n-1)] such that, for each index i (between 0 and n-1, inclusive), output[i] is equal to the product of the three largest elements out of arr[0..i] (or equal to -1 if i < 2, as arr[0..i] then includes fewer than three elements).
Note that the three largest elements used to form any product may have the same values as one another, but they must be at different indices in arr.
Example:
var arr_2 = [2, 4, 7, 1, 5, 3];
var expected_2 = [-1, -1, 56, 56, 140, 140];
My solution:
function findMaxProduct(arr) {
// Write your code here
if(!arr || arr.length === 0) return [];
let helper = arr.slice();
helper.sort((a,b)=>a-b); // THIS IS THE SORT
let ans = [];
let prod = 1;
for(let i=0; i<arr.length; i++) {
if(i < 2) {
prod *= arr[i];
ans.push(-1);
}
else {
if(i === 3) {
prod *= arr[i];
ans.push(prod);
} else if(arr[i] < helper[0]) {
ans.push(prod);
} else {
const min = helper.shift();
prod /= min;
prod *= arr[i];
ans.push(prod);
}
}
}
return ans;
}
Thanks
You don't need to sort it. You just maintain an array of the largest three elements at each index.
For the first three elements it is simple you just assign the product of them to the third element in the result.
For the next elements, you add the current element to the three-largest-element-array and sort it and take the elements from 1 to 3 ( the largest three ) and assign the product of those at that index in result array. Then update the three-element-array with largest three.
Complexity :
This sort and slice of three-element-array should be O(1) because each time atmost 4 elements are there in the array.
Overall complexity is O(n).
You can do it as follows :
function findMaxProduct(arr) {
if(!arr) return [];
if (arr.length < 3) return arr.slice().fill(-1)
let t = arr.slice(0,3)
let ans = arr.slice().fill(-1,0,2) //fill first two with -1
ans[2] = t[0]*t[1]*t[2];
for(let i=3; i<arr.length; i++) {
t.push(arr[i]);
t = t.sort().slice(1,4);
ans[i] = t[0]*t[1]*t[2];
}
return ans;
}
I am keeping the array ordered (manually). Then just get the first 3 elements.
function findMaxProduct(arr) {
let results = [];
let heap = [];
for (let i = 0; i < arr.length; i++) {
// Insert the new element in the correct position
for (let j = 0; j < heap.length; j++) {
if (arr[i] >= heap[j]) {
heap.splice(j, 0, arr[i]);
break;
}
}
// No position found, insert at the end
if (heap.length != i + 1) {
heap.push(arr[i]);
}
if (i < 2) {
results.push(-1);
} else {
results.push(heap[0] * heap[1] * heap[2]);
}
}
return results;
}
You can make an array that holds three currently largest integers, and update that array as you passing through original array. That's how you will always have three currently largest numbers and you will be able to solve this with O(n) time complexity.
I think there's a faster and more efficient way to go about this. This is a similar thought process as #Q2Learn, using Python; just faster:
def findMaxProduct(arr):
#create a copy of arr
solution = arr.copy()
# make first 2 elements -1
for i in range(0,2):
solution[i] = -1
#for each item in copy starting from index 2, multiply item from 2 indices b'4 (notice how each index of arr being multiplied is reduced by 2, 1 and then 0, to accommodate each move)
for i in range(2, len(arr)):
solution[i] = arr[i-2] * arr[i-1] * arr[i]
return solution
check = findMaxProduct(arr)
print(check)
Single Scan Algorithm O(n)
We don't need to necessarily sort the given array to find the maximum product. Instead, we can only find the three largest values (x, y, z) in the given stage of iteration:
JavaScript:
function findMaxProduct(arr) {
let reults = []
let x = 0
let y = 0
let z = 0
for(let i=0; i<arr.length; i++) {
n = arr[i]
if (n > x) {
z = y
y = x
x = n
}
if (n < x && n > y) {
z = y
y = n
}
if (n < y && n > z) {
z = n
}
ans = x*y*z
if (ans === 0) {
results.push(-1)
} else {
results.push(ans)
}
return ans;
}
Python:
def findMaxProduct(arr):
results = []
if not arr:
return []
x = 0
y = 0
z = 0
for i, n in enumerate(arr):
if n > x:
z = y
y = x
x = n
if n < x and n > y:
z = y
y = n
if n < y and n > z:
z = n
ans = x*y*z
if ans == 0:
results.append(-1)
else:
results.append(ans)
print(results)
public int[] LargestTripleProducts(int[] input)
{
var ansArr = new int[input.Length];
var firstLargetst = input[0];
var secondLargetst = input[1];
ansArr[0] = ansArr[1] = -1;
for (int i = 2; i < input.Length; i++)
{
ansArr[i] = firstLargetst * secondLargetst * input[i];
if (firstLargetst < input[i] && firstLargetst < secondLargetst)
{
firstLargetst= input[i];
continue;
}
if (secondLargetst < input[i] && secondLargetst < firstLargetst)
{
secondLargetst= input[i];
}
}
return ansArr;
}
Python solution based on #SomeDude answer above. See explanation there.
def findMaxProduct(arr):
if not arr:
return None
if len(arr) < 3:
for i in range(len(arr)):
arr[i] = -1
return arr
three_largest_elem = arr[0:3]
answer = arr.copy()
for i in range(0, 2):
answer[i] = -1
answer[2] = three_largest_elem[0] * three_largest_elem[1] * three_largest_elem[2]
for i in range(3, len(arr)):
three_largest_elem.append(arr[i])
three_largest_elem = sorted(three_largest_elem)
three_largest_elem = three_largest_elem[1:4]
answer[i] = three_largest_elem[0] * three_largest_elem[1] * three_largest_elem[2]
return answer #Time: O(1) n <= 4, to Overall O(n) | Space: O(1)
Python has it's in-built package heapq, look at it for it.
Credit: Martin
> Helper function for any type of calculations
import math
> Heap algorithm
import heapq
> Create empty list to append output values
output = []
def findMaxProduct(arr):
out = []
h = []
for e in arr:
heapq.heappush(h, e)
if len(h) < 3:
out.append(-1)
else:
if len(h) > 3:
heapq.heappop(h)
out.append(h[0] * h[1] * h[2])
return out
Hope this helps!

Randomly space characters throughout string?

To shuffle a string, I could use something like this
String.prototype.shuffle = function () {
var arr = this.split("");
var len = arr.length;
for (var n = len - 1; n > 0; n--) {
m = Math.floor(Math.random() * (n + 1));
tmp = arr[n];
arr[n] = arr[m];
arr[m] = tmp;
}
return arr.join("");
}
But how could I randomly space it with n characters, while preserving the string order?
For example:
"test" => "t-es--t"
"test" => "-t-e-st"
"test" => "te--st-"
I've thought about creating a list from the string, generating a random number to represent an index, and then shifting the list to the left, but is there a better way to do this?
This will insert n characters char randomly into the string. If char is missing, it defaults to a space:
String.prototype.shuffle = function(n, char) {
var arr = this.split(''),
char= char || ' ';
while(n--) {
arr.splice(Math.floor(Math.random() * (arr.length+1)), 0, char);
}
return arr.join('');
} //shuffle
This Fiddle shows the relative random distribution using the method.
If you want a truly unbiased solution that produces all possibilities equally likely, and have access to a perfect random number generator (which is a whole other topic), there's a fairly easy solution. Let's define some terms:
m = number of characters in the string
k = number of spaces you want to insert (you called this n)
Consider one solution to this problem with m=7 and k=3:
0123456789
cab ba g e
What the problem essentially amounts to is choosing k different numbers from among a set of m+k numbers. There are (m+k)!/(m!*k!) possibilities. This is the concept of combinations and is similar to the stars-and-bars problem in the Wikipedia page. (To get an unbiased generator you would need a random number generator with the number of state values much higher than this number of possibilities. But I said RNGs are a whole other topic.)
Here's an example in Python showing all possibilities:
import itertools
def show_all(s, k):
# show all combinations of k spaces inserted into string s
m = len(s)
for sample in itertools.combinations(range(m+k),k):
jprev = 0
out = ''
for ispace, i in enumerate(sample):
j = i-ispace # adjust index by number of spaces used
out += s[jprev:j] + ' '
jprev = j
out += s[jprev:]
yield sample, out
for sample, out in show_all('shoe',2):
print sample,':'+out+':'
output:
(0, 1) : shoe:
(0, 2) : s hoe:
(0, 3) : sh oe:
(0, 4) : sho e:
(0, 5) : shoe :
(1, 2) :s hoe:
(1, 3) :s h oe:
(1, 4) :s ho e:
(1, 5) :s hoe :
(2, 3) :sh oe:
(2, 4) :sh o e:
(2, 5) :sh oe :
(3, 4) :sho e:
(3, 5) :sho e :
(4, 5) :shoe :
Now the problem becomes one of generating a random combination. In Python this is part of the itertools recipes:
def random_combination_with_replacement(iterable, r):
"Random selection from itertools.combinations_with_replacement(iterable, r)"
pool = tuple(iterable)
n = len(pool)
indices = sorted(random.randrange(n) for i in xrange(r))
return tuple(pool[i] for i in indices))
In Javascript we have to implement this ourselves, which we can do using Robert Floyd's algorithm for sampling without replacement:
pseudocode:
initialize set S to empty
for J := N-M + 1 to N do
T := RandInt(1, J)
if T is not in S then
insert T in S
else
insert J in S
Javascript:
function random_comb(r, n, m)
{
/* Generate a combination of m distinct random integers between 0 and n-1
using Floyd's algorithm
r: random generation function
such that r(k) generates an integer in the range [0, k-1]
*/
var S = {};
var out = [];
for (var i = 0; i < m; ++i)
{
var j = i+(n-m);
var t = r(j+1);
var item = (t in S) ? j : t;
S[item] = 1;
out.push(item);
}
return out.sort();
}
Now let's put it all together, ignoring the fact that Math.random() is inadequate:
var r = function(n) { return Math.floor(Math.random()*n); }
function random_comb(r, n, m)
{
/* Generate a combination of m distinct random integers between 0 and n-1
using Floyd's algorithm
r: random generation function
such that r(k) generates an integer in the range [0, k-1]
*/
var S = {};
var out = [];
for (var i = 0; i < m; ++i)
{
var j = i+(n-m);
var t = r(j+1);
var item = (t in S) ? j : t;
S[item] = 1;
out.push(item);
}
return out.sort();
}
function random_insert(r, s, k, c)
{
/* randomly insert k instances of character c into string s */
var m = s.length;
var S = random_comb(r, m+k, k);
var jprev = 0;
var out = '';
for (var ispace = 0; ispace < k; ++ispace)
{
var i = S[ispace];
var j = i - ispace; // adjust index by # of spaces
out += s.slice(jprev,j) + c;
jprev = j;
}
out += s.slice(jprev);
return out;
}
var word = 'shoe';
var results = [];
for (var i = 0; i < 10; ++i)
{
results.push(random_insert(r,word, 2, '-'));
}
var tally = {};
for (var i = 0; i < 100000; ++i)
{
var s = random_insert(r,word,2,'-');
tally[s] = (s in tally) ? (tally[s] + 1) : 1;
}
for (var s in tally)
{
results.push(s+": "+tally[s]);
}
for (var i = 0; i < results.length; ++i)
{
$("#results").append(results[i]+'<br>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>
Working jsFiddle
Even though I loved #Barmar 's idea..
You can do it by simply looping and randomizing positions to insert the spaces..
String.prototype.insertSpaces = function (n, char) {
var str = this;
for(var i = 0; i < n; i++){
var randPos = Math.floor(Math.random() * (str.length + 1)); // get random index to insert
str = str.substring(0, randPos) + char + str.substring(randPos, str.legnth); // insert the repeated sting
}
return str;
}
function addRandomSpaces(str,n,char){
for (var newstr="", i=0; i<str.length;){
if (n && Math.random()<0.5) {
newstr += char;
n--;
} else {
newstr += str[i++];
}
}
while(n--){
newstr += char;
}
return newstr;
}
Here's a function that will loop through a given string str, adding n instances of char at random places. If when it finishes, n items haven't been added, it adds finishes them at the end.
You can use the slice function insert the new character:
var x = "this is phrase";
var y = " a";
[x.slice(0,7), y, x.slice(7)].join('');
Result: this is a phrase
Something like this:
String.prototype.shuffle2 = function() {
'use strict';
var numberOfSpaces = Math.floor(Math.random() * (this.length - 1));
var word = this;
for (var i = 0; i < numberOfSpaces; i++) {
var index = Math.floor(Math.random() * (this.length - 1));
word = [word.slice(0,index), '-', word.slice(index)].join('');
}
return word;
};
Greetings!
String.prototype.addspace = function () {
var arr = this.split("");
var len = arr.length;
maxSp = 4;
for(var i = 0; i <= len; i++){
m = Math.floor(Math.random() * (maxSp + 1));
for(var j = 0; j < m ; j++){
arr.splice(i,0," ");
}
len += m;
i +=m;
}
return arr.join("");
}
alert("Juanito".addspace().shuffle());

Categories

Resources