Пример #1
0
        /// <summary>
        /// A classic sort of a problem really. Given a list, can you randomly shuffle it into an array but be sure that  the array is full?
        /// My first approach, commented out, does not guarantee this at all! 
        /// </summary>
        /// <param name="intake"></param>
        /// <returns></returns>
        private List<Student> shuffleStudents(List<Student> intake)
        {
            Random ind = new Random();
            var inputStudents = intake.ToArray();
            Student[] students = new Student[intake.Count];
            int s = 0;
            while (students.Any(x => x == null) && inputStudents.Length > 0)
                {
                int r = ind.Next(0, inputStudents.Length);

                if (students[r] == null)
                    {
                    students[r] = inputStudents[s]; //do this here so I can get s = 0 in the array
                    }
                else
                    {
                    List<int> nulls = new List<int>();
                    for (int _i = 0; _i < inputStudents.Count(); _i++) if (students[_i] == null) nulls.Add(_i); //get a list of null indices
                    if (nulls.Count() > 0) students[nulls.First()] = inputStudents[s]; //fill up the holes
                    }
                s++;
                s = s < inputStudents.Length ? s : 0; //increment the input index but don't go outside the bounds of the array!
                }

            return students.ToList();
        }