Git Product home page Git Product logo

Comments (21)

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: hello-world

Code


namespace HelloWorld
{
    public static class HelloWorld
    {
        public static string Hello()
        {
            return "Hello, World!";
        }
    }
}

Tags:

construct:class
construct:method
construct:namespace
construct:return
construct:string
construct:visibility-modifiers
paradigm:object-oriented

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: leap

Code

using System;

namespace Exercism.Csharp
{
    /**
        on every year that is evenly divisible by 4
        except every year that is evenly divisible by 100
        unless the year is also evenly divisible by 400
    */
    public static class Leap
    {
        public static bool IsLeapYear(int year) => 
            year % 400 == 0 || 
            (year % 100 != 0 && year % 4 == 0);
    }
}

Tags:

construct:boolean
construct:class
construct:comment
construct:divide
construct:expression-bodied-member
construct:int
construct:integral-number
construct:logical-and
construct:logical-or
construct:method
construct:namespace
construct:number
construct:parameter
construct:using-directive
construct:visibility-modifiers
paradigm:object-oriented
technique:boolean-logic

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: sum-of-multiples

Code

using System;
using System.Collections.Generic;
using System.Linq;

public static class SumOfMultiples
{
    public static int Sum(IEnumerable<int> multiples, int max)
    {
        int sum = 0;

        for(int i = 1; i < max; i++)
        {
            if (multiples.Where(n => i % n == 0).Count() >= 1)
                sum += i;
        }

        return sum;
    }
}

Tags:

construct:assignment
construct:class
construct:for-loop
construct:if
construct:implicit-conversion
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:linq
construct:method
construct:number
construct:parameter
construct:return
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:higher-order-functions
technique:looping

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: collatz-conjecture

Code

using System;

public static class CollatzConjecture
{
    public static int Steps(int number)
    {
        if (number < 1) throw new ArgumentException("Number less than 1 prohibited.");

        int steps = 0;
        while (number != 1) {
            steps++;
            if (number % 2 == 0) {
                number /= 2;
            }
            else
            {
                number = 3 * number + 1;
            }
        }
        return steps;
    }
}

Tags:

construct:add
construct:assignment
construct:class
construct:constructor
construct:if
construct:int
construct:integral-number
construct:method
construct:multiply
construct:number
construct:parameter
construct:return
construct:string
construct:throw
construct:using
construct:variable
construct:visibility-modifiers
construct:while-loop
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:looping

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: binary-search

Code

public class BinarySearch
{

	private readonly int[] source;

	public BinarySearch(int[] input)
	{
		source = input;
	}

	public int Find(int value)
	{

		if (source.Length == 0) return -1;

		var result = -1;
		var startIndex = 0;
		var endIndex = source.Length - 1;
		var halfIndex = (endIndex - startIndex) / 2 + startIndex;
		var currDirection = "?";

		// easily found
		if (source[halfIndex] == value) result = halfIndex;

		while (source[halfIndex] != value)
		{

			var lastHalfIndex = halfIndex;
			var lastDirection = currDirection;

			startIndex = source[halfIndex] < value ? halfIndex + 1 : 0;
			endIndex = source[halfIndex] < value ? source.Length - 1 : halfIndex - 1;
			halfIndex = (endIndex - startIndex) / 2 + startIndex;
			currDirection = lastHalfIndex > halfIndex ? "-" : "+";

			// changed direction, so not in array
			if (lastDirection != "?" && lastDirection != currDirection) break;

			// found
			if (source[halfIndex] == value) result = halfIndex;

			// made it to beginning or the end
			if (halfIndex == 0 || halfIndex == source.Length - 1) break;

		}

		return result;

	}

}

Tags:

construct:add
construct:assignment
construct:boolean
construct:break
construct:class
construct:comment
construct:divide
construct:field
construct:if
construct:indexer
construct:int
construct:integral-number
construct:logical-and
construct:logical-or
construct:method
construct:number
construct:parameter
construct:read-only
construct:return
construct:string
construct:subtract
construct:ternary
construct:variable
construct:visibility-modifiers
construct:while-loop
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:looping

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: etl

