0

How in array random delete and add units? For example if have array 1011100101 of length 10 with 6 units and 4 zeros, how to get array of length 10 with 3 units and 7 zeros? Or if have array 100100000 of length 10 with 2 units and 8 zeros, how to get array of length 10 with 5 units and 5 zeros? I tried something like this:

 int units = array.getUnits();
        if (units > P)
        {
            while (units != P)
            {
                int p = rnd.Next(units), pos = 0;
                for (int i = 0; i < array.Length; i++)
                {
                    if (array[i] == 1)
                        pos++;
                    if (pos == p)
                    {
                        array[p]=0;
                        break;
                    }
                }
                units--;
            }
        }
        else if (units < P)
        {
            while (units != P)
            {
                int p = rnd.Next(array.Length-units), 
                  pos = 0;
                for (int i = 0; i < array.Length; i++)
                {
                    if (array[i] == 0)
                        pos++;
                    if (pos == p)
                    {
                        array[p]=1;
                        break;
                    }
                }
               units++;
            }

        }

It only add one unit (not 2 or more) or delete one unit.

Old Fox
  • 8,629
  • 4
  • 34
  • 52
  • 3
    Use List so you can insert into the middle of an array. An array is much harder to insert items in the middle. – jdweng Apr 11 '16 at 12:21

2 Answers2

0

Like Jdweng mentioned in the comments. It is easier to use a list for this sort of a thing. You can't freely insert items into an array. In a list, you can.

    int[] source = {0, 1, 0, 1, 1};
    List<int> tempList = new List<int>(source);
    int totalChanges = 20;
    Random random = new Random(DateTime.Now.Millisecond);
    for (int i = 0; i < totalChanges; i++)
    {
        int index = tempList.Count == 0 ? 0 : random.Next(0, tempList.Count); //return either 0 if empty  or a random position
        tempList.Insert(index, random.Next(0,1));
    }
    int[] result = tempList.ToArray();

The above example converts the source int array to a list, then it will add 20 items at random positions in the list and convert the result back to a array. If you start with a empty array it will start by inserting a 1 or 0 at index 0.

Nick Otten
  • 702
  • 7
  • 17
0

Is this binary arithmetic you are doing? If so,

  • Convert to integer
  • Do your arithmetic with integers
  • Convert back to binary

String to binary in C#

Community
  • 1
  • 1