Initial commit

This commit is contained in:
github-classroom[bot] 2024-10-15 17:16:17 +00:00 committed by GitHub
commit a681bc9dcb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 4929 additions and 0 deletions

3551
.editorconfig Normal file

File diff suppressed because it is too large Load diff

583
.gitignore vendored Normal file
View file

@ -0,0 +1,583 @@
# Created by https://www.toptal.com/developers/gitignore/api/csharp,visualstudio
# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,visualstudio
### Csharp ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
### VisualStudio ###
# User-specific files
# User-specific files (MonoDevelop/Xamarin Studio)
# Mono auto generated files
# Build results
# Visual Studio 2015/2017 cache/options directory
# Uncomment if you have tasks that create the project's static files in wwwroot
# Visual Studio 2017 auto generated files
# MSTest test Results
# NUnit
# Build Results of an ATL Project
# Benchmark Results
# .NET Core
# ASP.NET Scaffolding
# StyleCop
# Files built by Visual Studio
# Chutzpah Test files
# Visual C++ cache files
# Visual Studio profiler
# Visual Studio Trace Files
# TFS 2012 Local Workspace
# Guidance Automation Toolkit
# ReSharper is a .NET coding add-in
# TeamCity is a build add-in
# DotCover is a Code Coverage Tool
# AxoCover is a Code Coverage Tool
# Coverlet is a free, cross platform Code Coverage Tool
# Visual Studio code coverage results
# NCrunch
# MightyMoose
# Web workbench (sass)
# Installshield output folder
# DocProject is a documentation generator add-in
# Click-Once directory
# Publish Web Output
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
# NuGet Packages
# NuGet Symbol Packages
# The packages folder can be ignored because of Package Restore
# except build/, which is used as an MSBuild target.
# Uncomment if necessary however generally it will be regenerated when needed
# NuGet v3's project.json files produces more ignorable files
# Microsoft Azure Build Output
# Microsoft Azure Emulator
# Windows Store app package directories and files
# Visual Studio cache files
# files ending in .cache can be ignored
# but keep track of directories ending in .cache
# Others
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
# RIA/Silverlight projects
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
# SQL Server files
# Business Intelligence projects
# Microsoft Fakes
# GhostDoc plugin setting file
# Node.js Tools for Visual Studio
# Visual Studio 6 build log
# Visual Studio 6 workspace options file
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
# Paket dependency manager
# FAKE - F# Make
# CodeRush personal settings
# Python Tools for Visual Studio (PTVS)
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
# Telerik's JustMock configuration file
# BizTalk build output
# OpenCover UI analysis results
# Azure Stream Analytics local run output
# MSBuild Binary and Structured Log
# NVidia Nsight GPU debugger configuration file
# MFractors (Xamarin productivity tool) working folder
# Local History for Visual Studio
# Visual Studio History (VSHistory) files
# BeatPulse healthcheck temp database
# Backup folder for Package Reference Convert tool in Visual Studio 2017
# Ionide (cross platform F# VS Code tools) working folder
# Fody - auto-generated XML schema
# VS Code files for those working on multiple tools
# Local History for Visual Studio Code
# Windows Installer files from build outputs
# JetBrains Rider
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/csharp,visualstudio

View file

View file

@ -0,0 +1 @@
Name;Age;Race
1 Name Age Race

View file

@ -0,0 +1 @@
Name;Age;Race Egon;6;Arab Blitz;9;Newfoundland
1 Name Age Race Egon 6 Arab Blitz 9 Newfoundland

View file

@ -0,0 +1 @@
Name;Age Egon;-6 Blitz;9
1 Name Age Egon -6 Blitz 9

View file

@ -0,0 +1 @@
Name;Age Egon;6 Blitz;9
1 Name Age Egon 6 Blitz 9

View file