Code

using System;
using System.Collections.Generic;

public static class Etl
{
    public static Dictionary<string, int> Transform(Dictionary<int, string[]> old)
    {
        var newDict = new Dictionary<string, int>();
        int oldKey;

        foreach (KeyValuePair<int, string[]> item in old)
        {
          oldKey = item.Key;

          foreach (var letter in item.Value)
          {
            newDict.Add(letter.ToLower(), oldKey);
          }

        }

        return newDict;

    }
}

Tags:

construct:assignment
construct:class
construct:constructor
construct:dictionary
construct:foreach
construct:implicit-conversion
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:method
construct:parameter
construct:return
construct:string
construct:throw
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:enumeration
technique:exceptions
technique:higher-order-functions
technique:looping
uses:Dictionary<TKey,TValue>

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: anagram

Code

using System;
using System.Linq;

public class Anagram
{
    public string baseWord;

    public Anagram(string baseWord)
    {
        this.baseWord = baseWord;    
    }

    public string[] Anagrams(string[] potentialMatches)
    {
        // To detect if a string is an anagram of another, we sort the string characters and compare the sorted strings.
        // This must be case insensitive, so let's make everything lowercase, even the sort rule.

        return potentialMatches.Where(x => (x.ToLower() != this.baseWord.ToLower() )        // "BANANA" is not an anagram of "Banana"
        && (String.Concat(this.baseWord.OrderBy(c => c.ToString().ToLower())).ToLower()    
        == String.Concat(x.OrderBy(c => c.ToString().ToLower())).ToLower() ) )             
        .ToArray();                                                                        
    }
}

Tags:

construct:assignment
construct:boolean
construct:class
construct:comment
construct:field
construct:implicit-conversion
construct:invocation
construct:lambda
construct:linq
construct:logical-and
construct:method
construct:parameter
construct:return
construct:string
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:higher-order-functions

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: pascals-triangle

Code

using System.Collections.Generic;
using System.Linq;

namespace PascalsTriangle
{
    public static class PascalsTriangle
    {
        public static IEnumerable<IEnumerable<int>> Calculate(int rows)
        {
            var response = new List<List<int>>();
            for (int i = 0; i < rows; i++)
            {
                response.Add(i > 0 ? NextRow(response.Last()) : new List<int> {1});
            }

            return response;
        }

        private static List<int> NextRow(IReadOnlyList<int> previous)
        {
            var newRow = new List<int>();
            if (previous.Count > 0)
            {
                newRow.Add(previous.First());
            }

            for (int i = 1; i < previous.Count; i++)
            {
                newRow.Add(previous[i - 1] + previous[i]);
            }

            newRow.Add(1);
            return newRow;
        }
    }
}

Tags:

construct:add
construct:class
construct:collection-initializer
construct:constructor
construct:for-loop
construct:if
construct:indexer
construct:initializer
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:linq
construct:list
construct:method
construct:namespace
construct:number
construct:parameter
construct:return
construct:subtract
construct:ternary
construct:throw
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:object-oriented
technique:exceptions
technique:higher-order-functions
technique:looping
uses:List<T>

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: pascals-triangle

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exercism_Test.csharp.pascals_triangle
{
    class PascalsTriangle
    {
        public static int[][] Calculate(int tierNum)
        {
            int[][] tier = new int[tierNum][];
            tier[tierNum-1] = new int[tierNum];
            tier[tierNum-1][0] = 1;
            if (tierNum == 1)
                return tier;

            tier[tierNum-1][tierNum-1] = 1;
            int[][] pTier = Calculate(tierNum - 1);
            for (int r = 0; r < tierNum - 1; r++)
                tier[r] = pTier[r];
            for (int i = 1; i < tierNum - 1; i++)
                tier[tierNum-1][i] = tier[tierNum-2][i] + tier[tierNum-2][i - 1];
            return tier;
        }
    }
}

