Advertisement
CCCoder

Algo HW 3

Sep 26th, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.08 KB | None | 0 0
  1. // Found this method to partition an array: https://stackoverflow.com/a/1396143/6501242
  2. public static IEnumerable<List<T>> Partition<T>(this IList<T> source, Int32 size) {
  3. for (int i = 0; i < Math.Ceiling(source.Count / (Double)size); i++)
  4.     yield return new List<T>(source.Skip(size * i).Take(size));
  5. }
  6.  
  7. static bool FindViaSublist(int[] set, int target) {
  8.     if (set.Length == 1) {
  9.         return set[0] == target;
  10.     }
  11.     if (set.Length == 2) {
  12.         return set[0] == target ? true : set[1] == target;
  13.     }
  14.     int sublistSize = (int)Math.Floor((double)set.Length / 3);
  15.     IEnumerable<List<int>> partitions = Partition(new List<int>(set), sublistSize);
  16.         partitions = partitions.Reverse();
  17.        
  18.         foreach (List<int> partition in partitions) {
  19.             if (partition[0] < target) {
  20.                 continue;
  21.             }
  22.             if (partition[0] == target) {
  23.                 return true;
  24.             }
  25.                 FindViaSublist(partition.ToArray(), target);               
  26.         }
  27.         return false;
  28.     }
  29. }
  30.  
  31. // Examples:
  32. int[] arr1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
  33. Console.WriteLine(FindViaSublist(arr1, 5)); // True
  34. Console.WriteLine(FindViaSublist(arr1, 100)); // False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement