I am trying to make an LRU, and keep track of the value order.
So lets say I have array items = "P1", "P3", null, null
"P1", "P3", "P4", null)null index.null (items = null, "P3", "P4", null)"P3", "P4", null, null)null index (items = "P3", "P4", "P1", null)So I need to find a way to move all non-nulls to front of the array (in order).
I did find a post that used this items = items.Where(s => !String.IsNullOrEmpty(s)).ToArray();, however this removes all nulls, when I want to keep intact the array size.
How can I preserve my array size, while shifting all nulls to the end, and all non-nulls to the front (keeping the values in order still)
Just literally "First the non-null items, then the null items":
var nulls = items.Where(x => x == null);
var nonnulls = items.Where(x => x != null);
var result = nonnulls.Concat(nulls);
Or:
var result = items.OrderBy(x => x == null).ThenBy(x => x.SomeOtherKey);
Here's a solution that doesn't create a new array. It just rearranges the existing array.
static void MoveFront<T>(T[] arr) where T : class
{
int ileft = 0;
int iright = 1;
while (iright < arr.Length)
{
T left = arr[ileft];
T right = arr[iright];
if (left == null && right != null)
{
Swap(arr, ileft++, iright++);
}
else if (left == null && right == null)
{
iright++;
}
else if (left != null && right != null)
{
ileft += 2;
iright += 2;
}
else if (left != null && right == null)
{
ileft++;
iright++;
}
}
}
static void Swap<T>(T[] arr, int left, int right)
{
T temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
Call it like this:
string[] arr = { "a", null, "b", null, "c" };
MoveFront(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With