classic_vmk
classic_vmk

Reputation: 505

Re position the item in an array based on the index order given in another array

I have two arrays as below.

string[] alb = new string[5] 
             {
                "B","Z","C", "E","T"
             };
int[] orderedIndexes = {0,3,4,1,2}

Based on the indexes given in second array I would like to align the items in the first array. I don't want to use another array as buffer and like to use the same array for swapping the items. The result am expecting is like

alb = {"B","E","T","Z","C"}. 

Note : As the real problem is having real business values I cannot post the homework I did.

Any help would be really appreciated.

Upvotes: 3

Views: 77

Answers (2)

James R.
James R.

Reputation: 840

The linq answer is absolutely great, but I thought it would be fun to solve it in an old-school array manipulation way. Besides, part of the question mentioned not creating a buffer, which to me, the linq answer violates somewhat. Anyway, for what it's worth...

using System;

namespace x
{
    class Program
    {
        static void Main()
        {
            var alb = new[] { "B","Z","C","E","T" };
            int[] orderedIndexes = {2,0,1,4,3};

            for (var i = 0; i < orderedIndexes.Length; i++)
            {
                var x = orderedIndexes[i];
                var ts = alb[i];
                alb[i] = alb[x];
                alb[x] = ts;
                x = Array.IndexOf(orderedIndexes, i);
                var ti = orderedIndexes[i];
                orderedIndexes[i] = orderedIndexes[x];
                orderedIndexes[x] = ti;
            }

            for (var i = 0; i < orderedIndexes.Length; i++)
            {
                Console.WriteLine("{0}, {1}", i, alb[i]);
            }
        }
    }
}

Upvotes: 3

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32511

First you should check if that index array is a valid index array like this:

var isValidIndex = !Enumerable.Range(0, alb.Length - 1).Except(orderedIndexes).Any();

Then you can simply use the Select on the orderedIndexes like this:

var result = orderedIndexes.Select(i => alb[i]).ToArray();

//result: {"B","E","T","Z","C"}

Upvotes: 1

Related Questions