Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-order array putting nulls at end C#

Tags:

arrays

c#

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

  • P4 shows up (items = "P1", "P3", "P4", null)
  • P4 does not already exist, so I just add it to the lowest null index.
  • But then P1 comes again, so P1's spot goes to null (items = null, "P3", "P4", null)
  • I then need a way (my question) to shift everything like so (items = "P3", "P4", null, null)
  • Then add P1 at the lowest null index (items = "P3", "P4", "P1", null)
  • And so on, keeping track of LRU

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)

like image 206
Austin Avatar asked Dec 04 '25 17:12

Austin


2 Answers

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);
like image 102
usr Avatar answered Dec 06 '25 05:12

usr


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);
like image 23
user2023861 Avatar answered Dec 06 '25 06:12

user2023861