Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,71 @@
namespace AdventureTime
using System;

namespace AdventureTime
{
internal class Program
{
private static void Main()
{
DateTime dt = Time.WhatTimeIsIt();
DateTimeKind kind = DateTimeKind.Utc;
// 1
// Console.WriteLine(Time.WhatTimeIsItInUtc());

// 2
// Console.WriteLine(dt);
// Console.WriteLine(Time.SpecifyKind(dt, kind));

// 3
//Console.WriteLine(Time.ToRoundTripFormatString(dt));

// 4
/*
Console.WriteLine(Time.SpecifyKind(dt, DateTimeKind.Local).ToString("o"));
Console.WriteLine(Time.SpecifyKind(dt, DateTimeKind.Unspecified).ToString("o"));
Console.WriteLine(Time.SpecifyKind(dt, DateTimeKind.Utc).ToString("o"));
*/

// 5
//Console.WriteLine(dt);
//Console.WriteLine(Time.ParseFromRoundTripFormat(Time.ToRoundTripFormatString(dt)));

// 6
//Console.WriteLine(Time.ToUtc(dt));

// 7
//Console.WriteLine(dt);
//Console.WriteLine(Time.AddTenSeconds(dt));

// 8
//Console.WriteLine(dt);
//Console.WriteLine(Time.AddTenSecondsV2(dt));

// 9
DateTime test_dt = new DateTime(2021, 5, 24, 2, 15, 0);
//Console.WriteLine(Time.GetHoursBetween(dt, Time.SpecifyKind(test_dt, DateTimeKind.Utc)));

// 10
//Console.WriteLine(Time.GetTotalMinutesInThreeMonths());

// 11
//Console.WriteLine(Time.GetAdventureTimeDurationInMinutes_ver0_Dumb());

// 12
//Console.WriteLine(Time.GetGenderSwappedAdventureTimeDurationInMinutes_ver0_Dumb());

// 13
//Console.WriteLine(Time.GetAdventureTimeDurationInMinutes_ver1_FeelsSmarter());

// 14
//Console.WriteLine(Time.GetAdventureTimeDurationInMinutes_ver2_FeelsLikeRocketScience());

// 15
//Console.WriteLine(Time.GetGenderSwappedAdventureTimeDurationInMinutes_ver2_FeelsLikeRocketScience());

// ...

// 16
//Console.WriteLine(Time.AreEqualBirthdays(dt, test_dt));
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Globalization;
using NodaTime;
using NodaTime.TimeZones;

Expand All @@ -14,15 +15,15 @@ internal static class Time
/// </summary>
public static DateTime WhatTimeIsIt()
{
throw new NotImplementedException();
return DateTime.Now;
}

/// <summary>
/// Возвращает текущее время в UTC.
/// </summary>
public static DateTime WhatTimeIsItInUtc()
{
throw new NotImplementedException();
return DateTime.UtcNow;
}

/// <summary>
Expand All @@ -36,7 +37,7 @@ public static DateTime SpecifyKind(DateTime dt, DateTimeKind kind)
/*
Подсказка: поищи в статических методах DateTime.
*/
throw new NotImplementedException();
return DateTime.SpecifyKind(dt, kind);
}

/// <summary>
Expand All @@ -51,7 +52,7 @@ Обязательно поиграйся и посмотри на измене
Ну и на будущее запомни этот прекрасный строковый формат представления времени - он твой бро!
Название запоминать не нужно, просто помни, что для передачи значения в виде строки, выбирать лучше инвариантные относительно сериализации/десериализации форматы.
*/
throw new NotImplementedException();
return dt.ToString("O");
}

/// <summary>
Expand All @@ -65,7 +66,7 @@ public static DateTime ParseFromRoundTripFormat(string dtStr)
Поиграйся и проверь, что round-trip действительно round-trip, т.е. туда-обратно равно оригиналу (для туда воспользуйся предыдущим методом).
Проверь для всех значений DateTime.Kind.
*/
throw new NotImplementedException();
return DateTime.Parse(dtStr);
}

/// <summary>
Expand All @@ -77,7 +78,7 @@ public static DateTime ToUtc(DateTime dt)
Eсли воспользуешься нужным методом, то напоминаю, что результат его работы зависит от dt.Kind.
В случае dt.Kind == Unspecified предполагается, что время локальное, т.е. результат работы в случае Local и Unspecified совпадают. Такие дела
*/
throw new NotImplementedException();
return dt.ToUniversalTime();
}

/// <summary>
Expand All @@ -88,7 +89,7 @@ public static DateTime ToUtc(DateTime dt)
public static DateTime AddTenSeconds(DateTime dt)
{
// здесь воспользуйся методами самого объекта и заодно посмотри какие еще похожие есть
throw new NotImplementedException();
return dt.AddSeconds(10);
}