Tags:

construct:add
construct:assignment
construct:class
construct:for-loop
construct:if
construct:indexer
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:method
construct:namespace
construct:number
construct:parameter
construct:return
construct:subtract
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:higher-order-functions
technique:looping
technique:recursion

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: isbn-verifier

Code

using System;

public static class IsbnVerifier
{
    public static class IsbnVerifier
    {
        public static bool IsValid(string number)
        {
            var list = number.ToList();
            list.RemoveAll(c => c == '-');

            if (list.Count != 10)
                return false;

            for (int i = 0; i < list.Count() - 1; i++)
            {
                if (!char.IsDigit(list[i]))
                    return false;
            }

            if (!char.IsDigit(list[list.Count - 1]) && (list[list.Count - 1] != 'X'))
            {
                return false;
            }
            var listonfStrings = list.Select(c => c.ToString()).ToList();
            listonfStrings[9] = listonfStrings[9] == "X" ? "10" : listonfStrings[9];
            var listonfInts = listonfStrings.Select(c => Convert.ToInt32(c)).ToList();

            return (listonfInts[0] * 10 + listonfInts[1] * 9 + listonfInts[2] * 8 + listonfInts[3] * 7 + listonfInts[4] * 6 + listonfInts[5] * 5 + listonfInts[6] * 4 + listonfInts[7] * 3 + listonfInts[8] * 2 + listonfInts[9] * 1) % 11 == 0;

        }
    }
}

Tags:

construct:add
construct:assignment
construct:boolean
construct:char
construct:class
construct:for-loop
construct:if
construct:implicit-conversion
construct:indexer
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:linq
construct:list
construct:logical-and
construct:method
construct:multiply
construct:number
construct:parameter
construct:return
construct:string
construct:subtract
construct:ternary
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:higher-order-functions
technique:looping
uses:List<T>

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: atbash-cipher

Code

using System;
using System.Collections.Generic;
using System.Linq;

public class Atbash
{
    public static string Encode (string given)
    {
        var converted = given
          .ToLower()
          .Where(Char.IsLetterOrDigit)
          .Select(EncodeChar);
        return String.Join(" ", Chunk(5, converted));
    }

    private static char EncodeChar (char ch)
    {
        return Char.IsDigit(ch) ? ch : (char)('a' + 'z' - ch);
    }

    private static IEnumerable<String> Chunk (int size, IEnumerable<char> source)
    {
        while (source.Any())
        {
            yield return String.Concat(source.Take(size));
            source = source.Skip(size);
        }
    }
}

Tags:

construct:add
construct:assignment
construct:char
construct:class
construct:explicit-conversion
construct:implicit-conversion
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:linq
construct:method
construct:number
construct:parameter
construct:return
construct:string
construct:subtract
construct:ternary
construct:throw
construct:using-directive
construct:variable
construct:visibility-modifiers
construct:while-loop
construct:yield
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:higher-order-functions
technique:laziness
technique:looping
technique:type-conversion

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: matching-brackets

Code

using System;
using System.Collections.Generic;

public static class BracketPush
{
    public static bool IsPaired(string input)
    {
        Stack<char> stackBracket = new Stack<char>();
        char[] arrayInput = input.ToCharArray();
        Dictionary<char, char> dicBracket = new Dictionary<char, char> { { ')', '(' }, { ']', '['}, { '}', '{' } };
        List<char> listBracket = new List<char> { '(', ')', '[', ']', '{', '}'};
        foreach (var charTemp in arrayInput)
        {
            if(listBracket.Contains(charTemp))
            {               
                if (!dicBracket.ContainsKey(charTemp))
                {
                    stackBracket.Push(charTemp);
                }
                else
                {
                    if (stackBracket.Count != 0 && dicBracket[charTemp] == stackBracket.Peek())
                    {
                        stackBracket.Pop();
                    }
                    else return false;
                }
            }
        }
        return stackBracket.Count == 0 ? true : false;
    }
}