@ -0,0 +1,74 @@
using FluentAssertions;
using Xunit;
namespace HorseRace.Test;
public sealed class HorseImporterTests
{
[Fact]
public void NotExists()
{
HorseImporter.TryReadHorses("Data/none.csv", out var horses)
.Should().BeFalse("file does not exist");
horses.Should().BeNull();
}
[Fact]
public void Empty_01()
{
HorseImporter.TryReadHorses("Data/empty_01.csv", out var horses)
.Should().BeFalse("file is empty");
horses.Should().BeNull();
}
[Fact]
public void Empty_02()
{
HorseImporter.TryReadHorses("Data/empty_02.csv", out var horses)
.Should().BeFalse("file contains no data rows");
horses.Should().BeNull();
}
[Fact]
public void Invalid_01()
{
HorseImporter.TryReadHorses("Data/invalid_01.csv", out var horses)
.Should().BeFalse("file contains data rows, but none could be parsed");
horses.Should().NotBeNull("there are data rows to process")
.And.BeEmpty("no rows are valid, too many columns")
.And.BeSameAs(Array.Empty<Horse>(), "proper empty array creation");
}
[Fact]
public void Invalid_02()
{
HorseImporter.TryReadHorses("Data/invalid_02.csv", out var horses)
.Should().BeTrue("file contains data rows and some could be parsed");
horses.Should().NotBeNull("there are data rows to process")
.And.NotBeEmpty("at least one row is valid")
.And.HaveCount(1, "one row could be parsed")
.And.Subject.First()
.Should().BeEquivalentTo(new
{
Age = 9,
Name = "Blitz",
Position = 0,
Rank = 0,
StartNumber = 2
}, "position and rank are not set yet, start number is based on row number");
}
[Fact]
public void Valid()
{
HorseImporter.TryReadHorses("Data/valid.csv", out var horses)
.Should().BeTrue("file is valid");
horses.Should().NotBeNullOrEmpty("valid data")
.And.HaveCount(2, "two parseable rows")
.And.BeEquivalentTo(new[]
{
new Horse("Egon", 6, 1),
new Horse("Blitz", 9, 2)
});
}
}

View file

