What are alternatives to this method
tmp = c[0];
c[0] = c[1];
c[1] = c[2];
c[2] = c[3];
c[3] = tmp;
to left rotate a char array with 4 elements
Using generics and rotating in place (thanks Jon Skeet for the suggestion):
static void Rotate<T>(T[] source)
{
var temp = source[0];
Array.Copy(source, 1, source, 0, source.Length - 1);
source[source.Length - 1] = temp;
}
These should work for any array of at least 2 length, and on any array.
If performance is critical and the arrays are always small, use this:
static void Rotate<T>(T[] source)
{
var temp = source[0];
for (int i = 0; i < source.Length - 1; i++)
source[i] = source[i + 1];
source[source.Length - 1] = temp;
}
The first method is the fastest with large arrays, but for 4 items, this one's almost as fast as your example method.
An alterantive to rotating the array, is to rotate the index when accessing the array, i.e you are creating a virtual ring
int origin = someValue;
int x = c[(i + origin) % c.Length];
I'm not sure if you're asking for a more efficient method or for an easier way to type that, but i'm going to try answering you assuming you want an easier way
so try:
int temp = c[0]
for(int i = 0; i < c.count; i++)
{
if (i == (c.count - 1))
{
c[i] = temp;
break;
}
c[i] = c[i + 1];
}
Do the job in single step.
Using System.Linq;
int[] ar = { 1,2,3,4,5};
int k = 1; //
int[] ar1= ar.Skip(k) // Start with the last elements
.Concat(ar.Take(k)) // Then the first elements
.ToArray();
Output-- 2,3,4,5,1
In ruby rotating array can be done in one line.
def array_rotate(arr)
i, j = arr.length - 1, 0
arr[j],arr[i], i, j = arr[i], arr[j], i - 1, j + 1 while(j<arr.length/2)
puts "#{arr}"
end
Related
Let's Say We Have an Array Of Int :
int[] array = new int[5];
and inside of this array we have a 5 randomly numbers..
array = {10,5,7,0,3};
What Would be The Best Way To Change That array To This Array By Code
array[0]=0;
array[1]=3;
array[2]=5;
array[3]=7;
array[4]=10;
For Me i Thought about Creating Two Loops One Of i and One of j..
im gonna take the position 0 (i) and compare it with All the Other Numbers in The Array. i mean The positions j which is started from (i+1) till the end of the array (array.Length).
Then When i'll found that array[i] is Upper Than array[j] Simply i'll Change The first Value with The Other...
and Of course Here i need To Declare variable To Make That Change as shown :
int[] array = new int[5]{10,5,7,0,3};
int Change;
for(int i =0;i<array.Lenght;i++)
{
for(int j =i+1;j<array.Lenght;j++)
{
if(array[i]>array[j])
{
change=array[i];
array[i] = array[j];
array[j] = change;
}
}
}
This is solve The Problem But even thought i don't Like That Logic || that Code
if you have another one Can You Tell Me About it ??
You can simply use Array.Sort method.
int[] array = new int[5] { 10, 5, 7, 0, 3 };
Array.Sort(array);
On OP's request, I am providing the optimized code. Here complexity is O(Square(N)). I would suggest you use merge sort or quick sort, these have complexity O(NLogN)
int[] array = new int[5] { 10, 5, 7, 0, 3 };
int change = 0;
for (int i = 0; i <= array.Length - 2; i++)
{
for (int j = 0; j <= array.Length - 2; j++)
{
if (array[j] > array[j + 1])
{
change = array[j + 1];
array[j + 1] = array[j];
array[j] = change;
}
}
}
I have a float array containing 1M floats
I want to do sampling: for each 4 floats I want to take only 1. So i am doing this :
for(int i = 0; i< floatArray.Length; i++) {
if(i % 4 == 0) {
resultFloat.Add(floatArray[i])
}
}
This works fine, but it takes much time to run through all the elements , is there any other methods to make it with better results (if there are any)
I can see two factors that might be slowing down performance.
As you have already been offered, you should set the step to 4:
for (int i = 0; i < floatArray.Length; i += 4)
{
resultFloat.Add(floatArray[i]);
}
Looks like resultFloat is a list of float. I suggest to use array instead of list, like this:
int m = (floatArray.Length + 3) / 4;
float[] resultFloat = new float[m];
for (int i = 0, k = 0; i < floatArray.Length; i += 4, k++)
{
resultFloat[k] = floatArray[i];
}
Just increment your loop by 4 each iteration instead of by 1:
for(int i = 0; i< floatArray.Length; i+=4)
{
resultFloat.Add(floatArray[i]);
}
If you really have an issue with performance, then you'd be even better off not using a dynamic container for the results, but a statically sized array.
float[] resultFloat = new float[(floatArray.Length + 3) >> 2];
for(int i = 0; i < resultFloat.Length; i++)
resultFloat[i] = floatArray[i << 2];
Usually performance isn't an issue thow, and you shouldn't optimize until a profiler gave you proof that you should. In all other cases the more readable code is preferrable.
Just to add another option, if you want this to be the fastest, use Parallel.For instead of a normal for loop.
int resultLength = (floatArray.Length + 3) / 4;
var resultFloat = new float[resultLength];
Parallel.For(0, resultLength, i =>
{
resultFloat[i] = floatArray[i * 4];
});
List<decimal> list = new List<decimal>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
list.Add(6);
list.Add(7);
list.Add(8);
list.Add(9);
list.Add(10);
list.Add(11);
list.Add(12);
list.Add(13);
list.Add(14);
list.Add(15);
list.Add(16);
var sampleData = list.Where((x, i) => (i + 1) % (4) == 0).ToList();
If A, B, and C are all classes in memory and the array is elements 0-2:
[0] = A
[1] = B
[2] = C
I want to shift the array so that it turns into this:
[0] = C
[1] = A
[2] = B
I would want to be able to go either direction, but I'd assume if someone could point me towards how to do it in one direction I can figure out the other.
Thought I should mention, I need this without iteration if at all possible.
This is for a 3D game of pseudo-infinite terrain. Each object in the arrays are chunks of terrain data. I want to shift them as they contain extremely large jagged arrays with a significant amount of data each. As the player moves, I have terrain sliding (in to/out of) memory. I never considered the performance hit of doing only an array.copy to shift arrays followed by completely rebuilding the next series of chunks.
So to eliminate this relatively minor performance issue, I wanted to shift the arrays with wrapping as described and instead of rebuilding the whole next series of chunks by re-allocating memory, I'm going to re-use the huge jagged arrays mentioned by copying default values into them rather than completely reinitializing them.
For kicks so you can see what I was doing before:
public void ShiftChunks(strVector2 ChunkOffset) {
while (ChunkOffset.X < 0) {
Array.Copy(Chunks, 0, Chunks, 1, Chunks.Length - 1);
for (int X = 1; X < maxChunkArraySize; X++)
for (int Z = 0; Z < maxChunkArraySize; Z++)
Chunks[X][Z].SetArrayPosition(X, Z);
Chunks[0] = new clsChunk[maxChunkArraySize];
for (int Z = 0; Z < maxChunkArraySize; Z++)
Chunks[0][Z] = new clsChunk(0, Z);
ChunkOffset.X++;
}
while (ChunkOffset.X > 0) {
Array.Copy(Chunks, 1, Chunks, 0, Chunks.Length - 1);
for (int X = 0; X < maxChunkArraySize - 1; X++)
for (int Z = 0; Z < maxChunkArraySize; Z++)
Chunks[X][Z].SetArrayPosition(X, Z);
Chunks[maxChunkArraySize - 1] = new clsChunk[maxChunkArraySize];
for (int Z = 0; Z < maxChunkArraySize; Z++)
Chunks[maxChunkArraySize - 1][Z] = new clsChunk(maxChunkArraySize - 1, Z);
ChunkOffset.X--;
}
while (ChunkOffset.Z < 0) {
for (int X = 0; X < maxChunkArraySize; X++) {
Array.Copy(Chunks[X], 0, Chunks[X], 1, Chunks[X].Length - 1);
for (int Z = 1; Z < maxChunkArraySize; Z++)
Chunks[X][Z].SetArrayPosition(X, Z);
Chunks[X][0] = new clsChunk(X, 0);
}
ChunkOffset.Z++;
}
while (ChunkOffset.Z > 0) {
for (int X = 0; X < maxChunkArraySize; X++) {
Array.Copy(Chunks[X], 1, Chunks[X], 0, Chunks[X].Length - 1);
for (int k = 0; k < maxChunkArraySize - 1; k++)
Chunks[X][k].SetArrayPosition(X, k);
Chunks[X][maxChunkArraySize - 1] = new clsChunk(X, maxChunkArraySize - 1);
}
ChunkOffset.Z--;
}
}
If anyone would like to give opinions on how I might do this even better or how to optimize the code further, feel free to let me know.
static void Rotate<T>(T[] source)
{
var temp = source[source.Length - 1];
Array.Copy(source, 0, source, 1, source.Length - 1);
source[0] = temp;
}
I happen to have created the exact thing for this just a few days ago:
private static T[] WrapAround<T>(T[] arr, int amount) {
var newArr = new T[arr.Length];
while (amount > 1) {
for (var i = 0; i < arr.Length; i++) {
if (i != 0) {
newArr[i] = arr[i - 1];
}
if (i == 0) {
newArr[i] = arr[arr.Length - 1];
}
}
arr = (T[]) newArr.Clone();
amount--;
}
return newArr;
}
Edit: Actually, #Matthias' solution is a lot easier.. You might want to use that instead.
Here's a function that will rotate an array by any offset in either direction (up to +/- length of the array) using just Array.Copy().
This is an extension of Matthias's answer above. It allocates a temporary array with the size of the offset to deal with wrapping.
void Rotate<T>(T[] array, int offset) {
if (offset==0) return;
if (offset>0) {
var temp = new T[offset];
System.Array.Copy(array, array.Length-offset, temp, 0, offset);
System.Array.Copy(array, 0, array, offset, array.Length-offset);
System.Array.Copy(temp, 0, array, 0, offset);
}else{
var temp = new T[-offset];
System.Array.Copy(array, 0, temp, 0, -offset);
System.Array.Copy(array, -offset, array, 0, array.Length+offset);
System.Array.Copy(temp, 0, array, array.Length+offset, -offset);
}
}
However, for the use case you described, it might be faster to not shift the array at all, but rather use a cyclical index when retrieving your data.
I heard about Counting Sort and wrote my version of it based on what I understood.
public void my_counting_sort(int[] arr)
{
int range = 100;
int[] count = new int[range];
for (int i = 0; i < arr.Length; i++) count[arr[i]]++;
int index = 0;
for (int i = 0; i < count.Length; i++)
{
while (count[i] != 0)
{
arr[index++] = i;
count[i]--;
}
}
}
The above code works perfectly.
However, the algorithm given in CLRS is different. Below is my implementation
public int[] counting_sort(int[] arr)
{
int k = 100;
int[] count = new int[k + 1];
for (int i = 0; i < arr.Length; i++)
count[arr[i]]++;
for (int i = 1; i <= k; i++)
count[i] = count[i] + count[i - 1];
int[] b = new int[arr.Length];
for (int i = arr.Length - 1; i >= 0; i--)
{
b[count[arr[i]]] = arr[i];
count[arr[i]]--;
}
return b;
}
I've directly translated this from pseudocode to C#. The code doesn't work and I get an IndexOutOfRange Exception.
So my questions are:
What's wrong with the second piece of code ?
What's the difference algorithm wise between my naive implementation and the one given in the book ?
The problem with your version is that it won't work if the elements have satellite data.
CLRS version would work and it's stable.
EDIT:
Here's an implementation of the CLRS version in Python, which sorts pairs (key, value) by key:
def sort(a):
B = 101
count = [0] * B
for (k, v) in a:
count[k] += 1
for i in range(1, B):
count[i] += count[i-1]
b = [None] * len(a)
for i in range(len(a) - 1, -1, -1):
(k, v) = a[i]
count[k] -= 1
b[count[k]] = a[i]
return b
>>> print sort([(3,'b'),(2,'a'),(3,'l'),(1,'s'),(1,'t'),(3,'e')])
[(1, 's'), (1, 't'), (2, 'a'), (3, 'b'), (3, 'l'), (3, 'e')]
It should be
b[count[arr[i]]-1] = arr[i];
I'll leave it to you to track down why ;-).
I don't think they perform any differently. The second just pushes the correlation of counts out of the loop so that it's simplified a bit within the final loop. That's not necessary as far as I'm concerned. Your way is just as straightforward and probably more readable. In fact (I don't know about C# since I'm a Java guy) I would expect that you could replace that inner while-loop with a library array fill; something like this:
for (int i = 0; i < count.Length; i++)
{
arrayFill(arr, index, count[i], i);
index += count[i];
}
In Java the method is java.util.Arrays.fill(...).
The problem is that you have hard-coded the length of the array that you are using to 100. The length of the array should be m + 1 where m is the maximum element on the original array. This is the first reason that you would think using counting-sort, if you have information about the elements of the array are all minor that some constant and it would work great.
I have a datastructure with a field of the float-type. A collection of these structures needs to be sorted by the value of the float. Is there a radix-sort implementation for this.
If there isn't, is there a fast way to access the exponent, the sign and the mantissa.
Because if you sort the floats first on mantissa, exponent, and on exponent the last time. You sort floats in O(n).
Update:
I was quite interested in this topic, so I sat down and implemented it (using this very fast and memory conservative implementation). I also read this one (thanks celion) and found out that you even dont have to split the floats into mantissa and exponent to sort it. You just have to take the bits one-to-one and perform an int sort. You just have to care about the negative values, that have to be inversely put in front of the positive ones at the end of the algorithm (I made that in one step with the last iteration of the algorithm to save some cpu time).
So heres my float radixsort:
public static float[] RadixSort(this float[] array)
{
// temporary array and the array of converted floats to ints
int[] t = new int[array.Length];
int[] a = new int[array.Length];
for (int i = 0; i < array.Length; i++)
a[i] = BitConverter.ToInt32(BitConverter.GetBytes(array[i]), 0);
// set the group length to 1, 2, 4, 8 or 16
// and see which one is quicker
int groupLength = 4;
int bitLength = 32;
// counting and prefix arrays
// (dimension is 2^r, the number of possible values of a r-bit number)
int[] count = new int[1 << groupLength];
int[] pref = new int[1 << groupLength];
int groups = bitLength / groupLength;
int mask = (1 << groupLength) - 1;
int negatives = 0, positives = 0;
for (int c = 0, shift = 0; c < groups; c++, shift += groupLength)
{
// reset count array
for (int j = 0; j < count.Length; j++)
count[j] = 0;
// counting elements of the c-th group
for (int i = 0; i < a.Length; i++)
{
count[(a[i] >> shift) & mask]++;
// additionally count all negative
// values in first round
if (c == 0 && a[i] < 0)
negatives++;
}
if (c == 0) positives = a.Length - negatives;
// calculating prefixes
pref[0] = 0;
for (int i = 1; i < count.Length; i++)
pref[i] = pref[i - 1] + count[i - 1];
// from a[] to t[] elements ordered by c-th group
for (int i = 0; i < a.Length; i++){
// Get the right index to sort the number in
int index = pref[(a[i] >> shift) & mask]++;
if (c == groups - 1)
{
// We're in the last (most significant) group, if the
// number is negative, order them inversely in front
// of the array, pushing positive ones back.
if (a[i] < 0)
index = positives - (index - negatives) - 1;
else
index += negatives;
}
t[index] = a[i];
}
// a[]=t[] and start again until the last group
t.CopyTo(a, 0);
}
// Convert back the ints to the float array
float[] ret = new float[a.Length];
for (int i = 0; i < a.Length; i++)
ret[i] = BitConverter.ToSingle(BitConverter.GetBytes(a[i]), 0);
return ret;
}
It is slightly slower than an int radix sort, because of the array copying at the beginning and end of the function, where the floats are bitwise copied to ints and back. The whole function nevertheless is again O(n). In any case much faster than sorting 3 times in a row like you proposed. I dont see much room for optimizations anymore, but if anyone does: feel free to tell me.
To sort descending change this line at the very end:
ret[i] = BitConverter.ToSingle(BitConverter.GetBytes(a[i]), 0);
to this:
ret[a.Length - i - 1] = BitConverter.ToSingle(BitConverter.GetBytes(a[i]), 0);
Measuring:
I set up some short test, containing all special cases of floats (NaN, +/-Inf, Min/Max value, 0) and random numbers. It sorts exactly the same order as Linq or Array.Sort sorts floats:
NaN -> -Inf -> Min -> Negative Nums -> 0 -> Positive Nums -> Max -> +Inf
So i ran a test with a huge array of 10M numbers:
float[] test = new float[10000000];
Random rnd = new Random();
for (int i = 0; i < test.Length; i++)
{
byte[] buffer = new byte[4];
rnd.NextBytes(buffer);
float rndfloat = BitConverter.ToSingle(buffer, 0);
switch(i){
case 0: { test[i] = float.MaxValue; break; }
case 1: { test[i] = float.MinValue; break; }
case 2: { test[i] = float.NaN; break; }
case 3: { test[i] = float.NegativeInfinity; break; }
case 4: { test[i] = float.PositiveInfinity; break; }
case 5: { test[i] = 0f; break; }
default: { test[i] = test[i] = rndfloat; break; }
}
}
And stopped the time of the different sorting algorithms:
Stopwatch sw = new Stopwatch();
sw.Start();
float[] sorted1 = test.RadixSort();
sw.Stop();
Console.WriteLine(string.Format("RadixSort: {0}", sw.Elapsed));
sw.Reset();
sw.Start();
float[] sorted2 = test.OrderBy(x => x).ToArray();
sw.Stop();
Console.WriteLine(string.Format("Linq OrderBy: {0}", sw.Elapsed));
sw.Reset();
sw.Start();
Array.Sort(test);
float[] sorted3 = test;
sw.Stop();
Console.WriteLine(string.Format("Array.Sort: {0}", sw.Elapsed));
And the output was (update: now ran with release build, not debug):
RadixSort: 00:00:03.9902332
Linq OrderBy: 00:00:17.4983272
Array.Sort: 00:00:03.1536785
roughly more than four times as fast as Linq. That is not bad. But still not yet that fast as Array.Sort, but also not that much worse. But i was really surprised by this one: I expected it to be slightly slower than Linq on very small arrays. But then I ran a test with just 20 elements:
RadixSort: 00:00:00.0012944
Linq OrderBy: 00:00:00.0072271
Array.Sort: 00:00:00.0002979
and even this time my Radixsort is quicker than Linq, but way slower than array sort. :)
Update 2:
I made some more measurements and found out some interesting things: longer group length constants mean less iterations and more memory usage. If you use a group length of 16 bits (only 2 iterations), you have a huge memory overhead when sorting small arrays, but you can beat Array.Sort if it comes to arrays larger than about 100k elements, even if not very much. The charts axes are both logarithmized:
(source: daubmeier.de)
There's a nice explanation of how to perform radix sort on floats here:
http://www.codercorner.com/RadixSortRevisited.htm
If all your values are positive, you can get away with using the binary representation; the link explains how to handle negative values.
By doing some fancy casting and swapping arrays instead of copying this version is 2x faster for 10M numbers as Philip Daubmeiers original with grouplength set to 8. It is 3x faster as Array.Sort for that arraysize.
static public void RadixSortFloat(this float[] array, int arrayLen = -1)
{
// Some use cases have an array that is longer as the filled part which we want to sort
if (arrayLen < 0) arrayLen = array.Length;
// Cast our original array as long
Span<float> asFloat = array;
Span<int> a = MemoryMarshal.Cast<float, int>(asFloat);
// Create a temp array
Span<int> t = new Span<int>(new int[arrayLen]);
// set the group length to 1, 2, 4, 8 or 16 and see which one is quicker
int groupLength = 8;
int bitLength = 32;
// counting and prefix arrays
// (dimension is 2^r, the number of possible values of a r-bit number)
var dim = 1 << groupLength;
int groups = bitLength / groupLength;
if (groups % 2 != 0) throw new Exception("groups must be even so data is in original array at end");
var count = new int[dim];
var pref = new int[dim];
int mask = (dim) - 1;
int negatives = 0, positives = 0;
// counting elements of the 1st group incuding negative/positive
for (int i = 0; i < arrayLen; i++)
{
if (a[i] < 0) negatives++;
count[(a[i] >> 0) & mask]++;
}
positives = arrayLen - negatives;
int c;
int shift;
for (c = 0, shift = 0; c < groups - 1; c++, shift += groupLength)
{
CalcPrefixes();
var nextShift = shift + groupLength;
//
for (var i = 0; i < arrayLen; i++)
{
var ai = a[i];
// Get the right index to sort the number in
int index = pref[( ai >> shift) & mask]++;
count[( ai>> nextShift) & mask]++;
t[index] = ai;
}
// swap the arrays and start again until the last group
var temp = a;
a = t;
t = temp;
}
// Last round
CalcPrefixes();
for (var i = 0; i < arrayLen; i++)
{
var ai = a[i];
// Get the right index to sort the number in
int index = pref[( ai >> shift) & mask]++;
// We're in the last (most significant) group, if the
// number is negative, order them inversely in front
// of the array, pushing positive ones back.
if ( ai < 0) index = positives - (index - negatives) - 1; else index += negatives;
//
t[index] = ai;
}
void CalcPrefixes()
{
pref[0] = 0;
for (int i = 1; i < dim; i++)
{
pref[i] = pref[i - 1] + count[i - 1];
count[i - 1] = 0;
}
}
}
You can use an unsafe block to memcpy or alias a float * to a uint * to extract the bits.
I think your best bet if the values aren't too close and there's a reasonable precision requirement, you can just use the actual float digits before and after the decimal point to do the sorting.
For example, you can just use the first 4 decimals (be they 0 or not) to do the sorting.