Tags:

construct:boolean
construct:char
construct:class
construct:collection-initializer
construct:constructor
construct:dictionary
construct:foreach
construct:if
construct:initializer
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:list
construct:logical-and
construct:method
construct:number
construct:parameter
construct:return
construct:stack
construct:ternary
construct:throw
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:object-oriented
technique:boolean-logic
technique:enumeration
technique:exceptions
technique:higher-order-functions
technique:looping
uses:Dictionary<TKey,TValue>
uses:List<T>
uses:Stack<T>

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: crypto-square

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public static class CryptoSquare
{
    public static string NormalizedPlaintext(string plaintext)
    {
        return new Regex(@"[^a-z0-9]").Replace(plaintext.ToLower(), "");
    }

    public static IEnumerable<string> PlaintextSegments(string plaintext)
    {
        int length = plaintext.Length;
        int columns = (int)Math.Ceiling(Math.Sqrt(length));
        int rows = (int)Math.Ceiling((double)length / columns);
        if (rows <= 1) yield return plaintext;
        else
        {
            var filter = Enumerable.Range(0, rows).SelectMany(f => Enumerable.Range(0, columns));

            var h = plaintext
                .Zip(filter, (character, filter) => (character, filter))
                .GroupBy(pair => pair.filter)
                .Select(group => 
                    string.Concat(group.Select(pair => pair.character)));
            
            var o = string.Join(" ", h);
            
            yield return o;
        }
    }

    public static string Ciphertext(string plaintext)
    {
        return string.Join(" ", PlaintextSegments(NormalizedPlaintext(plaintext)).ToList());
    }
}

Tags:

construct:verbatim-string
construct:class
construct:constructor
construct:divide
construct:double
construct:explicit-conversion
construct:floating-point-number
construct:if
construct:implicit-conversion
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:linq
construct:method
construct:number
construct:parameter
construct:return
construct:string
construct:tuple
construct:using-directive
construct:variable
construct:visibility-modifiers
construct:yield
paradigm:functional
paradigm:object-oriented
technique:higher-order-functions
technique:laziness
technique:regular-expression
technique:type-conversion
uses:Regex
uses:ValueTuple

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: pig-latin

Code

using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace pig_latin
{
    public static class PigLatin
    {
        internal static string Translate(string sentence)
        {
            const string ay = "ay";
            var words = (sentence ?? "").Split(' ');
            var plWords = new List<string>();
            foreach (var word in words)
            {
                var temp = word.ToLowerInvariant();
                if (Regex.Match(temp, "^([aeiou]|yt|xr)").Success)
                    plWords.Add(temp + ay);
                else if (Regex.Match(temp, "^(thr|sch)").Success)
                    plWords.Add(temp.Remove(0, 3) + temp.Substring(0, 3) + ay);
                else if (Regex.Match(temp, "^(ch|qu|th)").Success)
                    plWords.Add(temp.Remove(0, 2) + temp.Substring(0, 2) + ay);
                else if (Regex.Match(temp, "^\\wqu").Success)
                    plWords.Add(temp.Remove(0, 3) + temp.Substring(0, 3) + ay);
                else
                    plWords.Add(temp.Remove(0, 1) + temp.Substring(0, 1) + ay);
            }
            return string.Join(" ", plWords);
        }
    }
}

Tags:

construct:add
construct:char
construct:class
construct:const
construct:constructor
construct:foreach
construct:if
construct:implicit-conversion
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:list
construct:method
construct:namespace
construct:number
construct:parameter
construct:return
construct:string
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:object-oriented
technique:enumeration
technique:higher-order-functions
technique:looping
technique:regular-expression
uses:List<T>
uses:Regex

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: pig-latin

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class PigLatin
{
  public static string Translate(string input)
  {
    string output = "";
    Regex vowels = new Regex(@"^[aeiou]");

    Regex special = new Regex(@"^xr|^yt");
    Regex trios = new Regex(@"^sch|^squ|^thr");
    Regex duos = new Regex(@"^ch|^qu|^th");

    string[] inputArray = input.Split(' ');

    foreach (string word in inputArray)
    {
      if (vowels.Match(word).Success || special.Match(word).Success)
        output += word + "ay ";
      else if (trios.Match(word).Success)
        output += word.Substring(3) + word.Substring(0, 3) + "ay ";
      else if (duos.Match(word).Success)
        output += word.Substring(2) + word.Substring(0, 2) + "ay ";
      else
        output += word.Substring(1) + word.Substring(0, 1) + "ay ";
    }
    return output.Trim();
  }
}

Tags:

construct:verbatim-string
construct:add
construct:assignment
construct:boolean
construct:char
construct:class
construct:constructor
construct:foreach
construct:if
construct:implicit-conversion
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:logical-or
construct:method
construct:number
construct:parameter
construct:return
construct:string
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:enumeration
technique:higher-order-functions
technique:looping
technique:regular-expression
uses:Regex

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: complex-numbers

Code

using System;

public struct ComplexNumber
{
    public double RealPart {get;set;}
    public double ImaginaryPart { get; set; }

    public ComplexNumber(double real, double imaginary)
    {
        RealPart = real;
        ImaginaryPart = imaginary;
    }

    public double Real()
    {
        return RealPart;
    }

    public double Imaginary()
    {
        return ImaginaryPart;
    }

    public ComplexNumber Mul(ComplexNumber other)
    {
        return new ComplexNumber(RealPart * other.RealPart - ImaginaryPart * other.ImaginaryPart,
            ImaginaryPart * other.RealPart + RealPart * other.ImaginaryPart);
    }

    public ComplexNumber Add(ComplexNumber other)
    {
        return new ComplexNumber(RealPart + other.RealPart, ImaginaryPart + other.ImaginaryPart);
    }

    public ComplexNumber Sub(ComplexNumber other)
    {
        return new ComplexNumber(RealPart - other.RealPart, ImaginaryPart - other.ImaginaryPart);
    }

    public ComplexNumber Div(ComplexNumber other)
    {
        return new ComplexNumber(
            (RealPart * other.RealPart + ImaginaryPart * other.ImaginaryPart) /
            (other.RealPart * other.RealPart + other.ImaginaryPart * other.ImaginaryPart),
            (ImaginaryPart * other.RealPart - RealPart * other.ImaginaryPart) /
            (other.RealPart * other.RealPart + other.ImaginaryPart * other.ImaginaryPart));
    }

    public double Abs()
    {
        return Math.Sqrt(RealPart * RealPart + ImaginaryPart * ImaginaryPart);
    }

    public ComplexNumber Conjugate()
    {
        return new ComplexNumber(RealPart, -ImaginaryPart);
    }
    
    public ComplexNumber Exp()
    {
        return new ComplexNumber(Math.Exp(RealPart) * Math.Cos(ImaginaryPart), Math.Sin(ImaginaryPart));
    }
}

Tags:

construct:add
construct:assignment
construct:auto-implemented-property
construct:constructor
construct:divide
construct:double
construct:floating-point-number
construct:getter
construct:implicit-conversion
construct:invocation
construct:lambda
construct:method
construct:multiply
construct:number
construct:parameter
construct:property
construct:return
construct:struct
construct:subtract
construct:using-directive
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:higher-order-functions

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: wordy

Code

using System;
using System.Collections.Generic;
using System.Linq;

public class WordProblem
{
    static Dictionary<string, Func<int, int, int>> Ops = new Dictionary<string, Func<int, int, int>> {
        { "plus", (a, b) => a + b },
        { "minus", (a, b) => a - b },
        { "divided", (a, b) => a / b },
        { "multiplied", (a, b) => a * b }
    };