@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<None Update="Data\*.csv">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HorseRace\HorseRace.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,149 @@
using System.Reflection;
using FluentAssertions;
using Xunit;
namespace HorseRace.Test;
public sealed class HorseRaceTests : HorseTestBase
{
public HorseRaceTests()
{
RandomProvider.Random = new Random(12345678);
}
[Fact]
public void SortByPosition()
{
var horses = GetSampleHorses();
SetPosition(horses[0], 6);
SetPosition(horses[1], 2);
SetPosition(horses[2], 2);
SetPosition(horses[3], 4);
var horsesCopy = (Horse[]) horses.Clone();
var race = new HorseRace(horses);
CallSortByPosition(race);
horses[0].Should().BeEquivalentTo(horsesCopy[0], "highest position");
horses[1].Should().BeEquivalentTo(horsesCopy[3], "second highest position");
horses[2].Should().BeEquivalentTo(horsesCopy[1], "same position, but higher starting number");
horses[3].Should().BeEquivalentTo(horsesCopy[2], "same position, but lower starting number");
}
[Fact]
public void AssignRanks()
{
var horses = GetSampleHorses();
SetPosition(horses[0], 6);
SetPosition(horses[1], 2);
SetPosition(horses[2], 2);
SetPosition(horses[3], 4);
var race = new HorseRace(horses);
CallAssignRanks(race);
horses[0].Rank.Should().Be(1, "highest rank");
horses[1].Rank.Should().Be(2, "second highest rank");
horses[2].Rank.Should().Be(3, "shared third place");
horses[3].Rank.Should().Be(3, "shared third place");
}
[Fact]
public void MoveHorses_NotFinished_01()
{
var horses = GetSampleHorses();
var race = new HorseRace(horses);
for (var i = 0; i < 4; i++)
{
CallMoveHorses(race);
}
CheckIsFinished(race)
.Should().BeFalse("race not finished yet");
horses[0].Position.Should().Be(1);
horses[1].Position.Should().Be(0);
horses[2].Position.Should().Be(2);
horses[3].Position.Should().Be(1);
}
[Fact]
public void MoveHorses_NotFinished_02()
{
var horses = GetSampleHorses();
var race = new HorseRace(horses);
for (var i = 0; i < 10; i++)
{
CallMoveHorses(race);
}
CheckIsFinished(race)
.Should().BeFalse("race not finished yet");
horses[0].Position.Should().Be(3);
horses[1].Position.Should().Be(2);
horses[2].Position.Should().Be(4);
horses[3].Position.Should().Be(4);
}
[Fact]
public void MoveHorses_Finished()
{
var horses = GetSampleHorses();
var race = new HorseRace(horses);
for (var i = 0; i < 60; i++)
{
CallMoveHorses(race);
}
CheckIsFinished(race)
.Should().BeTrue("race is finished");
horses[0].Position.Should().Be(18);
horses[1].Position.Should().Be(17);
horses[2].Position.Should().Be(20, "horses are no longer moved once race is finished");
horses[3].Position.Should().Be(17);
}
private static Horse[] GetSampleHorses() =>
[
new("Harvey", 5, 4),
new("Haley", 8, 3),
new("Horace", 9, 2),
new("Hillary", 4, 1)
];
#region test helper methods - ignore
private const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance;
private static void CallMoveHorses(HorseRace instance)
{
GetMethod("MoveHorses").Invoke(instance, null);
}
private static void CallSortByPosition(HorseRace instance)
{
GetMethod("SortByPosition").Invoke(instance, null);
}
private static void CallAssignRanks(HorseRace instance)
{
GetMethod("AssignRanks").Invoke(instance, null);
}
private static bool CheckIsFinished(HorseRace instance)
{
var prop = typeof(HorseRace).GetProperty("IsFinished", Flags);
return (bool) prop!.GetValue(instance)!;
}
private static MethodInfo GetMethod(string methodName)
=> typeof(HorseRace).GetMethod(methodName, Flags)!;
#endregion
}

View file

@ -0,0 +1,14 @@
namespace HorseRace.Test;
#region test helper methods - ignore
public abstract class HorseTestBase
{
protected static void SetPosition(Horse horse, int position)
{
var prop = typeof(Horse).GetProperty(nameof(Horse.Position));
prop?.SetValue(horse, position);
}
}
#endregion

View file

