Randomly relocating array elements into separate arrays

My task involves an array of numbers ranging from 1 to 60.

var originalArray = [1, 2, 3, 4 .... 58, 59, 60] // etc

The challenge is to split these numbers randomly into a specified number of arrays based on another number between 2 and 4. It is important for the outcome to be unique each time.

For instance:

distributeArray(2) should produce two arrays, each containing 30 randomly selected numbers from the original array.

distributeArray(3) should yield three arrays, each with 20 numbers chosen randomly from the original array.

This scenario may be common, so any advice or guidance would be greatly appreciated. Thank you in advance.

Answer №1

If you're looking to create randomized splits of an array, consider this approach: first shuffle the array and then divide it into n equal parts.

var newArr = [...Array(61).keys()].slice(1)

function splitRandomized(data, numParts) {
  var seenIndices = [];
  var count = 0;

  var shuffledArr = data.reduce(function(result, element) {
    function getRandomIndex() {
      var randIndex = parseInt(Math.random(0, arr.length) * arr.length);
      if (seenIndices.indexOf(randIndex) != -1) {
        return getRandomIndex();
      } else {
        seenIndices.push(randIndex);
        return randIndex;
      }
    }

    result[getRandomIndex()] = element;
    return result;
  }, []);

  var splitResult = shuffledArr.reduce(function(result, element) {
    var index = count++;
    result[index] = result[index].concat(element);
    count = count % numParts;
    return result;
  }, Array(numParts).fill([]));

  return splitResult;
}

console.log(JSON.stringify(splitRandomized(newArr, 3)));
console.log(JSON.stringify(splitRandomized(newArr, 10)));
console.log(JSON.stringify(splitRandomized(newArr, 50)));

Answer №2

To generate a function that can create arrays of random lengths and distribute elements among them in a randomized manner, you can use the following approach. First, initialize two arrays - one for storing original values and another to hold the final result. Then, utilize a combination of loops and array manipulation methods like splice and push to achieve the desired distribution.

const distributeArrays = (n, x) => {
  
  let [originalArray, result, len] = [
    Array.from({length: n}, (_, key) => key)
  , Array.from({length: x}, () => [])
  , Math.ceil(n / x)
  ];
  do {
    let [curr, index] = [
      originalArray
      .splice(Math.floor(Math.random() * originalArray.length), 1)
      .pop()
      , Math.floor(Math.random() * result.length)
    ];
    if (result[index].length < len)
      result[index].push(curr);
    else
      for (let i = 0; i < result.length; i++) {
        if (result[i].length < len) {
          result[i].push(curr);
          break;
        }
      }
  } while (originalArray.length);
  
  return result
  
}

console.log(
  distributeArrays(60, 3)
  , distributeArrays(21, 7)
  , distributeArrays(5, 3)
  , distributeArrays(27, 5)
);

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

Using placeholders for multi-statement queries in Node.js with MySQL

I've reached the final stages of my project. The only thing left to do is to write the final query to the database. I want to use placeholders for this, but I'm not sure how to do it correctly in a multi-statement query. This is the query I have ...

What is the best way to display "No results found" in Mat-select-autocomplete?

I am working with the mat-select-autocomplete for a multiselect dropdown. When searching for values that are not in the list, I want to display a message saying "No results found". Can someone please help me achieve this? Link to Code ...

Storing data efficiently with Angular 2's local storage service

I am attempting to create a ToDoList using localstorage within a service. add.component.ts export class AddComponent implements OnInit { item: Item[]; constructor( private router: Router, private itemService: ItemService) { } ...

How can I transform a javascript object into a fresh array object?

Could you assist me with transforming JSON data? The initial structure is as follows: [ { "_id": "606f990042cc89060c54a632", "number": 1293, "date": "2021-04-08", "__v": 0 }, ...

JavaScript does not function properly on dynamically loaded content from AJAX requests and it is not relying on

I am currently using ajax to load all content from 'mysite/math/' into math.php. I want to render the loaded math content using katex. KaTeX GitHub Inside math.php, I include the Katex library from the CDN mentioned in the link above. The HTML ...

Using jQuery to search for corresponding JSON keys in the PokéAPI

Currently, in my development of an app, I am searching for and implementing an English translation of a language JSON endpoint using the PokéAPI. The challenge lies in identifying the correct location of the English language key within the array response, ...

I am attempting to create a skybox, yet it seems like I am overlooking a crucial element

Currently, I am attempting to create a skybox but have encountered difficulties with various tutorials. Initially, I tried to use an array approach to pass parameters for the material based on a previous example, but it seems that the method has been updat ...

Toggling the legend and row on click functionality in Google charts

I have a specific requirement that involves a Google chart: Once a Google chart is loaded, I need the ability to click on a legend, which will then gray out the legend and remove its corresponding value from the graph. If I click on the grayed-out le ...

Beginning your journey with Mock server and Grunt

Although I have gone through the documentation available at , I am still struggling to get the mockserver up and running despite spending hours on following the instructions provided in the guide. Could someone please outline the precise steps or identify ...

The value of the cookie is not set (version 2.0.6 of react-cookie)

I am encountering an issue with implementing react cookies version 2. I am using webpack-dev-server for testing. Below is the console log: Warning: Failed context type: The context cookies is marked as required in withCookies(App), but its value is unde ...

Having trouble getting the Bootstrap 5 Modal to function properly within an Electron app

Facing an issue with my web app using Bootstrap 5, as the modal is not displaying properly. Below is the HTML code for the modal and the button that triggers it: <div class="modal" tabindex="-1" id=&quo ...

What are the steps to create a responsive Coin Slider?

Once the slider is generated, it appears that there is no built-in method to resize it, causing issues with responsive design. Is there a way to adjust the size of the Coin Slider plugin based on the media queries in Twitter Bootstrap 3? Take a look at C ...

Align the reposition button with the pagination in the datatables

I am looking to adjust the placement of my buttons. The buttons in question are for comparison, saving layout, and printing. I would like them to be inline with the pagination, as I am using datatables here. <table id="sparepart_id" cellspacing="0" ...

The event was triggered, however, some sections of the code did not run

I am currently working on a project called lan-info on GitHub. Here is the code snippet that I am using: let arpSweepCommand = './arpSweep.sh'; app.get('/arp', (req, res) => { console.log('we have a working signal!'); ...

I encountered an issue while generating a crypto address on the Waves blockchain using the @waves/waves-crypto library in TypeScript

Encountering an issue with finding "crypto-js" in "@waves/waves-crypto". Despite attempts to uninstall and reinstall the module via npm and importing it using "*wavesCrypto", the error persists within the module's index.d.ts file. I am attempting to ...

Unable to transform the singular JSON object received from the server into the necessary format in order to analyze the data

Forgive me if my questions seem simple, as I am new to working with Angular. I'm having trouble understanding how to handle a JSON object received from the server and convert it into a custom datatype to use for rendering HTML using ngFor. I've ...

Difficulty understanding D3 Angular: color fill remains unchanged

While developing an angular application with D3 JS, I encountered an issue with changing the fill color of an SVG. Upon reviewing the code, I noticed that I created one SVG and attempted to insert another one from a vendor: function link (scope, element, ...

After retrieving data, React can update specific key values in an array of objects within a datatable row by replacing them with aster

I am currently working on a project that involves displaying data in a datatable/datagrid using an array of objects with various values. I need to find a way to specifically target a certain object or column within the table and change its row value from t ...

When a user hovers over an element, display text in a particular div

I've been experimenting with different methods to achieve this, but nothing seems to be working for me. The idea is that when I hover over a specific div like "divOne" or "divTwo", I want a text to appear in the "writeToMe" div. After spending several ...

Using the duplicate feature in MongoDB to display various fields

db.collection.aggregate([{"$group" : {"_id": "$fieldA", "count": {"$sum": 1}}},{"$match":{"_id" :{"$ne":null}, "count" : {"$gt":1}}},{"$project": ...