    public static int Solve(string phrase)
    {
        if (phrase[phrase.Length - 1] == '?') phrase = phrase.Substring(0, phrase.Length - 1);
        var words = phrase.Substring(8, phrase.Length - 8).Split(' ').Where(w => w != "by");
        int memo;
        try
        {
            memo = Int32.Parse(words.First());
        }
        catch (FormatException e)
        {
            throw new ArgumentException();
        }
        words = words.Skip(1);
        while (words.Any())
        {
            Func<int, int, int> op;
            try
            {
                op = Ops[words.First()];
            }
            catch (KeyNotFoundException e)
            {
                throw new ArgumentException();
            }
            var operand = Int32.Parse(words.Skip(1).First());
            memo = op(memo, operand);
            words = words.Skip(2);
        }
        return memo;
    }
}

Tags:

construct:add
construct:assignment
construct:catch
construct:char
construct:class
construct:collection-initializer
construct:constructor
construct:dictionary
construct:divide
construct:field
construct:if
construct:implicit-conversion
construct:indexer
construct:initializer
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:linq
construct:method
construct:multiply
construct:number
construct:parameter
construct:return
construct:string
construct:subtract
construct:throw
construct:try
construct:using-directive
construct:variable
construct:visibility-modifiers
construct:while-loop
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:higher-order-functions
technique:looping
uses:Dictionary<TKey,TValue>

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: forth

Code

using System;
using System.Collections.Generic;
using System.Linq;

public static class Forth
{
    private static string twoOperandsOperators = "+-*/swapover";
    private static string operators = twoOperandsOperators + "dupdrop";

    private static Dictionary<string, Func<int, int, int>> arthemicOperations = new Dictionary<string, Func<int, int, int>>
    {
        ["+"] = (d,e) => (d + e),
        ["-"] = (d,e) => (e - d),
        ["*"] = (d,e) => (d * e),
        ["/"] = (d,e) => d != 0? (e / d) : throw new InvalidOperationException()
    };

    private static IEnumerable<string> Evaluate(Stack<string> stack)
    {
        while (stack.Count != 0)
        {
            var element = ((string)stack.Pop()).ToLower();
            if (int.TryParse(element, out int number))
            {
                yield return number.ToString();
                continue;
            }
            else if(!operators.Contains(element))
            {
                throw new InvalidOperationException();
            }

            // drop is handled here as a no operator (no-op)
            var a = int.Parse(Evaluate(stack).First());

            if(twoOperandsOperators.Contains(element))
            {
                var b = int.Parse(Evaluate(stack).First());
                if(arthemicOperations.ContainsKey(element))
                {
                    yield return arthemicOperations[element](a, b).ToString();
                }
                else if (element == "swap")
                {
                    stack.Push(a.ToString());
                    stack.Push(b.ToString());
                }
                else if (element == "over")
                {
                    stack.Push(b.ToString());
                    stack.Push(a.ToString());
                    stack.Push(b.ToString());
                }
            }
            else if (element == "dup")
            {
                stack.Push(a.ToString());
                stack.Push(a.ToString());
            }
        }
    }

    private static string Transform(string instruction, string transformation)
    {
        var transformationPart = transformation.Split(' ')
        .Skip(1)
        .SkipLast(1)
        .ToArray();

        var word = transformationPart[0];
        var replacement = string.Join(' ', transformationPart.Skip(1));
        return instruction.Replace(word, replacement);
    }
    public static string Evaluate(string[] instructions)
    {
        var loweredInstructions = instructions.Select(instruction => instruction.ToLower())
                                              .ToArray();
        var lastLine = loweredInstructions.Last();
        var replacementInstructions = loweredInstructions.SkipLast(1)
                                                       .Select((i,j) => new {i,j})
                                                       .OrderByDescending( _=> _.j)
                                                       .Select(_ => _.i)
                                                       .ToArray();
        foreach (var replacement in replacementInstructions)
        {
            lastLine = Transform(lastLine, replacement);
        }

        var stack = new Stack<string>();
        lastLine.Split(' ')
                .ToList()
                .ForEach(stack.Push);
        return string.Join(' ', Evaluate(stack).Reverse());
    }
}

