From 068f1cd4051a8910fca6ab2528a5997100686a13 Mon Sep 17 00:00:00 2001 From: sova gleb Date: Fri, 28 May 2021 10:08:44 +0300 Subject: [PATCH] task 5 finished --- .../DrunkFibonacci/DrunkFibonacci.cs | 70 ++++++++++++++++--- 1 file changed, 59 insertions(+), 11 deletions(-) diff --git a/course-2021-1/exercises/05-drunk-fibonacci/DrunkFibonacci/DrunkFibonacci/DrunkFibonacci.cs b/course-2021-1/exercises/05-drunk-fibonacci/DrunkFibonacci/DrunkFibonacci/DrunkFibonacci.cs index ac217f0d..18729c4d 100644 --- a/course-2021-1/exercises/05-drunk-fibonacci/DrunkFibonacci/DrunkFibonacci/DrunkFibonacci.cs +++ b/course-2021-1/exercises/05-drunk-fibonacci/DrunkFibonacci/DrunkFibonacci/DrunkFibonacci.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; namespace DrunkFibonacci { @@ -12,7 +13,7 @@ internal static class DrunkFibonacci public static int[] CreateIntArray(int len) { // на создание массивов заданной длины - throw new NotImplementedException(); + return new int[len]; } /// @@ -24,7 +25,10 @@ public static int[] CreateIntArray(int len) public static void FillIntArray(int[] arr, int seed, int step) { // на задание значений массива - throw new NotImplementedException(); + for (var i = 0; i < arr.Length; ++i) + { + arr[i] = seed + i * step; + } } /// @@ -34,7 +38,7 @@ public static void FillIntArray(int[] arr, int seed, int step) public static int[] GetFirstFiveFibonacci() { // на создание массива с инициализацией - throw new NotImplementedException(); + return new int[] {1, 1, 2, 3, 5}; } /// @@ -49,7 +53,11 @@ его следует инициализировать одной и той же Задача на ленивую генерацию последовательностей. */ - throw new NotImplementedException(); + Random rand = new Random(13); + while (true) + { + yield return rand.Next(); + } } /// @@ -67,7 +75,34 @@ Вероятность считается так. На каждом i-ом эт из последовательности GetDeterministicRandomSequence и проверяешь, есть ли у числа Y единичные биты числа 42. При вычислении сложения переполнение типа разрешено и всячески поощряется. */ - throw new NotImplementedException(); + int prev = 0; + int prevprev = 1; + var enumerator = GetDeterministicRandomSequence().GetEnumerator(); + for (int i = 0; ; ++i) + { + enumerator.MoveNext(); + int next = prev + prevprev; + + if (i % 6 == 5) + { + prevprev = prev; + prev = next; + continue; + } + else if (i % 6 == 3) + { + next = 300; + } + + if ((enumerator.Current & 42) != 0) + { + next &= ~42; + } + + prevprev = prev; + prev = next; + yield return next; + } } /// @@ -78,7 +113,7 @@ При вычислении сложения переполнение типа public static int GetMaxOnRange(int from, int cnt) { // научишься пропускать и брать фиксированную часть последовательности, агрегировать. Максимум есть среди готовых функций агрегации. - throw new NotImplementedException(); + return GetDrunkFibonacci().Skip(from - 1).Take(cnt).Max(); } /// @@ -88,7 +123,7 @@ public static int GetMaxOnRange(int from, int cnt) public static List GetNextNegativeRange(int from = 1) { // научишься пропускать и брать по условию, превращать в список (см. ToList). - throw new NotImplementedException(); + return GetDrunkFibonacci().Skip(from - 1).SkipWhile(x => x >= 0).TakeWhile(x => x < 0).ToList(); } /// @@ -97,7 +132,7 @@ public static List GetNextNegativeRange(int from = 1) public static IEnumerable GetXoredWithLaggedItself() { // узнаешь о существовании функции Zip. - throw new NotImplementedException(); + return GetDrunkFibonacci().Zip(GetDrunkFibonacci().Skip(42), (x, y) => x ^ y); } /// @@ -106,7 +141,17 @@ public static IEnumerable GetXoredWithLaggedItself() public static IEnumerable GetInChunks() { // ни чему особо не научишься, просто интересная задачка :) - throw new NotImplementedException(); + var enumerator = GetDrunkFibonacci().GetEnumerator(); + while (true) + { + int[] chunk = new int[16]; + for (int i = 0; i < 16; ++i) + { + enumerator.MoveNext(); + chunk[i] = enumerator.Current; + } + yield return chunk; + } } /// @@ -122,7 +167,7 @@ которая сглаживает (flatten) последовательност Вообще говоря, SelectMany умеет много чего и мегаполезна. Она в какой-то степени эквивалентна оператору `bind` над монадами (в данном случае над монадами последовательностей). */ - throw new NotImplementedException(); + return GetInChunks().SelectMany(chunk => chunk.OrderBy(x => x).Take(3)); } /// @@ -156,7 +201,10 @@ Конкретно в этом задании более к месту буде Итого научишься группировать и создавать на их основе словарь (см. ToDictionary). */ - throw new NotImplementedException(); + return GetDrunkFibonacci() + .Take(10000) + .GroupBy(x => x % 8, (x, group) => new { Key = x, Count = group.Count() }) + .ToDictionary(x => x.Key, x => x.Count); } } }