When provided with an index, rearrange the elements of the array by swapping

My goal is to create a behavior similar to that of a radio group, where only one option can be selected at a time. For instance, if we start with the array [0, 1, 1, 1, 1, 1], the elements should be rearranged as follows:

index array
0 [0, 1, 1, 1, 1, 1]
1 [1, 0, 1, 1, 1, 1]
2 [1, 1, 0, 1, 1, 1]
3 [1, 1, 1, 0, 1, 1]
4 [1, 1, 1, 1, 0, 1]
5 [1, 1, 1, 1, 1, 0]

I have developed a solution for this, but I believe it involves "extra work" in certain scenarios due to unnecessary loops.

function rearrange(array: number[], idx: number) {
  let arr = array.slice();
  let l = arr.length;
  if (arr.indexOf(0) === idx) return arr;

  while (arr.indexOf(0) !== idx) {
    let swap;
    for (let i = 0; i < l; i++) {
      if (arr[i] === 0 || arr[i + 1] === 0) {
        swap = arr[i];
        if (i + 1 < l) {
          arr[i] = arr[i + 1];
          arr[i + 1] = swap;
        }
        if (i + 1 > l) {
          arr[i] = arr[i - 1];
          arr[i - 1] = swap;
        }
      }
    }
  }

  return arr;
}

If you have any ideas on how to simplify or improve this process, please share them.

Answer №1

Simply use the findIndex method to locate the previous 0, replace it with 1, and then assign 0 to the index idx.

function rearrange(array: number[], idx: number) {
  const arr = [...array];
  arr[arr.indexOf(0)] = 1;
  arr[idx] = 0;
  return arr;
}

Here's another way to go about it...

const rearrange = (array: number[], idx: number) => (
  array.map((_, i) => i === idx ? 0 : 1)
);

Answer №2

If you want to avoid swapping pairs, try rotating a subarray in a single step by using slice and splice methods.

Check out this handy function that modifies the original array instead of creating a new one. Here are some examples to illustrate its usage. It's designed to keep values connected as if they were moved like with a "moving" zero:

function reposition(array, index) {
  let zeroIndex = array.indexOf(0);
  if (zeroIndex < index) {
      arr.splice(zeroIndex, index - zeroIndex + 1, ...arr.slice(zeroIndex + 1, index + 1), 0);
  } else {
      arr.splice(index, zeroIndex - index + 1, 0, ...arr.slice(index, zeroIndex));
  }
}

arr = [0,1,2,3,4,5];

reposition(arr, 3);
console.log(...arr);
reposition(arr, 1);
console.log(...arr);
reposition(arr, 5);
console.log(...arr);
reposition(arr, 1);
console.log(...arr);

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

dividing a matrix into sections (JAVA)

