From 1c1276778b562850563d6391c0c89eb056844f30 Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:40:05 -0300 Subject: [PATCH 01/14] Just starting out. --- 55_Life/csharp/.gitignore | 509 +++++++++++++++++++++++++++++++++++++ 55_Life/csharp/Life.csproj | 9 + 55_Life/csharp/Life.sln | 16 ++ 55_Life/csharp/Program.cs | 37 +++ 4 files changed, 571 insertions(+) create mode 100644 55_Life/csharp/.gitignore create mode 100644 55_Life/csharp/Life.csproj create mode 100644 55_Life/csharp/Life.sln create mode 100644 55_Life/csharp/Program.cs diff --git a/55_Life/csharp/.gitignore b/55_Life/csharp/.gitignore new file mode 100644 index 00000000..e96e7522 --- /dev/null +++ b/55_Life/csharp/.gitignore @@ -0,0 +1,509 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/dotnetcore,rider,visualstudio,visualstudiocode +# Edit at https://www.toptal.com/developers/gitignore?templates=dotnetcore,rider,visualstudio,visualstudiocode + +### DotnetCore ### +# .NET Core build folders +bin/ +obj/ + +# Common node modules locations +/node_modules +/wwwroot/node_modules + +### Rider ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# Support for Project snippet scope + +### VisualStudio ### +## 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 +*.code-workspace + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/dotnetcore,rider,visualstudio,visualstudiocode diff --git a/55_Life/csharp/Life.csproj b/55_Life/csharp/Life.csproj new file mode 100644 index 00000000..7311ef16 --- /dev/null +++ b/55_Life/csharp/Life.csproj @@ -0,0 +1,9 @@ + + + + Exe + net6.0 + enable + + + diff --git a/55_Life/csharp/Life.sln b/55_Life/csharp/Life.sln new file mode 100644 index 00000000..1f6131b8 --- /dev/null +++ b/55_Life/csharp/Life.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Life", "Life.csproj", "{28B02688-78D1-4B3E-B998-BCC78C292D03}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {28B02688-78D1-4B3E-B998-BCC78C292D03}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28B02688-78D1-4B3E-B998-BCC78C292D03}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28B02688-78D1-4B3E-B998-BCC78C292D03}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28B02688-78D1-4B3E-B998-BCC78C292D03}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs new file mode 100644 index 00000000..e12d5b7d --- /dev/null +++ b/55_Life/csharp/Program.cs @@ -0,0 +1,37 @@ +// See https://aka.ms/new-console-template for more information + +const int MaxWidth = 70; +const int MaxHeight = 24; + +PrintHeader(); + +int x1 = 1, y1 = 1; +int x2 = 24, y2 = 70; +var a = new float[24, 70]; +var b = new string[24]; +var c = 1; + +Console.WriteLine("ENTER YOUR PATTERN:"); +b[c] = Console.ReadLine(); +if (b[c] == "DONE") + b[c] = "" + + +void PrintHeader() +{ + const int pageWidth = 64; + + void PrintCentered(string text) + { + var spaceCount = (pageWidth - text.Length) / 2; + Console.Write(new string(' ', spaceCount)); + Console.WriteLine(text); + } + + PrintCentered("LIFE"); + PrintCentered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); + Console.WriteLine(); + Console.WriteLine(); + Console.WriteLine(); +} + From ade38d696998a222e693a37916132c2cdc8dbffd Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:40:50 -0300 Subject: [PATCH 02/14] Another step. --- 55_Life/csharp/Program.cs | 151 ++++++++++++++++++++++++++++++++++---- 1 file changed, 137 insertions(+), 14 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index e12d5b7d..6a8ed618 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -1,21 +1,23 @@ // See https://aka.ms/new-console-template for more information -const int MaxWidth = 70; -const int MaxHeight = 24; +IEnumerable ReadPattern(int limitHeight) +{ + for (var i = 0; i < limitHeight; i++) + { + var input = Console.ReadLine(); + if (input.ToUpper() == "DONE") + { + yield return string.Empty; + break; + } -PrintHeader(); - -int x1 = 1, y1 = 1; -int x2 = 24, y2 = 70; -var a = new float[24, 70]; -var b = new string[24]; -var c = 1; - -Console.WriteLine("ENTER YOUR PATTERN:"); -b[c] = Console.ReadLine(); -if (b[c] == "DONE") - b[c] = "" + // kept for compatibility + if (input.StartsWith('.')) + yield return input.Substring(1, input.Length - 2); + yield return input; + } +} void PrintHeader() { @@ -35,3 +37,124 @@ void PrintHeader() Console.WriteLine(); } +(int index, string value) GetLongestInput(IEnumerable strings) +{ + return strings + .Select((value, index) => (index, value)) + .OrderByDescending(input => input.value.Length) + .First(); +} + + +PrintHeader(); + +Console.WriteLine("ENTER YOUR PATTERN:"); +// var pattern = ReadPattern(limitHeight: MaxHeight).ToArray(); +var pattern = new string[] { "a", "bdc", "", "pattern" }; // FOR DEBUGGING PURPOSES +var (index, value) = GetLongestInput(pattern); +Console.WriteLine("" + index + ", " + value); + +// B = pattern + +int x1 = (11 - index / 2) - 1; +int y1 = (33 - value.Length / 2) - 1; +const int MaxWidth = 70; // Y2 +const int MaxHeight = 24; // X2 + +var a = new int[24, 70]; // TODO understand it +int population = 0; + +// count initial population? +for (var x = 0; x < pattern.Length; x++) +{ + for (var y = 0; y < pattern[x].Length; y++) + { + if (pattern[x][y] != ' ') + { + a[x1 + x, y1 + y] = 1; + population++; + } + } +} + +void ProcessGeneration() +{ + void PrintPopulation(int generation, int population) + { + Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); + var i9 = false; // TODO understand + if (i9) + Console.WriteLine("INVALID!"); + } + int generation = 1; + PrintPopulation(generation, population); + + int x3 = MaxHeight, y3 = MaxWidth; + int x4 = 1, y4 = 1; + + for (int x = 0; x < x1; x++) + { + Console.WriteLine(); + } + + for (var x = x1; x < MaxHeight; x++) + { + Console.WriteLine(); + for (var y = y1; y < MaxWidth; y++) + { + if (a[x, y] == 2) + { + a[x, y] = 0; // birth? + continue; + } + + if (a[x, y] == 3) + { + a[x, y] = 1; + Console.WriteLine(new string('\t', y+1) + "*"); + continue; + } + + // TODO understand what it does + if (x < x3) x3 = x; + if (x > x4) x4 = x; + if (y < y3) y3 = y; + if (y < y4) y4 = y; + } + } + +} + +PrintMatrix(a); +void PrintMatrix(int[,] matrix) +{ + Console.WriteLine("Matrix:"); + for (int x = 0; x < matrix.GetLength(0); x++) + { + for (int y = 0; y < matrix.GetLength(1); y++) + { + Console.Write(matrix[x, y].ToString()); + } + Console.WriteLine(); + } +} + +Console.WriteLine(); +Console.WriteLine(); +Console.WriteLine(); +ProcessGeneration(); + + + + + + +// int x1 = 1, y1 = 1; +// int x2 = 24, y2 = 70; + +// var b = new string[24]; + + + + + From 53d2943f934dbbb38e78ae3e9d1d0d81e6fcfefd Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:41:28 -0300 Subject: [PATCH 03/14] Not working yet. --- 55_Life/csharp/Program.cs | 204 +++++++++++++++++++++++++++----------- 1 file changed, 148 insertions(+), 56 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index 6a8ed618..ab995aa5 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -1,5 +1,7 @@ // See https://aka.ms/new-console-template for more information +using System.Xml; + IEnumerable ReadPattern(int limitHeight) { for (var i = 0; i < limitHeight; i++) @@ -50,82 +52,43 @@ PrintHeader(); Console.WriteLine("ENTER YOUR PATTERN:"); // var pattern = ReadPattern(limitHeight: MaxHeight).ToArray(); -var pattern = new string[] { "a", "bdc", "", "pattern" }; // FOR DEBUGGING PURPOSES +var pattern = new[] +{ + " ", + " * ", + " * ", + " * ", + " " +}; // FOR DEBUGGING PURPOSES var (index, value) = GetLongestInput(pattern); Console.WriteLine("" + index + ", " + value); // B = pattern -int x1 = (11 - index / 2) - 1; -int y1 = (33 - value.Length / 2) - 1; + const int MaxWidth = 70; // Y2 const int MaxHeight = 24; // X2 -var a = new int[24, 70]; // TODO understand it +var matrix = new int[24, 70]; // TODO understand it int population = 0; +var isInvalid = false; // TODO understand -// count initial population? + +int x1 = (11 - index / 2) - 1; // middle x +int y1 = (33 - value.Length / 2) - 1; // middle y for (var x = 0; x < pattern.Length; x++) { for (var y = 0; y < pattern[x].Length; y++) { if (pattern[x][y] != ' ') { - a[x1 + x, y1 + y] = 1; - population++; + matrix[x1 + x, y1 + y] = 1; // copy the pattern to the middle of the simulation + population++; // increments the population } } } -void ProcessGeneration() -{ - void PrintPopulation(int generation, int population) - { - Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); - var i9 = false; // TODO understand - if (i9) - Console.WriteLine("INVALID!"); - } - int generation = 1; - PrintPopulation(generation, population); - - int x3 = MaxHeight, y3 = MaxWidth; - int x4 = 1, y4 = 1; - - for (int x = 0; x < x1; x++) - { - Console.WriteLine(); - } - - for (var x = x1; x < MaxHeight; x++) - { - Console.WriteLine(); - for (var y = y1; y < MaxWidth; y++) - { - if (a[x, y] == 2) - { - a[x, y] = 0; // birth? - continue; - } - - if (a[x, y] == 3) - { - a[x, y] = 1; - Console.WriteLine(new string('\t', y+1) + "*"); - continue; - } - - // TODO understand what it does - if (x < x3) x3 = x; - if (x > x4) x4 = x; - if (y < y3) y3 = y; - if (y < y4) y4 = y; - } - } - -} - -PrintMatrix(a); +PrintMatrix(matrix); void PrintMatrix(int[,] matrix) { Console.WriteLine("Matrix:"); @@ -139,6 +102,135 @@ void PrintMatrix(int[,] matrix) } } + + +int generation = 0; + +void ProcessGeneration() +{ + generation++; + void PrintPopulation(int generation, int population) + { + Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); + if (isInvalid) + Console.WriteLine("INVALID!"); + } + PrintPopulation(generation, population); + + int nextMaxX = MaxHeight, nextMaxY = MaxWidth; + int nextMinX = 1, nextMinY = 1; + + for (int x = 0; x < x1; x++) + { + Console.WriteLine(); + } + + for (var x = x1; x < MaxHeight; x++) + { + Console.WriteLine(); + for (var y = y1; y < MaxWidth; y++) + { + if (matrix[x, y] == 2) + { + matrix[x, y] = 0; + continue; + } + + if (matrix[x, y] == 3) + { + matrix[x, y] = 1; // birth? + Console.WriteLine(new string(' ', y+1) + "*"); + continue; + } + + nextMinX = Math.Min(x, nextMinX); + nextMaxX = Math.Max(x, nextMaxX); + nextMinY = Math.Min(y, nextMinY); + nextMaxY = Math.Max(y, nextMaxY); + } + } + + var x2 = MaxHeight; + for (int x = x2 + 1; x < MaxHeight; x++) // TODO test +1 + { + Console.WriteLine(); + } + + x1 = nextMaxX; + x2 = nextMinX; + y1 = nextMaxY; + var y2 = nextMinY; + + // TODO boundaries? review + if (x1 < 3) + { + x1 = 3; + isInvalid = true; + } + + if (x2 > 22) + { + x2 = 22; + isInvalid = true; + } + + if (y1 < 3) + { + y1 = 3; + isInvalid = true; + } + + if (y2 > 68) + { + y2 = 68; + isInvalid = true; + } + + ProcessPopulation(); + // TODO line 635 + + void ProcessPopulation() + { + var population = 0; + for (int x = x1 - 1; x < x2 + 1; x++) // TODO review indices + { + for (int y = y1 - 1; y < y2 + 1; y++) // TODO review indices + { + var counter = 0; + for (int i = x - 1; i < x + 1; i++) + { + for (int j = y - 1; j < y + 1; j++) + { + if (matrix[i, j] == 1 || matrix[i, j] == 2) + counter++; + } + } + + if (matrix[x, y] == 0) + { + if (counter == 3) + { + matrix[x, y] = 2; + population++; + } + } + else if (counter is < 3 or > 4) + { + matrix[x, y] = 2; + } + else + { + population++; + } + } + } + } + PrintMatrix(matrix); + ProcessGeneration(); +} + + + Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); From be5e35f7e0c887b53304543d1a055326c12b9c3c Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:42:40 -0300 Subject: [PATCH 04/14] Got it working. --- 55_Life/csharp/Program.cs | 347 ++++++++++++++++++++++++-------------- 1 file changed, 216 insertions(+), 131 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index ab995aa5..0f78a6e4 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -1,6 +1,6 @@ // See https://aka.ms/new-console-template for more information -using System.Xml; +using System.Text; IEnumerable ReadPattern(int limitHeight) { @@ -47,6 +47,10 @@ void PrintHeader() .First(); } +try +{ + + PrintHeader(); @@ -54,11 +58,9 @@ Console.WriteLine("ENTER YOUR PATTERN:"); // var pattern = ReadPattern(limitHeight: MaxHeight).ToArray(); var pattern = new[] { - " ", - " * ", - " * ", - " * ", - " " + "*", + "*", + "*" }; // FOR DEBUGGING PURPOSES var (index, value) = GetLongestInput(pattern); Console.WriteLine("" + index + ", " + value); @@ -69,26 +71,42 @@ Console.WriteLine("" + index + ", " + value); const int MaxWidth = 70; // Y2 const int MaxHeight = 24; // X2 -var matrix = new int[24, 70]; // TODO understand it -int population = 0; +// var matrix = new int[24, 70]; // TODO understand it +var matrixSpace = new MatrixSpace(height: 24, width: 70); +// int population = 0; var isInvalid = false; // TODO understand -int x1 = (11 - index / 2) - 1; // middle x -int y1 = (33 - value.Length / 2) - 1; // middle y -for (var x = 0; x < pattern.Length; x++) -{ - for (var y = 0; y < pattern[x].Length; y++) + +int minX = (11 - index / 2) - 1; // middle x +int minY = (33 - value.Length / 2) - 1; // middle y +int maxX = MaxHeight; +int maxY = MaxWidth; +var simulation = InitializeSimulation(pattern, matrixSpace); + + + +Simulation InitializeSimulation(string[] inputPattern, MatrixSpace matrixToInitialize) { + var newSimulation = new Simulation(); + + for (var x = 0; x < inputPattern.Length; x++) { - if (pattern[x][y] != ' ') + for (var y = 0; y < inputPattern[x].Length; y++) { - matrix[x1 + x, y1 + y] = 1; // copy the pattern to the middle of the simulation - population++; // increments the population + if (inputPattern[x][y] != ' ') + { + matrixToInitialize.Matrix[minX + x, minY + y] = 1; // copy the pattern to the middle of the simulation + // population++; // increments the population + newSimulation.IncreasePopulation(); + } } } + + return newSimulation; } -PrintMatrix(matrix); + +// PrintMatrix(matrixSpace.Matrix); void PrintMatrix(int[,] matrix) { Console.WriteLine("Matrix:"); @@ -96,149 +114,191 @@ void PrintMatrix(int[,] matrix) { for (int y = 0; y < matrix.GetLength(1); y++) { - Console.Write(matrix[x, y].ToString()); + var character = matrix[x, y] == 0 ? ' ' : '*'; + Console.Write(character); } Console.WriteLine(); } } - - -int generation = 0; - -void ProcessGeneration() -{ - generation++; - void PrintPopulation(int generation, int population) + void ProcessGeneration() { - Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); - if (isInvalid) - Console.WriteLine("INVALID!"); - } - PrintPopulation(generation, population); - - int nextMaxX = MaxHeight, nextMaxY = MaxWidth; - int nextMinX = 1, nextMinY = 1; - - for (int x = 0; x < x1; x++) - { - Console.WriteLine(); - } - - for (var x = x1; x < MaxHeight; x++) - { - Console.WriteLine(); - for (var y = y1; y < MaxWidth; y++) + var matrix = matrixSpace.Matrix; // TODO refactor + + // generation++; + + void PrintPopulation(int generation, int population) { - if (matrix[x, y] == 2) - { - matrix[x, y] = 0; - continue; - } - - if (matrix[x, y] == 3) - { - matrix[x, y] = 1; // birth? - Console.WriteLine(new string(' ', y+1) + "*"); - continue; - } - - nextMinX = Math.Min(x, nextMinX); - nextMaxX = Math.Max(x, nextMaxX); - nextMinY = Math.Min(y, nextMinY); - nextMaxY = Math.Max(y, nextMaxY); + Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); + if (isInvalid) + Console.WriteLine("INVALID!"); } - } + PrintPopulation(simulation.Generation, simulation.Population); - var x2 = MaxHeight; - for (int x = x2 + 1; x < MaxHeight; x++) // TODO test +1 - { - Console.WriteLine(); - } + simulation.StartNewGeneration(); - x1 = nextMaxX; - x2 = nextMinX; - y1 = nextMaxY; - var y2 = nextMinY; - - // TODO boundaries? review - if (x1 < 3) - { - x1 = 3; - isInvalid = true; - } + // LINE 215 + // x3 = 24 = MaxHeight + // y3 = 70 = MaxWidth + // x4 = 1 + // y4 = 1 + // g = g + 1 - if (x2 > 22) - { - x2 = 22; - isInvalid = true; - } - - if (y1 < 3) - { - y1 = 3; - isInvalid = true; - } - - if (y2 > 68) - { - y2 = 68; - isInvalid = true; - } - - ProcessPopulation(); - // TODO line 635 - - void ProcessPopulation() - { - var population = 0; - for (int x = x1 - 1; x < x2 + 1; x++) // TODO review indices + int nextMinX = MaxHeight - 1; // x4 + int nextMinY = MaxWidth - 1; // y4 + int nextMaxX = 0; // x3 + int nextMaxY = 0; // y3 + + + // prints lines before + for (int x = 0; x < minX; x++) { - for (int y = y1 - 1; y < y2 + 1; y++) // TODO review indices + Console.WriteLine(); + } + + // prints matrix and + for (var x = minX; x < maxX; x++) + { + var printedLine = Enumerable.Repeat(' ', MaxWidth).ToList(); + for (var y = minY; y < maxY; y++) { - var counter = 0; - for (int i = x - 1; i < x + 1; i++) + if (matrix[x, y] == 2) { - for (int j = y - 1; j < y + 1; j++) - { - if (matrix[i, j] == 1 || matrix[i, j] == 2) - counter++; - } + matrix[x, y] = 0; + continue; + } + if (matrix[x, y] == 3) + { + matrix[x, y] = 1; + } + else if (matrix[x, y] != 1) + { + continue; } - if (matrix[x, y] == 0) + printedLine[y] = '*'; + + nextMinX = Math.Min(x, nextMinX); + nextMaxX = Math.Max(x+1, nextMaxX); + nextMinY = Math.Min(y, nextMinY); + nextMaxY = Math.Max(y+1, nextMaxY); + } + Console.WriteLine(string.Join(separator: null, values: printedLine)); + } + + // prints lines after + for (int x = maxX + 1; x < MaxHeight; x++) // TODO test +1 + { + Console.WriteLine(); + } + Console.WriteLine(); + + minX = nextMinX; + maxX = nextMaxX; + minY = nextMinY; + maxY = nextMaxY; + + // TODO boundaries? review + if (minX < 3) + { + minX = 3; + isInvalid = true; + } + if (maxX > 22) + { + maxX = 22; + isInvalid = true; + } + if (minY < 3) + { + minY = 3; + isInvalid = true; + } + if (maxY > 68) + { + maxY = 68; + isInvalid = true; + } + + // LINE 309 + ProcessPopulation(); + + void ProcessPopulation() + { + // var population = 0; + for (int x = minX - 1; x < maxX + 2; x++) // TODO review indices + { + for (int y = minY - 1; y < maxY + 2; y++) // TODO review indices { - if (counter == 3) + var neighbors = 0; + for (int i = x - 1; i < x + 2; i++) // TODO review indices + { + for (int j = y - 1; j < y + 2; j++) // TODO review indices + { + if (matrix[i, j] == 1 || matrix[i, j] == 2) + neighbors++; + } + } + // PrintMatrix(matrix); + if (matrix[x, y] == 0) + { + if (neighbors == 3) + { + matrix[x, y] = 3; + // population++; + simulation.IncreasePopulation(); + } + } + else if (neighbors is < 3 or > 4) { matrix[x, y] = 2; - population++; + } + else + { + // population++; + simulation.IncreasePopulation(); } } - else if (counter is < 3 or > 4) - { - matrix[x, y] = 2; - } - else - { - population++; - } } + + // LINE 635 + minX--; + minY--; + maxX++; + maxY++; } + // PrintMatrix(matrix); + ProcessGeneration(); } - PrintMatrix(matrix); + + + + Console.WriteLine(); + Console.WriteLine(); + Console.WriteLine(); ProcessGeneration(); } +catch (Exception e) +{ + Console.WriteLine(e); +} +public class Simulation +{ + public int Generation { get; private set; } + public int Population { get; private set; } + public void StartNewGeneration() + { + Generation++; + Population = 0; + } -Console.WriteLine(); -Console.WriteLine(); -Console.WriteLine(); -ProcessGeneration(); - - - - + public void IncreasePopulation() + { + Population++; + } +} // int x1 = 1, y1 = 1; @@ -250,3 +310,28 @@ ProcessGeneration(); +public class MatrixSpace +{ + public int[,] Matrix { get; } + + public MatrixSpace(int height, int width) + { + Matrix = new int[height, width]; + } + + public override string ToString() + { + var stringBuilder = new StringBuilder(); + for (var x = 0; x < Matrix.GetLength(0); x++) + { + for (var y = 0; y < Matrix.GetLength(1); y++) + { + var character = Matrix[x, y] == 0 ? " ": Matrix[x, y].ToString(); + stringBuilder.Append(character); + } + + stringBuilder.AppendLine(); + } + return stringBuilder.ToString(); + } +} From 44b1ada7d4882f59cd8b51b33c2deb221722de31 Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:43:14 -0300 Subject: [PATCH 05/14] Eliminated StackOverflow bug. --- 55_Life/csharp/Program.cs | 66 +++++++++++++++------------------------ 1 file changed, 26 insertions(+), 40 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index 0f78a6e4..0496fd91 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -47,10 +47,6 @@ void PrintHeader() .First(); } -try -{ - - PrintHeader(); @@ -106,33 +102,22 @@ Simulation InitializeSimulation(string[] inputPattern, MatrixSpace matrixToIniti } -// PrintMatrix(matrixSpace.Matrix); -void PrintMatrix(int[,] matrix) +void ProcessGeneration() { - Console.WriteLine("Matrix:"); - for (int x = 0; x < matrix.GetLength(0); x++) - { - for (int y = 0; y < matrix.GetLength(1); y++) - { - var character = matrix[x, y] == 0 ? ' ' : '*'; - Console.Write(character); - } - Console.WriteLine(); - } -} + var matrix = matrixSpace.Matrix; // TODO refactor - void ProcessGeneration() + while (true) { - var matrix = matrixSpace.Matrix; // TODO refactor - + // generation++; - + void PrintPopulation(int generation, int population) { Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); if (isInvalid) Console.WriteLine("INVALID!"); } + PrintPopulation(simulation.Generation, simulation.Population); simulation.StartNewGeneration(); @@ -148,14 +133,14 @@ void PrintMatrix(int[,] matrix) int nextMinY = MaxWidth - 1; // y4 int nextMaxX = 0; // x3 int nextMaxY = 0; // y3 - - + + // prints lines before for (int x = 0; x < minX; x++) { Console.WriteLine(); } - + // prints matrix and for (var x = minX; x < maxX; x++) { @@ -164,9 +149,10 @@ void PrintMatrix(int[,] matrix) { if (matrix[x, y] == 2) { - matrix[x, y] = 0; + matrix[x, y] = 0; continue; } + if (matrix[x, y] == 3) { matrix[x, y] = 1; @@ -179,10 +165,11 @@ void PrintMatrix(int[,] matrix) printedLine[y] = '*'; nextMinX = Math.Min(x, nextMinX); - nextMaxX = Math.Max(x+1, nextMaxX); + nextMaxX = Math.Max(x + 1, nextMaxX); nextMinY = Math.Min(y, nextMinY); - nextMaxY = Math.Max(y+1, nextMaxY); + nextMaxY = Math.Max(y + 1, nextMaxY); } + Console.WriteLine(string.Join(separator: null, values: printedLine)); } @@ -191,29 +178,33 @@ void PrintMatrix(int[,] matrix) { Console.WriteLine(); } + Console.WriteLine(); minX = nextMinX; maxX = nextMaxX; minY = nextMinY; maxY = nextMaxY; - + // TODO boundaries? review if (minX < 3) { minX = 3; isInvalid = true; } + if (maxX > 22) { maxX = 22; isInvalid = true; } + if (minY < 3) { minY = 3; isInvalid = true; } + if (maxY > 68) { maxY = 68; @@ -239,6 +230,7 @@ void PrintMatrix(int[,] matrix) neighbors++; } } + // PrintMatrix(matrix); if (matrix[x, y] == 0) { @@ -268,20 +260,14 @@ void PrintMatrix(int[,] matrix) maxY++; } // PrintMatrix(matrix); - ProcessGeneration(); } - - - - Console.WriteLine(); - Console.WriteLine(); - Console.WriteLine(); - ProcessGeneration(); -} -catch (Exception e) -{ - Console.WriteLine(e); } + +Console.WriteLine(); +Console.WriteLine(); +Console.WriteLine(); +ProcessGeneration(); + public class Simulation { public int Generation { get; private set; } From d9ab235585aab5558a2c10d6211ad192bf9e7c27 Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:43:44 -0300 Subject: [PATCH 06/14] Some initial refactorings. --- 55_Life/csharp/Program.cs | 201 +++++++++++++++++--------------------- 1 file changed, 90 insertions(+), 111 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index 0496fd91..ec925faa 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -39,16 +39,10 @@ void PrintHeader() Console.WriteLine(); } -(int index, string value) GetLongestInput(IEnumerable strings) -{ - return strings - .Select((value, index) => (index, value)) - .OrderByDescending(input => input.value.Length) - .First(); -} -PrintHeader(); + + Console.WriteLine("ENTER YOUR PATTERN:"); // var pattern = ReadPattern(limitHeight: MaxHeight).ToArray(); @@ -58,59 +52,59 @@ var pattern = new[] "*", "*" }; // FOR DEBUGGING PURPOSES +// var pattern = new[] +// { +// "**", +// "**", +// }; // FOR DEBUGGING PURPOSES +// var pattern = new[] +// { +// "***", +// "*", +// }; // FOR DEBUGGING PURPOSES + + +const int MaxWidth = 70; +const int MaxHeight = 24; + +var isInvalid = false; + var (index, value) = GetLongestInput(pattern); -Console.WriteLine("" + index + ", " + value); - -// B = pattern - - -const int MaxWidth = 70; // Y2 -const int MaxHeight = 24; // X2 - -// var matrix = new int[24, 70]; // TODO understand it -var matrixSpace = new MatrixSpace(height: 24, width: 70); -// int population = 0; -var isInvalid = false; // TODO understand - - - int minX = (11 - index / 2) - 1; // middle x int minY = (33 - value.Length / 2) - 1; // middle y int maxX = MaxHeight; int maxY = MaxWidth; -var simulation = InitializeSimulation(pattern, matrixSpace); +var matrix = new Matrix(height: MaxHeight, width: MaxWidth); +var simulation = InitializeSimulation(pattern, matrix); + +PrintHeader(); +Console.WriteLine(); +Console.WriteLine(); +Console.WriteLine(); +ProcessGeneration(); - -Simulation InitializeSimulation(string[] inputPattern, MatrixSpace matrixToInitialize) { +Simulation InitializeSimulation(IReadOnlyList inputPattern, Matrix matrixToInitialize) { var newSimulation = new Simulation(); - for (var x = 0; x < inputPattern.Length; x++) + for (var x = 0; x < inputPattern.Count; x++) { for (var y = 0; y < inputPattern[x].Length; y++) { - if (inputPattern[x][y] != ' ') - { - matrixToInitialize.Matrix[minX + x, minY + y] = 1; // copy the pattern to the middle of the simulation - // population++; // increments the population - newSimulation.IncreasePopulation(); - } + if (inputPattern[x][y] == ' ') continue; + + matrixToInitialize[minX + x, minY + y] = 1; // copy the pattern to the middle of the simulation + newSimulation.IncreasePopulation(); } } return newSimulation; } - void ProcessGeneration() { - var matrix = matrixSpace.Matrix; // TODO refactor - while (true) { - - // generation++; - void PrintPopulation(int generation, int population) { Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); @@ -123,25 +117,18 @@ void ProcessGeneration() simulation.StartNewGeneration(); // LINE 215 - // x3 = 24 = MaxHeight - // y3 = 70 = MaxWidth - // x4 = 1 - // y4 = 1 - // g = g + 1 + var nextMinX = MaxHeight - 1; + var nextMinY = MaxWidth - 1; + var nextMaxX = 0; + var nextMaxY = 0; - int nextMinX = MaxHeight - 1; // x4 - int nextMinY = MaxWidth - 1; // y4 - int nextMaxX = 0; // x3 - int nextMaxY = 0; // y3 - - - // prints lines before - for (int x = 0; x < minX; x++) + // prints empty lines before alive cells + for (var x = 0; x < minX; x++) { Console.WriteLine(); } - // prints matrix and + // refreshes the matrix and updates search area for (var x = minX; x < maxX; x++) { var printedLine = Enumerable.Repeat(' ', MaxWidth).ToList(); @@ -152,7 +139,6 @@ void ProcessGeneration() matrix[x, y] = 0; continue; } - if (matrix[x, y] == 3) { matrix[x, y] = 1; @@ -173,12 +159,11 @@ void ProcessGeneration() Console.WriteLine(string.Join(separator: null, values: printedLine)); } - // prints lines after - for (int x = maxX + 1; x < MaxHeight; x++) // TODO test +1 + // prints empty lines after alive cells + for (int x = maxX + 1; x < MaxHeight; x++) { Console.WriteLine(); } - Console.WriteLine(); minX = nextMinX; @@ -211,62 +196,60 @@ void ProcessGeneration() isInvalid = true; } - // LINE 309 - ProcessPopulation(); - - void ProcessPopulation() + for (var x = minX - 1; x < maxX + 2; x++) { - // var population = 0; - for (int x = minX - 1; x < maxX + 2; x++) // TODO review indices + for (var y = minY - 1; y < maxY + 2; y++) { - for (int y = minY - 1; y < maxY + 2; y++) // TODO review indices + int CountNeighbors() { var neighbors = 0; - for (int i = x - 1; i < x + 2; i++) // TODO review indices + for (var i = x - 1; i < x + 2; i++) { - for (int j = y - 1; j < y + 2; j++) // TODO review indices + for (var j = y - 1; j < y + 2; j++) { if (matrix[i, j] == 1 || matrix[i, j] == 2) neighbors++; } } - // PrintMatrix(matrix); - if (matrix[x, y] == 0) + return neighbors; + } + + var neighbors = CountNeighbors(); + if (matrix[x, y] == 0) + { + if (neighbors == 3) { - if (neighbors == 3) - { - matrix[x, y] = 3; - // population++; - simulation.IncreasePopulation(); - } - } - else if (neighbors is < 3 or > 4) - { - matrix[x, y] = 2; - } - else - { - // population++; + matrix[x, y] = 3; simulation.IncreasePopulation(); } } + else if (neighbors is < 3 or > 4) + { + matrix[x, y] = 2; + } + else + { + simulation.IncreasePopulation(); + } } - - // LINE 635 - minX--; - minY--; - maxX++; - maxY++; } - // PrintMatrix(matrix); + + // expands search area to accommodate new cells + minX--; + minY--; + maxX++; + maxY++; } } -Console.WriteLine(); -Console.WriteLine(); -Console.WriteLine(); -ProcessGeneration(); +(int index, string value) GetLongestInput(IEnumerable strings) +{ + return strings + .Select((value, index) => (index, value)) + .OrderByDescending(input => input.value.Length) + .First(); +} public class Simulation { @@ -286,33 +269,29 @@ public class Simulation } } - -// int x1 = 1, y1 = 1; -// int x2 = 24, y2 = 70; - -// var b = new string[24]; - - - - - -public class MatrixSpace +class Matrix { - public int[,] Matrix { get; } + private readonly int[,] _matrix; - public MatrixSpace(int height, int width) + public Matrix(int height, int width) { - Matrix = new int[height, width]; + _matrix = new int[height, width]; } + public int this[int x, int y] + { + get => _matrix[x, y]; + set => _matrix[x, y] = value; + } + public override string ToString() { var stringBuilder = new StringBuilder(); - for (var x = 0; x < Matrix.GetLength(0); x++) + for (var x = 0; x < _matrix.GetLength(0); x++) { - for (var y = 0; y < Matrix.GetLength(1); y++) + for (var y = 0; y < _matrix.GetLength(1); y++) { - var character = Matrix[x, y] == 0 ? " ": Matrix[x, y].ToString(); + var character = _matrix[x, y] == 0 ? " ": _matrix[x, y].ToString(); stringBuilder.Append(character); } @@ -320,4 +299,4 @@ public class MatrixSpace } return stringBuilder.ToString(); } -} +} \ No newline at end of file From e53b9d9cf18fc89e6aa34130b5eb1b16cd8e782b Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:44:13 -0300 Subject: [PATCH 07/14] Further refactoring, naming procedures. --- 55_Life/csharp/Program.cs | 186 ++++++++++++++++++-------------------- 1 file changed, 89 insertions(+), 97 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index ec925faa..cc594435 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -2,47 +2,8 @@ using System.Text; -IEnumerable ReadPattern(int limitHeight) -{ - for (var i = 0; i < limitHeight; i++) - { - var input = Console.ReadLine(); - if (input.ToUpper() == "DONE") - { - yield return string.Empty; - break; - } - - // kept for compatibility - if (input.StartsWith('.')) - yield return input.Substring(1, input.Length - 2); - - yield return input; - } -} - -void PrintHeader() -{ - const int pageWidth = 64; - - void PrintCentered(string text) - { - var spaceCount = (pageWidth - text.Length) / 2; - Console.Write(new string(' ', spaceCount)); - Console.WriteLine(text); - } - - PrintCentered("LIFE"); - PrintCentered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); - Console.WriteLine(); - Console.WriteLine(); - Console.WriteLine(); -} - - - - - +const int MaxWidth = 70; +const int MaxHeight = 24; Console.WriteLine("ENTER YOUR PATTERN:"); // var pattern = ReadPattern(limitHeight: MaxHeight).ToArray(); @@ -63,26 +24,63 @@ var pattern = new[] // "*", // }; // FOR DEBUGGING PURPOSES - -const int MaxWidth = 70; -const int MaxHeight = 24; - var isInvalid = false; -var (index, value) = GetLongestInput(pattern); -int minX = (11 - index / 2) - 1; // middle x -int minY = (33 - value.Length / 2) - 1; // middle y -int maxX = MaxHeight; -int maxY = MaxWidth; +var (index, value) = FindLongestInput(pattern); +var minX = (11 - index / 2) - 1; // middle x +var minY = (33 - value.Length / 2) - 1; // middle y +var maxX = MaxHeight; +var maxY = MaxWidth; var matrix = new Matrix(height: MaxHeight, width: MaxWidth); var simulation = InitializeSimulation(pattern, matrix); PrintHeader(); -Console.WriteLine(); -Console.WriteLine(); -Console.WriteLine(); ProcessGeneration(); +IEnumerable ReadPattern(int limitHeight) +{ + for (var i = 0; i < limitHeight; i++) + { + var input = Console.ReadLine(); + if (input.ToUpper() == "DONE") + { + yield return string.Empty; + break; + } + + // kept for compatibility + if (input.StartsWith('.')) + yield return input.Substring(1, input.Length - 2); + + yield return input; + } +} + +(int index, string value) FindLongestInput(IEnumerable strings) +{ + return strings + .Select((value, index) => (index, value)) + .OrderByDescending(input => input.value.Length) + .First(); +} + +void PrintHeader() +{ + void PrintCentered(string text) + { + const int pageWidth = 64; + + var spaceCount = (pageWidth - text.Length) / 2; + Console.Write(new string(' ', spaceCount)); + Console.WriteLine(text); + } + + PrintCentered("LIFE"); + PrintCentered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); + Console.WriteLine(); + Console.WriteLine(); + Console.WriteLine(); +} Simulation InitializeSimulation(IReadOnlyList inputPattern, Matrix matrixToInitialize) { var newSimulation = new Simulation(); @@ -103,26 +101,24 @@ Simulation InitializeSimulation(IReadOnlyList inputPattern, Matrix matri void ProcessGeneration() { + void PrintPopulation(int generation, int population) + { + Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); + if (isInvalid) + Console.WriteLine("INVALID!"); + } + while (true) { - void PrintPopulation(int generation, int population) - { - Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); - if (isInvalid) - Console.WriteLine("INVALID!"); - } - PrintPopulation(simulation.Generation, simulation.Population); - simulation.StartNewGeneration(); - // LINE 215 var nextMinX = MaxHeight - 1; var nextMinY = MaxWidth - 1; var nextMaxX = 0; var nextMaxY = 0; - // prints empty lines before alive cells + // prints the empty lines before search area for (var x = 0; x < minX; x++) { Console.WriteLine(); @@ -159,42 +155,46 @@ void ProcessGeneration() Console.WriteLine(string.Join(separator: null, values: printedLine)); } - // prints empty lines after alive cells - for (int x = maxX + 1; x < MaxHeight; x++) + // prints empty lines after search area + for (var x = maxX + 1; x < MaxHeight; x++) { Console.WriteLine(); } Console.WriteLine(); - minX = nextMinX; - maxX = nextMaxX; - minY = nextMinY; - maxY = nextMaxY; - - // TODO boundaries? review - if (minX < 3) + void UpdateSearchArea() { - minX = 3; - isInvalid = true; - } + minX = nextMinX; + maxX = nextMaxX; + minY = nextMinY; + maxY = nextMaxY; - if (maxX > 22) - { - maxX = 22; - isInvalid = true; - } + // TODO boundaries? review + if (minX < 3) + { + minX = 3; + isInvalid = true; + } - if (minY < 3) - { - minY = 3; - isInvalid = true; - } + if (maxX > 22) + { + maxX = 22; + isInvalid = true; + } - if (maxY > 68) - { - maxY = 68; - isInvalid = true; + if (minY < 3) + { + minY = 3; + isInvalid = true; + } + + if (maxY > 68) + { + maxY = 68; + isInvalid = true; + } } + UpdateSearchArea(); for (var x = minX - 1; x < maxX + 2; x++) { @@ -243,14 +243,6 @@ void ProcessGeneration() } } -(int index, string value) GetLongestInput(IEnumerable strings) -{ - return strings - .Select((value, index) => (index, value)) - .OrderByDescending(input => input.value.Length) - .First(); -} - public class Simulation { public int Generation { get; private set; } From 778af346d723fec512d30e451ad84a22ab1cb9a6 Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:45:00 -0300 Subject: [PATCH 08/14] Added enum Cell to enhance clarity. --- 55_Life/csharp/Program.cs | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index cc594435..0abb68f1 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -1,10 +1,13 @@ // See https://aka.ms/new-console-template for more information +using System.Drawing; using System.Text; const int MaxWidth = 70; const int MaxHeight = 24; + + Console.WriteLine("ENTER YOUR PATTERN:"); // var pattern = ReadPattern(limitHeight: MaxHeight).ToArray(); var pattern = new[] @@ -91,7 +94,7 @@ Simulation InitializeSimulation(IReadOnlyList inputPattern, Matrix matri { if (inputPattern[x][y] == ' ') continue; - matrixToInitialize[minX + x, minY + y] = 1; // copy the pattern to the middle of the simulation + matrixToInitialize[minX + x, minY + y] = Cell.NeutralCell; // copy the pattern to the middle of the simulation newSimulation.IncreasePopulation(); } } @@ -130,16 +133,16 @@ void ProcessGeneration() var printedLine = Enumerable.Repeat(' ', MaxWidth).ToList(); for (var y = minY; y < maxY; y++) { - if (matrix[x, y] == 2) + if (matrix[x, y] == Cell.DyingCel) { matrix[x, y] = 0; continue; } - if (matrix[x, y] == 3) + if (matrix[x, y] == Cell.NewCell) { - matrix[x, y] = 1; + matrix[x, y] = Cell.NeutralCell; } - else if (matrix[x, y] != 1) + else if (matrix[x, y] != Cell.NeutralCell) { continue; } @@ -207,7 +210,7 @@ void ProcessGeneration() { for (var j = y - 1; j < y + 2; j++) { - if (matrix[i, j] == 1 || matrix[i, j] == 2) + if (matrix[i, j] == Cell.NeutralCell || matrix[i, j] == Cell.DyingCel) neighbors++; } } @@ -220,13 +223,13 @@ void ProcessGeneration() { if (neighbors == 3) { - matrix[x, y] = 3; + matrix[x, y] = Cell.NewCell; simulation.IncreasePopulation(); } } else if (neighbors is < 3 or > 4) { - matrix[x, y] = 2; + matrix[x, y] = Cell.DyingCel; } else { @@ -243,6 +246,14 @@ void ProcessGeneration() } } +internal enum Cell +{ + EmptyCell = 0, + NeutralCell = 1, + DyingCel = 2, + NewCell =3 +} + public class Simulation { public int Generation { get; private set; } @@ -263,14 +274,14 @@ public class Simulation class Matrix { - private readonly int[,] _matrix; + private readonly Cell[,] _matrix; public Matrix(int height, int width) { - _matrix = new int[height, width]; + _matrix = new Cell[height, width]; } - public int this[int x, int y] + public Cell this[int x, int y] { get => _matrix[x, y]; set => _matrix[x, y] = value; @@ -283,7 +294,7 @@ class Matrix { for (var y = 0; y < _matrix.GetLength(1); y++) { - var character = _matrix[x, y] == 0 ? " ": _matrix[x, y].ToString(); + var character = _matrix[x, y] == 0 ? " ": ((int)_matrix[x, y]).ToString(); stringBuilder.Append(character); } From 4870a14909b6055440c0445b5db1571004353518 Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:45:34 -0300 Subject: [PATCH 09/14] Refactoring, plus adding real user input again. --- 55_Life/csharp/Program.cs | 72 ++++++++++++++------------------------- 1 file changed, 25 insertions(+), 47 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index 0abb68f1..b9aef5dd 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -1,40 +1,16 @@ -// See https://aka.ms/new-console-template for more information - -using System.Drawing; -using System.Text; - -const int MaxWidth = 70; -const int MaxHeight = 24; - +using System.Text; +const int maxWidth = 70; +const int maxHeight = 24; Console.WriteLine("ENTER YOUR PATTERN:"); -// var pattern = ReadPattern(limitHeight: MaxHeight).ToArray(); -var pattern = new[] -{ - "*", - "*", - "*" -}; // FOR DEBUGGING PURPOSES -// var pattern = new[] -// { -// "**", -// "**", -// }; // FOR DEBUGGING PURPOSES -// var pattern = new[] -// { -// "***", -// "*", -// }; // FOR DEBUGGING PURPOSES +var pattern = ReadPattern(limitHeight: maxHeight).ToArray(); -var isInvalid = false; +var (minX, minY) = FindTopLeftCorner(pattern); +var maxX = maxHeight; +var maxY = maxWidth; -var (index, value) = FindLongestInput(pattern); -var minX = (11 - index / 2) - 1; // middle x -var minY = (33 - value.Length / 2) - 1; // middle y -var maxX = MaxHeight; -var maxY = MaxWidth; -var matrix = new Matrix(height: MaxHeight, width: MaxWidth); +var matrix = new Matrix(height: maxHeight, width: maxWidth); var simulation = InitializeSimulation(pattern, matrix); PrintHeader(); @@ -59,12 +35,15 @@ IEnumerable ReadPattern(int limitHeight) } } -(int index, string value) FindLongestInput(IEnumerable strings) +(int minX, int minY) FindTopLeftCorner(IEnumerable patternLines) { - return strings + var longestInput = patternLines .Select((value, index) => (index, value)) .OrderByDescending(input => input.value.Length) .First(); + var centerX = (11 - longestInput.index / 2) - 1; + var centerY = (33 - longestInput.value.Length / 2) - 1; + return (centerX, centerY); } void PrintHeader() @@ -88,13 +67,14 @@ void PrintHeader() Simulation InitializeSimulation(IReadOnlyList inputPattern, Matrix matrixToInitialize) { var newSimulation = new Simulation(); + // copies the pattern to the middle of the simulation and counts initial population for (var x = 0; x < inputPattern.Count; x++) { for (var y = 0; y < inputPattern[x].Length; y++) { if (inputPattern[x][y] == ' ') continue; - matrixToInitialize[minX + x, minY + y] = Cell.NeutralCell; // copy the pattern to the middle of the simulation + matrixToInitialize[minX + x, minY + y] = Cell.NeutralCell; newSimulation.IncreasePopulation(); } } @@ -104,20 +84,19 @@ Simulation InitializeSimulation(IReadOnlyList inputPattern, Matrix matri void ProcessGeneration() { - void PrintPopulation(int generation, int population) - { - Console.WriteLine($"GENERATION: {generation}\tPOPULATION: {population}"); - if (isInvalid) - Console.WriteLine("INVALID!"); - } + var isInvalid = false; while (true) { - PrintPopulation(simulation.Generation, simulation.Population); + // Thread.Sleep(millisecondsTimeout: 1000); + Console.WriteLine($"GENERATION: {simulation.Generation}\tPOPULATION: {simulation.Population}"); + if (isInvalid) + Console.WriteLine("INVALID!"); + simulation.StartNewGeneration(); - var nextMinX = MaxHeight - 1; - var nextMinY = MaxWidth - 1; + var nextMinX = maxHeight - 1; + var nextMinY = maxWidth - 1; var nextMaxX = 0; var nextMaxY = 0; @@ -130,7 +109,7 @@ void ProcessGeneration() // refreshes the matrix and updates search area for (var x = minX; x < maxX; x++) { - var printedLine = Enumerable.Repeat(' ', MaxWidth).ToList(); + var printedLine = Enumerable.Repeat(' ', maxWidth).ToList(); for (var y = minY; y < maxY; y++) { if (matrix[x, y] == Cell.DyingCel) @@ -159,7 +138,7 @@ void ProcessGeneration() } // prints empty lines after search area - for (var x = maxX + 1; x < MaxHeight; x++) + for (var x = maxX + 1; x < maxHeight; x++) { Console.WriteLine(); } @@ -172,7 +151,6 @@ void ProcessGeneration() minY = nextMinY; maxY = nextMaxY; - // TODO boundaries? review if (minX < 3) { minX = 3; From cd478a4a948d575ebb0ab55f34f555ac95c93bd8 Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:46:07 -0300 Subject: [PATCH 10/14] Added argument to configure a pause in between iterations, allowing the player to enjoy watching the evolution of the game of life. --- 55_Life/csharp/Program.cs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index b9aef5dd..07a06eac 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -82,13 +82,32 @@ Simulation InitializeSimulation(IReadOnlyList inputPattern, Matrix matri return newSimulation; } +TimeSpan GetPauseBetweenIterations() +{ + if (args.Length == 2) + { + var parameter = args[0].ToLower(); + if (parameter.Contains("wait")) + { + var value = args[1]; + if (int.TryParse(value, out var sleepMilliseconds)) + return TimeSpan.FromMilliseconds(sleepMilliseconds); + } + } + + return TimeSpan.Zero; +} + void ProcessGeneration() { + var pauseBetweenIterations = GetPauseBetweenIterations(); var isInvalid = false; while (true) { - // Thread.Sleep(millisecondsTimeout: 1000); + if (pauseBetweenIterations > TimeSpan.Zero) + Thread.Sleep(pauseBetweenIterations); + Console.WriteLine($"GENERATION: {simulation.Generation}\tPOPULATION: {simulation.Population}"); if (isInvalid) Console.WriteLine("INVALID!"); From 3ffd2fdc520145d42b65becb51b6ae9cc87163aa Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:46:39 -0300 Subject: [PATCH 11/14] Refactoring and documenting the solution. --- 55_Life/csharp/Program.cs | 50 +++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index 07a06eac..f2b66b88 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -14,7 +14,7 @@ var matrix = new Matrix(height: maxHeight, width: maxWidth); var simulation = InitializeSimulation(pattern, matrix); PrintHeader(); -ProcessGeneration(); +ProcessSimulation(); IEnumerable ReadPattern(int limitHeight) { @@ -27,7 +27,9 @@ IEnumerable ReadPattern(int limitHeight) break; } - // kept for compatibility + // In the original version, BASIC would trim the spaces in the beginning of an input, so the original + // game allowed you to input an '.' before the spaces to circumvent this limitation. This behavior was + // kept for compatibility. if (input.StartsWith('.')) yield return input.Substring(1, input.Length - 2); @@ -67,14 +69,14 @@ void PrintHeader() Simulation InitializeSimulation(IReadOnlyList inputPattern, Matrix matrixToInitialize) { var newSimulation = new Simulation(); - // copies the pattern to the middle of the simulation and counts initial population + // translates the pattern to the middle of the simulation and counts initial population for (var x = 0; x < inputPattern.Count; x++) { for (var y = 0; y < inputPattern[x].Length; y++) { if (inputPattern[x][y] == ' ') continue; - matrixToInitialize[minX + x, minY + y] = Cell.NeutralCell; + matrixToInitialize[minX + x, minY + y] = CellState.Stable; newSimulation.IncreasePopulation(); } } @@ -98,7 +100,7 @@ TimeSpan GetPauseBetweenIterations() return TimeSpan.Zero; } -void ProcessGeneration() +void ProcessSimulation() { var pauseBetweenIterations = GetPauseBetweenIterations(); var isInvalid = false; @@ -131,16 +133,16 @@ void ProcessGeneration() var printedLine = Enumerable.Repeat(' ', maxWidth).ToList(); for (var y = minY; y < maxY; y++) { - if (matrix[x, y] == Cell.DyingCel) + if (matrix[x, y] == CellState.Dying) { - matrix[x, y] = 0; + matrix[x, y] = CellState.Empty; continue; } - if (matrix[x, y] == Cell.NewCell) + if (matrix[x, y] == CellState.New) { - matrix[x, y] = Cell.NeutralCell; + matrix[x, y] = CellState.Stable; } - else if (matrix[x, y] != Cell.NeutralCell) + else if (matrix[x, y] != CellState.Stable) { continue; } @@ -207,7 +209,7 @@ void ProcessGeneration() { for (var j = y - 1; j < y + 2; j++) { - if (matrix[i, j] == Cell.NeutralCell || matrix[i, j] == Cell.DyingCel) + if (matrix[i, j] == CellState.Stable || matrix[i, j] == CellState.Dying) neighbors++; } } @@ -220,13 +222,13 @@ void ProcessGeneration() { if (neighbors == 3) { - matrix[x, y] = Cell.NewCell; + matrix[x, y] = CellState.New; simulation.IncreasePopulation(); } } else if (neighbors is < 3 or > 4) { - matrix[x, y] = Cell.DyingCel; + matrix[x, y] = CellState.Dying; } else { @@ -243,12 +245,15 @@ void ProcessGeneration() } } -internal enum Cell +/// +/// Indicates the state of a given cell in the simulation. +/// +internal enum CellState { - EmptyCell = 0, - NeutralCell = 1, - DyingCel = 2, - NewCell =3 + Empty = 0, + Stable = 1, + Dying = 2, + New = 3 } public class Simulation @@ -269,16 +274,19 @@ public class Simulation } } +/// +/// This class was created to aid debugging, through the implementation of the ToString() method. +/// class Matrix { - private readonly Cell[,] _matrix; + private readonly CellState[,] _matrix; public Matrix(int height, int width) { - _matrix = new Cell[height, width]; + _matrix = new CellState[height, width]; } - public Cell this[int x, int y] + public CellState this[int x, int y] { get => _matrix[x, y]; set => _matrix[x, y] = value; From c7c3d68a2eed69735ae4664f3c0d7925f9545464 Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:47:08 -0300 Subject: [PATCH 12/14] Moving pause location to the end of iteration. --- 55_Life/csharp/Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index f2b66b88..1c21b5f7 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -107,9 +107,6 @@ void ProcessSimulation() while (true) { - if (pauseBetweenIterations > TimeSpan.Zero) - Thread.Sleep(pauseBetweenIterations); - Console.WriteLine($"GENERATION: {simulation.Generation}\tPOPULATION: {simulation.Population}"); if (isInvalid) Console.WriteLine("INVALID!"); @@ -242,6 +239,9 @@ void ProcessSimulation() minY--; maxX++; maxY++; + + if (pauseBetweenIterations > TimeSpan.Zero) + Thread.Sleep(pauseBetweenIterations); } } From 985e1886ac32763896a363f585e7c7f5618b3a31 Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:48:13 -0300 Subject: [PATCH 13/14] Adding comment about the port. --- 55_Life/csharp/Program.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index 1c21b5f7..2ed1ec62 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -1,4 +1,16 @@ -using System.Text; +/* + * LIFE + * An implementation of John Conway's popular cellular automaton + * Ported by Dyego Alekssander Maas + * + * An example pattern would be: + * " * " + * "***" + * "DONE" (indicates that the simulation can start) + * + * You can find patterns to play with here: http://pi.math.cornell.edu/~lipa/mec/lesson6.html +*/ +using System.Text; const int maxWidth = 70; const int maxHeight = 24; From 8c02ea39d272a157613318a0884cea6fc734faca Mon Sep 17 00:00:00 2001 From: Dyego Maas Date: Tue, 11 Jan 2022 20:58:07 -0300 Subject: [PATCH 14/14] Documented the --wait argument. --- 55_Life/csharp/Program.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/55_Life/csharp/Program.cs b/55_Life/csharp/Program.cs index 2ed1ec62..47ed7386 100644 --- a/55_Life/csharp/Program.cs +++ b/55_Life/csharp/Program.cs @@ -9,6 +9,10 @@ * "DONE" (indicates that the simulation can start) * * You can find patterns to play with here: http://pi.math.cornell.edu/~lipa/mec/lesson6.html + * + * Optionally, you can run this program with the "--wait 1000" argument, the number being the time in milliseconds + * that the application will pause between each iteration. This is enables you to watch the simulation unfolding. + * By default, there is no pause between iterations. */ using System.Text;