Randomly select shapes from an array in Javascript

When trying to randomly select two or three shapes from an array, I encountered difficulties. Here is the code I attempted:

var range = _.sample(shapes, 2);

Although this code runs, it does not provide a truly random selection.

var range = shapes.length-2 * Math.random();

Answer №1

Update It appears that the question is specific to underscore.js, not arrays in general. Here's a brief update:

It seems like you're using the _.sample() function correctly, but make sure to treat the result as an array when selecting multiple values:

var shapes = ['circle','star','square','hexagon','triangle','polygon'];
var range = _.sample(shapes, 2);  // => ["square", "triangle"]; (example output)

Therefore, there's no need for using Math.random() to choose items since the selection is already random. Simply loop through the array to access each value.

Example

... other code ...

for(var i = 0, shape; shape = range[i]; i++) {  // will iterate through the range array

    switch(shape) {                             // current item
        case "square":                          // (not 0 etc. as in the original code)
            ... code for square here...
            break;

        case "triangle":
            ... code for triangle here...
            break;

        ... etc. ...
    }
} 

Old answer

Answer №2

This code snippet selects a random element from an array.

var shape = shapes[Math.floor(Math.random() * shapes.length)];

To make this process more user-friendly, you can convert it into a function like this:

function getRandomElement(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

Now, it becomes simple to pick multiple random elements from the array:

var shape1 = getRandomElement(shapes);
var shape2 = getRandomElement(shapes);

However, there's a chance that both shape1 and shape2 could be the same. To avoid this, we can modify the function to ensure uniqueness:

function getUniqueRandomElements(arr, count) {
  if (!count) count = 1;
  
  var copy = arr.slice(0);
  var result = [];
  
  for (var i=0; i<count; i++) {
    var index = Math.floor(Math.random() * copy.length);
    
    result = result.concat(copy.splice(index, 1));
  }
  
  return result;
}

With this version of the function, duplicates are eliminated:

var letters = ["a", "b", "c", "d", "e"];
getUniqueRandomElements(letters, 3); // ["e", "c", "b"]
getUniqueRandomElements(letters, 3); // ["e", "a", "d"]
getUniqueRandomElements(letters, 3); // ["c", "a", "b"]

A useful enhancement can be made to this code by incorporating card shuffling functionality. Consider these two approaches:

  1. Select 2 cards randomly from a sorted/unsorted deck
  2. Shuffle the deck and pick 2 cards from the top

The existing getUniqueRandomElements function aligns with method #1. By adjusting it to match method #2, we can obtain a shuffle function as well!

Here's how the modified function would look:

function getRandomNumber(x) {
  return Math.floor(Math.random() * x);
}

function shuffleCards(deck) {
  var copy = deck.slice(0);
  return deck.reduce(function(shuffledDeck, card) {
    var position = getRandomNumber(copy.length);
    return shuffledDeck.concat(copy.splice(position, 1));
  }, []);
}

function getUniqueRandomElements(arr, n) {
  return shuffleCards(arr).slice(0, n || 1);
}

By taking this approach, we achieve our initial goal while gaining reusable functions getRandomNumber and shuffleCards. This demonstrates the power of writing getUniqueRandomElements as a higher-order procedure! 🌟

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Comparison of the performance between using closure for array traversal versus a traditional for loop

Which is more efficient in terms of performance: array_walk($data, function($item){ // operation }); Alternatively, is it better to use: foreach($data as $item){ // operation } ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

How to enable sound on Internet Explorer Mobile 6

We are developing a web application designed to run on Internet Mobile Explorer 6. We are looking to incorporate sound feedback when the user makes an incorrect input. Are there any features supported on IE Mobile 6 that could help us achieve this? Any sug ...

Is it necessary to use asynchronous actions in Node.js only when developing server applications?

In the Node.js application I'm developing, there is a piece of code similar to this within an async function: await a(param1); await b(param2); await c(param3); await d(param4); From my understanding, this setup works well for a server-based app. Fo ...

Incorporating Up and Down Arrows Based on Order Classification

Is there a way to add arrow indicators beside table column names in HTML code when sorting them in ascending or descending order? The data is retrieved from a database using AJAX and PHP, displayed in a table format. I have already created a function to so ...

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

Creating dual modes (night/day) for your AngularJS application

Currently, I am in the process of developing a project with Angularjs and facing an obstacle with animations. My goal is to implement a feature in my application that allows it to display in two different modes - night mode and day mode. I have come ac ...

What is the best way to refresh the text within a span element?

Working on a web page where users can select an item by clicking a button. The chosen item's details will be shown in a dropbox. Currently, it updates the quantity if the user selects the same item again. However, there's an issue I'm facing ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Tips for efficiently handling multiple form inputs using PHP

As part of my project, I am designing an admin panel for a distribution company. They have specifically requested a feature where they can input orders for all clients through a single page. To meet this requirement, I have created a dynamic form that gene ...

Error encountered: The fiber texture failed to load due to a component becoming suspended during the response to synchronous input

I'm encountering an issue while attempting to load a texture through the TextureLoader: const texture = useLoader(TextureLoader, '/textures/texture.png') The error message I receive from react is as follows: ERROR A component suspended w ...

Implementing image-based autocomplete in a search bar within an MVC framework

Seeking assistance to implement a unique feature for my MVC application. I aim to create a search box that suggests images based on user input rather than text. The functionality involves matching the user's input with the "Title" property in an Ent ...

Issue with firestore IN query when encountering NULL value

Is there a way to create a query that retrieves all documents without a value, whether it be null or ''? Within my table are three documents, each containing a field called a. https://i.sstatic.net/FGV0Z.png During an IN query, the document wit ...

Is there a way to extract the HTML source code of a website using jQuery or JavaScript similar to PHP's file_get_contents function?

Can this be achieved without a server? $.get("http://xxxxx.com", function (data) { alert(data); }); I have tried the above code but it seems to not display any output. ...

Unable to transfer content to clipboard from a Popper element nested within a Dialogue component in Material-UI

If you want to see the bug, try opening this link in Firefox. It almost crashed Chrome :P https://codesandbox.io/s/73z5293391 Click on the OPEN SIMPLE DIALOGUE button. A dialogue will appear, then click on the TOGGLE POPPER button. Now a Popper will be d ...

What is the best way for a parent process to interrupt a child_process using a command?

I'm currently in the process of working on a project that involves having the user click on an 'execute' button to trigger a child_process running in the backend to handle a time-consuming task. The code snippet for this operation is shown b ...

One-click process succeeds where two clicks fail

The code below is intended to go through a two-click process as follows: First click on .imagenes decreases opacity and makes .logo visible. Second click on .imagenes returns the opacity to 1 and hides .logo again. However, during this cycle of two ...

How can React hook state be efficiently utilized in a debounced callback?

function Foo() { const [state, setState] = useState(0); const cb = useCallback(debounce(() => { console.log(state); }, 1000), []); return ...; } In the code snippet above, there is a potential issue where the state variable may become outda ...

Is there a way to save a collection of audio samples as a wav file using Node.js?

In my JavaScript code, I am developing an oscillator that generates a sweep (chirp) between different sine wave frequencies. To test this functionality, I would like to save the samples (which are in floating point format) to a WAV file. Can anyone provi ...

Error with react/display-name in ESLint when using dynamic imports in Next.js

I encountered an error message from ESLint that says: Component definition is missing display name This error occurred in the following code snippet: const Disqus = dynamic(() => import('@/components/blog/disqus'), { ssr: false, loading: ...