/// <summary>
Expand All @@ -102,7 +103,8 @@ public static DateTime AddTenSecondsV2(DateTime dt)
Ну а здесь воспользуйся сложением с TimeSpan. Обрати внимание, что помимо конструктора, у класса есть набор полезных статических методов-фабрик.
Обрати внимание, что у TimeSpan нет статических методов FromMonth, FromYear. Как думаешь, почему?
*/
throw new NotImplementedException();
// в месяцах и годах переменное количество дней
return dt + TimeSpan.FromSeconds(10);
}

/// <summary>
Expand All @@ -118,7 +120,10 @@ public static int GetHoursBetween(DateTime dt1, DateTime dt2)
2) Проверь, учитывается ли Kind объектов при арифметических операциях.
3) Подумай, почему возвращаемое значение может отличаться от действительности.
*/
throw new NotImplementedException();
// `Hours` возвращает число часов в записи времени, а `TotalHours` возвращает полное время в часах
// При попытке найти разницу между датой с local и датой, которая переведена в utc, разница не обнаружилась
// если даты в разных часовых поясах, то разница будет ещё включать разницу поясов
return (int)dt1.Subtract(dt2).TotalHours;
}

/// <summary>
Expand All @@ -127,7 +132,9 @@ public static int GetHoursBetween(DateTime dt1, DateTime dt2)
public static int GetTotalMinutesInThreeMonths()
{
// ну тут все просто и очевидно, если сделал остальные и подумал над вопросами в комментах.
throw new NotImplementedException();
DateTime curr_dt = DateTime.UtcNow;
DateTime three_month_from_curr_dt = curr_dt.AddMonths(3);
return (int) three_month_from_curr_dt.Subtract(curr_dt).TotalMinutes;
}

#region Adventure time saga
Expand All @@ -147,7 +154,10 @@ public static int GetAdventureTimeDurationInMinutes_ver0_Dumb()
Держи, заготовочку для копипасты:
- 2010, 3, 28, 2, 15, 0
*/
throw new NotImplementedException();
var from = new DateTimeOffset(2010, 3, 28, 2, 15, 0, TimeSpan.FromHours(3));
var to = new DateTimeOffset(2010, 3, 28, 2, 15, 0, TimeSpan.FromHours(0));

return (int)to.Subtract(from).TotalMinutes;
}

/// <summary>
Expand All @@ -165,7 +175,9 @@ public static int GetGenderSwappedAdventureTimeDurationInMinutes_ver0_Dumb()
- 2010, 3, 28, 3, 15, 0
- 2010, 3, 28, 1, 15, 0
*/
throw new NotImplementedException();
var from = new DateTimeOffset(2010, 3, 28, 3, 15, 0, TimeSpan.FromHours(3));
var to = new DateTimeOffset(2010, 3, 28, 1, 15, 0, TimeSpan.FromHours(0));
return (int)to.Subtract(from).TotalMinutes;
}

/// <summary>
Expand All @@ -180,7 +192,9 @@ Внимательный читатель мог усомниться в дан
На самом деле смещения таковы: Лондон +1 (BST - British Summer Time), Москва +4 (MSD - Moscow Daylight Time).
Давай теперь учтем правильное смещение. Я понимаю, что это очевидно, что результат не изменится, но тебе же не сложно скопипастить и просто поменять смещения?
*/
throw new NotImplementedException();
var from = new DateTimeOffset(2010, 3, 28, 3, 15, 0, TimeSpan.FromHours(4));
var to = new DateTimeOffset(2010, 3, 28, 1, 15, 0, TimeSpan.FromHours(1));
return (int)to.Subtract(from).TotalMinutes;
}

// GetGenderSwappedAdventureTimeDurationInMinutes_ver1_FeelsSmarter опустим, там то же самое
Expand All @@ -202,10 +216,18 @@ Тут придется воспользоваться знанием о час
ниже ты найдешь готовый метод GetZonedTime. Просто посмотри на него (можешь даже посмотреть методы и свойства типа TimeZoneInfo, если интересно) и воспользуйся им для вычисления правильного времени
"отбытия" и "прибытия" наших героев. Затем посчитай длительность путешествия. Также даны правильные идентификаторы зон.
*/
// таких зон не существует
/*
const string moscowZoneId = "Russian Standard Time";
const string londonZoneId = "GMT Standard Time";

throw new NotImplementedException();
*/
const string moscowZoneId = "Europe/Moscow";
const string londonZoneId = "Europe/London";

var from = GetZonedTime(new DateTime(2010, 3, 28, 2, 15, 0), moscowZoneId);
var to = GetZonedTime(new DateTime(2010, 3, 28, 2, 15, 0), londonZoneId);

return (int)to.Subtract(from).TotalMinutes;
}