@ -0,0 +1,154 @@
using FluentAssertions;
using Xunit;
namespace HorseRace.Test;
public sealed class HorseTests : HorseTestBase
{
public HorseTests()
{
RandomProvider.Random = new Random(12345);
}
[Fact]
public void Construction()
{
const string Name = "Henry";
const int Age = 8;
const int StartNo = 5;
var horse = new Horse(Name, Age, StartNo);
horse.Position.Should().Be(0, "initial value before being moved");
horse.StartNumber.Should().Be(StartNo);
horse.Age.Should().Be(Age);
horse.Name.Should().Be(Name);
horse.Rank.Should().Be(0, "initial value before being calculated (race finished)");
}
[Theory]
[MemberData(nameof(TryParseData))]
public void TryParse(string line, int startNo, bool expectedResult, Horse? expectedHorse, string reason)
{
Horse.TryParse(line, startNo, out var parsedHorse)
.Should().Be(expectedResult, reason);
if (expectedResult)
{
parsedHorse.Should().BeEquivalentTo(expectedHorse);
}
}
[Fact]
public void Move()
{
var horse = new Horse("Henry Horse", 9, 5);
SetPosition(horse, 4);
horse.Move();
horse.Position
.Should().Be(5);
horse.Move();
horse.Position
.Should().Be(6);
for (var i = 0; i < 5; i++)
{
horse.Move();
}
horse.Position
.Should().Be(7);
for (var i = 0; i < 8; i++)
{
horse.Move();
}
horse.Position
.Should().Be(12);
}
[Fact]
public void CompareTo_Equal()
{
const int Position = 4;
const int StartNo = 2;
var horse1 = new Horse("Horse A", 5, StartNo);
SetPosition(horse1, Position);
var horse2 = new Horse("Horse B", 8, StartNo);
SetPosition(horse2, Position);
var diff = horse1.CompareTo(horse2);
diff.Should().Be(0, "Both position and starting number are equal");
}
[Fact]
public void CompareTo_HigherPosition()
{
const int StartNo = 2;
var horse1 = new Horse("Horse A", 5, StartNo);
SetPosition(horse1, 8);
var horse2 = new Horse("Horse B", 8, StartNo);
SetPosition(horse2, 5);
horse1.CompareTo(horse2)
.Should().Be(-3, "First horse has higher position");
}
[Fact]
public void CompareTo_HigherStartNo()
{
const int Position = 2;
var horse1 = new Horse("Horse A", 5, 8);
SetPosition(horse1, Position);
var horse2 = new Horse("Horse B", 8, 5);
SetPosition(horse2, Position);
horse1.CompareTo(horse2)
.Should().Be(-3, "First horse has higher starting number");
}
[Fact]
public void CompareTo_LowerPosition()
{
const int StartNo = 2;
var horse1 = new Horse("Horse A", 5, StartNo);
SetPosition(horse1, 3);
var horse2 = new Horse("Horse B", 8, StartNo);
SetPosition(horse2, 5);
horse1.CompareTo(horse2)
.Should().Be(2, "First horse has lower position");
}
[Fact]
public void CompareTo_LowerStartNo()
{
const int Position = 2;
var horse1 = new Horse("Horse A", 5, 3);
SetPosition(horse1, Position);
var horse2 = new Horse("Horse B", 8, 5);
SetPosition(horse2, Position);
horse1.CompareTo(horse2)
.Should().Be(2, "First horse has lower starting number");
}
public static TheoryData<string, int, bool, Horse?, string> TryParseData => new()
{
{ "Henry;5", 2, true, new Horse("Henry", 5, 2), "Parseable" },
{ "Henry;-5", 2, false, null, "Invalid age" },
{ "Henry;25", 2, false, null, "Invalid age" },
{ "Henry;abc", 2, false, null, "Invalid age" },
{ "Henry;5;22", 2, false, null, "Too many columns" },
{ "Henry", 2, false, null, "Not enough columns" },
{ ";5", 2, false, null, "Empty name" },
{ "Henry;5", -2, false, null, "Invalid starting number" }
};
}

30
HorseRace.sln Normal file
View file

@ -0,0 +1,30 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.32126.317
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HorseRace", "HorseRace\HorseRace.csproj", "{F687519F-3209-44B6-81BF-DDD2466FEEF2}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HorseRace.Test", "HorseRace.Test\HorseRace.Test.csproj", "{C0CE7914-5D5B-4C90-A993-A8F8CC7002E8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F687519F-3209-44B6-81BF-DDD2466FEEF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F687519F-3209-44B6-81BF-DDD2466FEEF2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F687519F-3209-44B6-81BF-DDD2466FEEF2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F687519F-3209-44B6-81BF-DDD2466FEEF2}.Release|Any CPU.Build.0 = Release|Any CPU
{C0CE7914-5D5B-4C90-A993-A8F8CC7002E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C0CE7914-5D5B-4C90-A993-A8F8CC7002E8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C0CE7914-5D5B-4C90-A993-A8F8CC7002E8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C0CE7914-5D5B-4C90-A993-A8F8CC7002E8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B7BD828E-2CBE-4D53-BA50-CC9536773BE0}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1 @@
Name;Age Egon;6 Blitz;9 Lara;3 Donnerhall;5 Darco;10 Meteor;3 Big Ben;4 Goldfever;4 Silbersee;8 Adlerflug;7
1 Name Age Egon 6 Blitz 9 Lara 3 Donnerhall 5 Darco 10 Meteor 3 Big Ben 4 Goldfever 4 Silbersee 8 Adlerflug 7