Tags:

construct:add
construct:assignment
construct:char
construct:class
construct:comment
construct:constructor
construct:continue
construct:dictionary
construct:divide
construct:explicit-conversion
construct:field
construct:foreach
construct:if
construct:implicit-conversion
construct:indexer
construct:initializer
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:linq
construct:list
construct:method
construct:multiply
construct:number
construct:object-initializer
construct:parameter
construct:return
construct:stack
construct:string
construct:subtract
construct:ternary
construct:throw
construct:throw-expression
construct:using-directive
construct:variable
construct:visibility-modifiers
construct:while-loop
construct:yield
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:enumeration
technique:exceptions
technique:higher-order-functions
technique:laziness
technique:looping
technique:recursion
technique:type-conversion
uses:Dictionary<TKey,TValue>
uses:List<T>
uses:Stack<T>

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: dnd-character

Code

using System;
using System.Collections.Generic;
using System.Linq;

public class DndCharacter
{
    public int Strength { get; }
    public int Dexterity { get; }
    public int Constitution { get; }
    public int Intelligence { get; }
    public int Wisdom { get; }
    public int Charisma { get; }
    public int Hitpoints { get; }

    public DndCharacter()
    {
        Strength = Ability();
        Dexterity = Ability();
        Constitution = Ability();
        Intelligence = Ability();
        Wisdom = Ability();
        Charisma = Ability();
        Hitpoints = 10 + Modifier(Constitution);
    }

    public static int Modifier(int score) => (int)Math.Floor((score - 10) / 2.0);

    public static int Ability() => 3 + new Random().Next() % 16;

    public static DndCharacter Generate() => new DndCharacter();
}

Tags:

construct:add
construct:assignment
construct:auto-implemented-property
construct:class
construct:constructor
construct:divide
construct:double
construct:explicit-conversion
construct:expression-bodied-member
construct:floating-point-number
construct:getter
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:method
construct:number
construct:parameter
construct:property
construct:subtract
construct:using-directive
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:higher-order-functions
technique:randomness
technique:type-conversion
uses:Random

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

Exercise: resistor-color

Code

using System;

public static class ResistorColor
{
    public static int ColorCode(string color)
    {
        // throw new NotImplementedException("You need to implement this function.");
        
        switch (color.ToLower())
        {
            case "black" :
                return 0;
                break;

            case "brown" :
                return 1;
                break;

            case "red" :
                return 2;
                break;

            case "orange" :
                return 3;
                break;

            case "yellow" :
                return 4;
                break;

            case "green" :
                return 5;
                break;

            case "blue" :
                return 6;
                break;

            case "violet" :
                return 7;
                break;

            case "grey" :
                return 8;
                break;

            case "white" :
                return 9;
                break;

            // No Default Expected
            default:
                return 10;
                break;

            
        }

    }

    public static string[] Colors()
    {
        //throw new NotImplementedException("You need to implement this function.");
        string[] colors = new string[10];
        colors[0] = "Black";
        colors[1] = "Brown";
        colors[2] = "Red";
        colors[3] = "Orange";
        colors[4] = "Yellow";
        colors[5] = "Green";
        colors[6] = "Blue";
        colors[7] = "Violet";
        colors[8] = "Grey";
        colors[9] = "White";

 
        return colors;
    }
}

Tags:

construct:assignment
construct:break
construct:class
construct:comment
construct:indexer
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:method
construct:number
construct:parameter
construct:return
construct:string
construct:switch
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:higher-order-functions

from csharp.

ErikSchierboom avatar ErikSchierboom commented on August 11, 2024

This is an automated comment

Hello 👋 Next week we're going to start using the tagging work people are doing on these. If you've already completed the work, thank you! If you've not, but intend to this week, that's great! If you're not going to get round to doing it, and you've not yet posted a comment letting us know, could you please do so, so that we can find other people to do it. Thanks!

from csharp.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.