/// <summary>
Expand All @@ -216,9 +238,13 @@ public static int GetGenderSwappedAdventureTimeDurationInMinutes_ver2_FeelsLikeR
/*
Реши по аналогии с предыдущим методом и проверь, что оба метода действительно возвращают одно и то же время (и что оно правильное).
*/
const string moscowZoneId = "Russian Standard Time";
const string londonZoneId = "GMT Standard Time";
throw new NotImplementedException();
const string moscowZoneId = "Europe/Moscow";
const string londonZoneId = "Europe/London";

var from = Time.GetZonedTime(new DateTime(2010, 3, 28, 3, 15, 0), moscowZoneId);
var to = Time.GetZonedTime(new DateTime(2010, 3, 28, 1, 15, 0), londonZoneId);

return (int)to.Subtract(from).TotalMinutes;
}

private static DateTimeOffset GetZonedTime(DateTime localTime, string timeZoneId)
Expand Down Expand Up @@ -277,7 +303,7 @@ private static ZonedDateTime GetZonedTime(LocalDateTime localTime, string timeZo
/// <returns>True - если родились в один день, иначе - false.</returns>
internal static bool AreEqualBirthdays(DateTime person1Birthday, DateTime person2Birthday)
{
throw new NotImplementedException();
return person1Birthday.Date.ToUniversalTime() == person2Birthday.Date.ToUniversalTime();
}
}
}
2 changes: 1 addition & 1 deletion course-2021-1/exercises/02-adventure-time/readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 02. Primitive types
ow to# 02. Primitive types

## Entry point

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BoringVector\BoringVector.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System;
using System.Runtime.InteropServices;
using Xunit;

namespace BoringVector.Tests
{
/*
SquareLength
Add
Scale
DotProduct
CrossProduct
*/
public class BoringVectorTest
{
[Theory]
[InlineData(1, 1, 2)]
[InlineData(2, -2, 8)]
public void SquareLengthTest(double X, double Y, double l)
{
Vector test = new Vector(X, Y);
Assert.Equal(l, test.SquareLength());
}

[Theory]
[InlineData(1, 1, 0, 0, 1, 1)]
[InlineData(1, 1, -1, -1, 0, 0)]
public void AddTest(double X1, double Y1, double X2, double Y2, double X3, double Y3)
{
Vector test1 = new Vector(X1, Y1);
Vector test2 = new Vector(X2, Y2);
Vector test3 = test1.Add(test2);
Assert.Equal(X3, test3.X);
Assert.Equal(Y3, test3.Y);
}

[Theory]
[InlineData(1, 1, 2, 2, 2)]
public void ScaleTest(double X1, double Y1, double k, double X2, double Y2)
{
Vector test1 = new Vector(X1, Y1);
Vector test2 = test1.Scale(k);
Assert.Equal(X2, test2.X);
Assert.Equal(Y2, test2.Y);
}

[Theory]
[InlineData(1, 2, 1, -1, -1)]
public void DotProductTest(double X1, double Y1, double X2, double Y2, double dp)
{
Vector test1 = new Vector(X1, Y1);
Vector test2 = new Vector(X2, Y2);
double test = test1.DotProduct(test2);
Assert.Equal(dp, test);
}

[Theory]
[InlineData(2, 2, 1, -1, -4)]
public void CrossProductTest(double X1, double Y1, double X2, double Y2, double cp)
{
Vector test1 = new Vector(X1, Y1);
Vector test2 = new Vector(X2, Y2);
double test = test1.CrossProduct(test2);
Assert.Equal(cp, test);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ VisualStudioVersion = 15.0.27004.2002
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoringVector", "BoringVector\BoringVector.csproj", "{7B438112-6A12-47BC-B494-FF8850924783}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoringVector.Tests", "BoringVector.Tests\BoringVector.Tests.csproj", "{583A57E0-A7B1-486A-81FD-5746100C2C06}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +17,10 @@ Global
{7B438112-6A12-47BC-B494-FF8850924783}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B438112-6A12-47BC-B494-FF8850924783}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7B438112-6A12-47BC-B494-FF8850924783}.Release|Any CPU.Build.0 = Release|Any CPU
{583A57E0-A7B1-486A-81FD-5746100C2C06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{583A57E0-A7B1-486A-81FD-5746100C2C06}.Debug|Any CPU.Build.0 = Debug|Any CPU
{583A57E0-A7B1-486A-81FD-5746100C2C06}.Release|Any CPU.ActiveCfg = Release|Any CPU
{583A57E0-A7B1-486A-81FD-5746100C2C06}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ internal class Program
{
private static void Main()
{
Console.WriteLine("Hello World!");
double a = 1.2;
double b = 0.32;
Console.WriteLine("(" + a.ToString() + "; " + b.ToString() + ")");
}
}
}
Loading