tag: I am working with an Array[n][n] where the size, n, is a power of two, and I am looking to recursively manage the quadrants of the array. Is there a way in Java to select a segment of the array that covers the elements from [0 to (size/2)][0 to (size ...

typescript - add a global library import statement to every script

Recently, I began working on a TypeScript project in Node.js. I am looking to add import 'source-map-support/register'; to all of my .ts files for better visibility of TS source in stack traces. Is there a method to implement this without manuall ...

A guide to converting hexadecimal to the 2^16 system using C++

Currently, I have a coding task that involves converting hexadecimal numbers N1 (str1) and N2 (str2) to a 2^16 system. The goal is to find the sum of these converted numbers in the 2^16 system and then translate the result back into a hexadecimal format. ...

The program was expecting an array to start, but instead encountered an object. Any suggestions on how to convert

{ "workingHours": [ { "date":"2023-02-01", "amount":3, "freigegeben":false } ] } Whenever I include this in my re ...

reading blocks of 2-byte integers

Currently, I am importing a file containing 2-byte-long integers into an array FILE *f = fopen("file.bin", "rb"); int *arr; int len = 2; The following method is functional: // Approach 1 for (int i = 0; i < numberOfElements; i++) fread(arr + i, ...

Angular is not displaying the data from the dynamically injected component in the main component

I have encountered an issue where I am attempting to showcase a component's HTML view within another component in a chatbot scenario. Let's refer to them as the chat component and component 2. Essentially, the chat component – responsible for r ...

Guide on posting an object in Angular through HTTP Post

I am attempting to send an object named Pack to my API Rest server using my Angular service. Below is the function I have set up for this task: save_pack(Pack: any){ return new Promise((resolve, reject) =>{ this.http .post("http://loca ...

The average calculation in the Numpy array did not account for excluding masked elements

I am a beginner in Python programming, so please bear with me if my question seems too basic. I am attempting to utilize masked_array in order to calculate the mean of three arrays and generate a third array without including elements with values less than ...

Error: Import statements can only be used within a module in NodeJS when using Typescript

Having trouble writing Jest tests in my Express Typescript application. Whenever I try to import functions from another file in the test files, I encounter a SyntaxError: Cannot use import statement outside a module. Here is an excerpt from my package.json ...

What is the best way to tally the JRadioButtons that have been chosen correctly and display a final "Score"?

My application is currently a Multiple choice quiz with only two questions to test the logic. Once I figure it out, I plan to add up to 100 questions. I have implemented a new Frame with buttons added to a panel, which is then added to the JFrame. Utilizin ...

Working with deeply nested objects in JavaScript

Given the following array structure: objNeeded = [ {onelevel: 'first'}, { onelevel: 'second', sublevels: [ {onelevel: 'domain'}, {onelevel: 'subdomain'} ] }, { ...

Issue with TypeScript while trying to define a property of a named function expression using 'let' instead of 'const'

As I continued my journey through the TypeScript handbook, I stumbled upon an intriguing concept while learning about Call Signatures. The code snippet provided in the handbook goes like this: type DescribableFunction = { description: string; (someArg: n ...

Exploring the process of importing and exporting modules in TypeScript with the help of systemjs

Is there a way to export a module using systemjs in TypeScript? I encountered the error: TS1148 cannot compile modules unless the '--module' flag is provided. Here's my code; animal.ts export class Animal { color: string; age: numb ...

Utilizing Next.js to create a Higher Order Component (HOC) for fetching data from a REST API using Typescript is proving to be a challenge, as the

In my withUser.tsx file, I have implemented a higher order component that wraps authenticated pages. This HOC ensures that only users with a specified user role have access to the intended pages. import axios, { AxiosError } from "axios"; import ...

A method for enabling mat-spinner's entrance animation

I have recently implemented an Angular Material spinner with a disappearing animation that moves downwards before fading away. Is there a way to disable this animation? I have already tried using keyframes without success. <mat-spinner style="margin: ...

Reasons why a functional component may not trigger a rerender after a state change using useReducer()

When using react Hooks, specifically useReducer, I found that although the state changes, the functional component does not rerender. Additionally, when trying to open the drawer by pressing a button in the menu, even though the state changes the drawer re ...

Retrieving the current day integer from a fullcalendar rendering in JavaScript and utilizing it as an array key

I am currently working on rendering a full calendar and I would like each cell to be displayed in a different color based on an array that contains color values for each day of the month. The array is retrieved in JSON format. Here is an example JSON arra ...

Is there a method to indicate type narrowing to TypeScript following an initial null/undefined validation?

After loading environment variables into my Node & Express app using 'dotenv', I take steps to ensure these values are present and of the correct type before starting the server. However, when attempting to use these variables later on, TypeScrip ...

What is the procedure for including a attribute in all sub-objects within a nested object using Typescript?

I need to create a function called addId that takes an object as input and returns the same object with an added property _id: string in every sub-object. Let's consider the input object constructed from the following class. class A { a: number b ...

Preventing the transformation of a one by n array into a one-dimensional array

Here is a snippet of code I created to manage arrays and ranges consistently (Accepting a range as an array parameter). It includes a function named sanitise designed for processing a 2D set of numbers A and returning the same numbers as a 2D array of Doub ...