开发者

Reversing a integer value list

开发者 https://www.devze.com 2023-03-09 12:35 出处:网络
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 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. 开发者_StackOverflowI now want to reverse the values in the following way: All entries with ...

  • 1 should be converted to 4,
  • 2 should be converted to 3,
  • 3 should be converted to 2,
  • 4 should be converted to 1.

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

Any thoughts?


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


Implement this function:

f(x) = 5 - x


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.


Try the following:

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


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]);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消