59
HorseRace/Horse.cs Normal file
View file

@ -0,0 +1,59 @@
namespace HorseRace;
public sealed class Horse
{
public Horse(string name, int age, int startNo)
{
// TODO
}
public int Age { get; }
public string Name { get; }
public int Position { get; private set; }
public int Rank { get; set; }
public int StartNumber { get; }
/// <summary>
/// Compares this <see cref="Horse" />, first by position and then by start number,
/// to the supplied <see cref="Horse" />
/// </summary>
/// <param name="other"><see cref="Horse" /> to compare to</param>
/// <returns>The position difference between two horses</returns>
public int CompareTo(Horse other)
{
// TODO
return -1;
}
/// <summary>
/// Draws the current position of this <see cref="Horse" /> to the console, including
/// its label and the finish line.
/// </summary>
public void Draw()
{
// TODO
}
/// <summary>
/// Randomly either increases or keeps the position of the <see cref="Horse" />.
/// </summary>
public void Move()
{
// TODO
}
/// <summary>
/// Attempts to parse a CSV formatted string to a <see cref="Horse" /> instance.
/// Also sets the supplied <see cref="startNo" /> if parsing succeeds.
/// </summary>
/// <param name="csvLine">Text to parse</param>
/// <param name="startNo">Start number to set; must not be negative</param>
/// <param name="horse">Set to the parsed instance; null if parsing fails</param>
/// <returns>True if parsed successfully; false otherwise</returns>
public static bool TryParse(string csvLine, int startNo, out Horse? horse)
{
// TODO
horse = null;
return false;
}
}

View file

@ -0,0 +1,11 @@
namespace HorseRace;
public static class HorseImporter
{
public static bool TryReadHorses(string filePath, out Horse[]? horses)
{
// TODO
horses = null;
return false;
}
}

92
HorseRace/HorseRace.cs Normal file
View file

@ -0,0 +1,92 @@
namespace HorseRace;
public sealed class HorseRace
{
public const int MaxSteps = 20;
private const int DelayMilliseconds = 100;
private readonly Horse[] _horses;
public HorseRace(Horse[] horses)
{
// TODO
}
private bool IsFinished { get; set; }
/// <summary>
/// Prints the starting list for all horses in this race.
/// </summary>
public void PrintStartList()
{
string nl = Environment.NewLine;
var s = "Starting List";
s += $"{nl}{new string('=', s.Length)}{nl}"
;
foreach (var horse in _horses)
{
s += string.Format($"{horse.StartNumber,3} {horse.Name,-10} {horse.Age,2}{nl}");
}
Console.WriteLine(s);
}
/// <summary>
/// Starts and performs the race by moving and drawing the horses, until at least one
/// horse has reached the finish line.
/// </summary>
public void PerformRace()
{
IsFinished = false;
while (!IsFinished)
{
MoveHorses();
DrawHorses();
Thread.Sleep(DelayMilliseconds);
}
AssignRanks();
}
/// <summary>
/// Prints the race results to the terminal; only if the race is finished.
/// </summary>
public void PrintResults()
{
// TODO
}
/// <summary>
/// Moves all horses and checks, if any of the horses has reached the finish line.
/// </summary>
private void MoveHorses()
{
// TODO
}
/// <summary>
/// Draws each horse with label, current position and finish line.
/// </summary>
private void DrawHorses()
{
Console.Clear();
// TODO
}
/// <summary>
/// Assigns ranks to the horses, according to their individual position in the race.
/// </summary>
private void AssignRanks()
{
SortByPosition();
// TODO
}
/// <summary>
/// Sorts the array of horses by position and then by starting number.
/// </summary>
private void SortByPosition()
{
// TODO
}
}

View file

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<None Update="Data\*.csv">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

30
HorseRace/Program.cs Normal file
View file

