Offset integer value list

I have a list of integer values, which can be from 1 to 4. So, let's say {1,2,4,1,3,2,1,4,4}, for example. Now I want to change the values ​​as follows: All records 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 many ways to do this, but I want to use the most efficient approach.

Any thoughts?

+3
source share
6 answers
for(int i = 0; i < array.Length; i++)
{
    array[i] = 5 - array[i];
}
+7
source

Implement this feature:

f (x) = 5 - x

+2
source

for case, . , , , , O (N).

+1

:

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

I do not know about efficiency, but I think that first filter out all duplicates (think if there is a LINQ-extension method for this), then sort from smallest to largest and last hash map creation (Dictionary <int, int>) that contains the transforms. Then you can run through the array as follows:

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

Or something like that. Then you can make the final replacement as follows:

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

I think a good way to write conversion rules and use these rules to perform the conversion.

0
source

All Articles