Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to rearrange an array and set arr[i] to arr[arr[index]] to index in TypeScript

1 Answer

0 votes
function rearrange_array(arr : any) {
	let size = arr.length;
    
    for (let i = 0; i < size; i++)
        arr[i] += (arr[arr[i]] % size) * size;
 
    for (let i = 0; i < size; i++)
        arr[i] = Math.floor(arr[i] / size);
}
 

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

// arr[arr[0]] = 2 -> arr[0] = 2
// arr[arr[1]] = 4 -> arr[1] = 4
// arr[arr[2]] = 3 -> arr[2] = 3
// arr[arr[3]] = 0 -> arr[3] = 0
// arr[arr[4]] = 5 -> arr[4] = 5
// arr[arr[5]] = 1 -> arr[5] = 1
 
rearrange_array(arr);
 
console.log(arr);
 
     
     
/*
run:
 
[2, 4, 3, 0, 5, 1] 
          
*/

 



answered Aug 17, 2022 by avibootz
...