jvb
jvb

Reputation: 59

Reversing a integer value list

I have a list of integer values which can be anywhere between 1 and 4. So, let's say {1,2,4,1,3,2,1,4,4} for instance. I now want to reverse the values in the following way: All entries with ...

There are numerous ways to do this but I want to take the most efficient approach.

Any thoughts?

Upvotes: 3

Views: 170

Answers (6)

Sergii Zagriichuk
Sergii Zagriichuk

Reputation: 5399

I think good way to write rules of convert and using this rules perform converting.

Upvotes: 0

Akram Shahda
Akram Shahda

Reputation: 14781

Try the following:

var result = list.Select(item => 5 - item);

Upvotes: 1

CloudyMarble
CloudyMarble

Reputation: 37566

Implement this function:

f(x) = 5 - x

Upvotes: 2

Alxandr
Alxandr

Reputation: 12423

I don't know about efficiency, but I'm thinking that first filtering out all duplicates (think there's a LINQ-extension-method for that), then sorting from smallest to biggest, and last creating a hash-map (Dictionary<int, int>) that holds the conversions. Then you can run trough the array like this:

for(int i = 0, l = sortedUniqueArray.Count; i < l; i++) {
    dict[sortedUniqueArray[i]] = sortedUniqueArray[l - i];
}

Or something like that. Then you can do the final replacement like this:

orgArray.Select(itm => dict[itm]);

Upvotes: 0

Stecya
Stecya

Reputation: 23266

for(int i = 0; i < array.Length; i++)
{
    array[i] = 5 - array[i];
}

Upvotes: 7

rerun
rerun

Reputation: 25495

The most efficient will be a for loop with a case statement but it won't be the most flexible or pretty to look at. Any solution you can come up this that only iterates the loop one time could be considered decent solutions since they will all be O(N) performing.

Upvotes: 1

Related Questions