Skip to content
Advertisement

Generate random letters “H” and “V” n times

I have a really specific problem and can’t think of an answer.

I have a function to generate a letter H or V.

I want to make that if the generator exceedes the limit for H to pick V and if the limit for V gets exceeded to pick H.

Example

Limit for H is 10 Limit for V is 10

JavaScript

the result would be the letter H 10 times and letter V 10 times.

This is my code

H5 = Limit for H number V5 = Limit for V number

JavaScript

EDIT

I have a for loop that loops like 20 times

JavaScript

I want to make it so that there is exactly 10 H and 10 V or any number i choose

This is the entire Code

worker.js Using Web Workers

JavaScript

Advertisement

Answer

Fill an array with 10 Hs, 10 Vs, then shuffle the array. Return consecutive elments from the array. Wrap everything in a closure, so that you do not pollute global state and can create differently parametrized “sequences”:

JavaScript

If you always need the same number of H’s and V’s, you could simply keep a single array and shuffle it each time before iterating (shuffling is O(n) and requires only 20 steps for 20 elements). This would avoid having to “generate” a new sequence every time.

Or you could split the “generator” and the “iterator” part, making it easy for you to reuse arrays and iterate a given sequence multiple times:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement