Mix up array with a spin

During the creation of a grid layout, I encountered an issue with shuffling the xposArray after correctly laying out the tiles.

 populateXPosArray:function(){
        var i = arr.length;

        for(j=0;j<i;j++){

            if((j % cols) === 0){
                ypos += 70;//height of the tile
                xpos = 0;
            }
            xposArray.push(xpos);
            xpos += 70;//width of the tile

        }

        //tryApp.shuffleArray(xposArray);

        console.log("xPosArray : " + xposArray);//returns 0,70,140,210, 280,0,70,140,210,280,0,70,140,210,280,0,70,140,210,280,0,70,140,210, 280
    },

    shuffleArray:function(array){
        //Fisher–Yates shuffle    
        var m = array.length, t, i;
        // While there remain elements to shuffle…
        while (m) {
            // Pick a remaining element…
            i = Math.floor(Math.random() * m--);

            // And swap it with the current element.
            t = array[m];
            array[m] = array[i];
            array[i] = t;
        }

        return array;
    },

Initially, the tiles are laid out perfectly in a 5 column 5 row grid. However, when using the shuffleArray function, the shuffled array is returned as shown below, which is not the desired outcome due to duplicated values within each group of 5.

 (280,140,140,140,210),(70,70,280,280,210),(0,140,210,0,140),(210,210,70,70,0),(70,0,0,280,280)

To avoid duplicate values within each group of 5, is it possible to shuffle only the first 5 elements and then proceed to the next 5, ensuring uniqueness within each set? An example of the desired output would be:

 (0,280,140,70,210),(70,0,210,140,280),(280,210,140,70,0),(210,70,140,280,0),(140,210,280,0,70);

Answer №1

To increase efficiency, divide the array into N sections and apply the shuffle function to each subsection.

function separate(arr, num) {
    var length = arr.length, output = [], index = 0;
    while (index < length) {
        var portionSize = Math.ceil((length - index) / num--);
        output.push(arr.slice(index, index + portionSize));
        index += portionSize;
    }
    return output;
}

var xChunks = separate(xposArray, 5);
var yChunks = xChunks.map(shuffleArray);
var flattened_array = [];
var finalResult = flattened_array.concat.apply(flattened_array, yChunks);

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

Complete guide on updating table styles by implementing a dark mode toggle button

I recently implemented a dark mode toggle button in my project after watching a tutorial on YouTube. Here is the HTML code for it: <div class="dark-div"> <input type="checkbox" class="checkbox" id="chk" ...

Setting a minimum and maximum date in a datepicker for a datetime variable

When trying to retrieve the date time of 06/03/2014 12:00:00 AM with an end date of 31/03/2015 12:00:00 AM, I encountered an issue where my jQuery alert message shows /9413044200000/. I am not sure what is causing this problem and I need assistance in sett ...

Is your pure function component not receiving or responding to input props correctly?

Here is my code snippet: const actionCreators = { action: AppReducer.actionCreators.action } interface GlobalState { user: Model.User | null; } interface InputState { setStashBarWidth(width: number); stashWidth: number; } const Header = ...

How can you identify and detect the id of an li element that has been loaded from a JSON

I've got a ul element filled with li elements that were fetched from a json file. My goal is to pass certain data from that json file to another page (a jquery mobile page) based on the id of the clicked li element. However, I'm facing issues in ...

Is there a way to connect and interact with a different ng-controller's ng-model within a separate ng-controller?

Is it possible to access the ng-model from another ng-controller and if so, how can it be done? In this scenario, I am using two controllers. The first controller has a model called mddl1, while the second controller does not have any other model. However, ...

How to feed images to Angular's UI Bootstrap Carousel

In my current project, I am incorporating the Angular UI Bootstrap carousel and want to customize it by using my own images. Below is the code snippet for the Carousel Controller that I have implemented: .controller('CarouselCtrl', function ($sc ...

Switching image source using JavaScript with a button click

I am working on a code where I need to change the image source by clicking a button and also increment the counter to display the next photo. However, I am currently facing an issue where only the first photo is being displayed out of the 8 available image ...

Testing Jest with NodeJS involves simulating input from standard input (stdin)

I'm currently working on a command-line application that takes user input from standard input using the following code: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, }); rl.on('li ...

What are some ways to adjust the sequence in which express Middleware is executed?

Two API's, /api1 and /api2 have been created along with four middlewares - validate1, validate 2, validationResult, checkAdmin. The routes are now excessively long and I'm looking for a way to keep them clean. router.post('/api1', vali ...

Utilizing a StyledComponents theme within a Component

When creating a style called Link, the theme is contained inside of this.props. How can the theme be extracted from props and passed into the Link styled component? Error: ReferenceError - theme is not defined import React from 'react'; impo ...

Revamp your Three.js scene by simply clicking a link to switch views

Is there a way to configure a Three.js scene so that clicking on a link can change the scene's view? I assumed it would be simple to create a function to modify the scene and then call that function through a link, but I have been unable to make it wo ...

What do you think the purpose of __N() is in the code snippet std::__throw_out_of_range(__N("array::at"))?

While studying the at() function's definition in the array header file, I stumbled upon something intriguing. Let's take a closer look at the code- reference //typedef for &value_type of array at(size_type __n) //s ...

Issues with the functionality of the submit button (html, js, php)

Seeking assistance with a submit button functionality issue - I have a simple submit button that allows visitors to enter their email address. Upon clicking the button, it should add their email to a CSV file and display a pop-up thank you message. The pr ...

What is the best way to incorporate background audio in Next.js?

I'm working on a project using Next.js and have encountered an issue with my audio player. Whenever the page is reloaded or left, the audio stops playing. I've tried using an iframe to keep the audio playing in the background, but it prompts me t ...

I encountered an issue while attempting to implement a mongoose Schema in my program. I keep receiving an error stating that "User is not a constructor

When attempting to utilize the mongoose Schema within my program, I consistently encounter an error stating that User is not a constructor. The reason behind this issue remains unclear to me... This excerpt displays the current content of my 'api.js ...

Utilizing Selenium to locate an element by its class name and then deleting it from the document object model through

I have found a code that worked really well for me. It involves getting the quantity of messages first and then removing them from the DOM. public static void RemoveMessages() { // Removing messages from the DOM using JavaScript ...

Load components dynamically based on list of identifiers

With over 100 components at my disposal, not all of them will be needed on a single page. For instance, a user might select a list of component IDs (components_ids - [7, 50, 22]). When the page is visited, I will only load the components with IDs that ...

Transforming JavaScript's POST Ajax into AngularJS' POST Factory

I am attempting to convert an Ajax call with WSSE authentication into an AngularJS factory. The request method is Post. The purpose of this conversion is to access the Adobe Analytics Rest API, retrieve data in JSON format, and then visualize it using d3. ...

Utilizing deferred to ensure that one function completes before triggering a refresh

In my JavaScript code, I have an ajax call that receives a GUID from the server-side code in the response. After getting the GUID successfully, it is used to make a call to an iframe. The ultimate goal is to refresh the page once the iframe has completed i ...