@ -0,0 +1,30 @@
using System.Text;
using HorseRace;
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine($"*** Horse Race ***{Environment.NewLine}");
if (!HorseImporter.TryReadHorses("Data/horses.csv", out Horse[]? horses)
|| horses == null)
{
Console.WriteLine("Failed to parse horses");
return;
}
if (horses.Length == 0)
{
Console.WriteLine("No horses available");
return;
}
var race = new HorseRace.HorseRace(horses);
race.PrintStartList();
Console.ReadKey();
race.PerformRace();
Console.WriteLine();
race.PrintResults();

View file

@ -0,0 +1,6 @@
namespace HorseRace;
public static class RandomProvider
{
public static Random Random = Random.Shared;
}

BIN
pics/sample_run.mp4 Normal file

Binary file not shown.

113
readme.adoc Normal file
View file

@ -0,0 +1,113 @@
:sectnums:
:nofooter:
:toc: left
:icons: font
:data-uri:
= OOB.02 -- Horse Race
This time you are going to read horse data from a CSV file and then simulate races between those horses, including output to the terminal.
[plantuml]
----
@startuml
class HorseRace {
+HorseRace(Horse[])
+int MaxSteps [const]
-int DelayMilliseconds [const]
-Horse[] _horses [readonly]
-bool IsFinished
+void PrintStartList()
+void PerformRace()
+void PrintResults()
-void MoveHorses()
-void DrawHorses()
-void AssignRanks()
-void SortByPosition()
}
class Horse {
+Horse(string, int, int)
+int Age [readonly]
+string Name [readonly]
+int Position [private set]
+int Rank
+int StartNumber [readonly]
+int CompareTo(Horse other)
+void Draw()
+void Move()
{static} +bool TryParse(string, int, out Horse?)
}
HorseRace "1" -r- "n" Horse: has
@enduml
----
== The `Horse` class
The `Horse` class, unsurprisingly, represents a horse.
Each horse has:
* A name
* An age
* An assigned starting number
During the race and based on the race results each horse gets assigned:
* A varying position
* A final rank
=== Method Requirements
Additional specifications for some methods -- primarily rely on the XML Doc.
* `CompareTo`
** Subtract _from_ the `other` value to get the correct `int` value
* `Move`
** The probability of moving one position ('field') forward is ~33%
*** Make sure to use the `Random` instance in `RandomProvider`
* `TryParse`
** The name cannot be empty
** The age of a horse has to be in the stem:[0 < x <= 20] range
** The starting number may not be negative
== Importing Data with the `HorseImporter` class
The `Horse` class provides a `TryParse` _factory method_, yet it still needs to be called for each CSV line which in turn needs to be read from a file.
That is the job of the `_static_` `HorseImporter` class.
Consider the usual rules for reading CSV files:
* The file has to exist
* It has to have a header and _at least one_ valid data row
* Invalid data rows are skipped
* If no data could be parsed an _empty_ array is returned
* Make sure the returned array does not contain any `null` values
NOTE: This is a `static` class providing a single, _stateless_ method
== Performing the race with the `HorseRace` class
A race can only happen when the horses are present.
Thus, it is _dependent_ on the array of horses => required to construct an instance of the `HorseRace` class.
* The `IsFinished` property is set to `true` once the first horse reaches the finish line
** Subsequent move operations are ignored
** The finish line is reached when the horse's `Position` equals `MAX_STEPS`
* `MoveHorses` applies a 'move order' to _each_ of the horses in the race
* Make sure to print in the expected format
** => see sample run below
** Remember that the `Horse` class already provides a `Draw` method!
* Ranks are assigned based on the position (at the end of the race), thus, horses with the same position also have the same rank
** Ranks start at 1 (not 0)
* When sorting make sure to use the `CompareTo` method of the `Horse` class
** Horses know how to compare to each other _themselves_!
NOTE: Do not worry about (already implemented) the delay between horse movements. We'll discuss various methods for adding delays to a program in a few months
=== Sample Run
video::pics/sample_run.mp4[width=480,opts=autoplay]