Randomly insert specified number of 1’s in a list of 0’s

using System;

using System.Collections.Generic;

using System.Text;

using System.Text.RegularExpressions;

using System.IO;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            List<int> intList = new List<int>();

            for (int i = 0; i < 10; i++)

            {

                intList.Add(0);

            }

            Console.WriteLine("Initial List: ");

            for (int i = 0; i < intList.Count; i++)

            {

                Console.Write(intList[i] + " ");

            }

            Console.WriteLine();

            intList = Insert(intList, 5);

            Console.WriteLine("Processed List: ");

            for (int i = 0; i < intList.Count; i++)

            {

                Console.Write(intList[i] + " ");

            }

            Console.WriteLine();

        }

        public static List<int> Insert(List<int> list, int count)

        {

            if (count > list.Count)

            {

                return list;

            }

            else

            {

                if (count > 0)

                {

                    int i = 0;

                    Random rand = new Random();

                    do

                    {

                        do

                        {

                            i = rand.Next(list.Count);

                        } while (list[i] != 0);

                        list[i] = 1;

                    } while (CountOne(list) != count);

                    return list;

                }

                else

                {

                    return list;

                }

            }

        }

        public static int CountOne(List<int> list)

        {

            int count = 0;

            for (int i = 0; i < list.Count; i++)

            {

                if (list[i] == 1)

                {

                    count++;

                }

            }

            return count;

        }

    }

}

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s