├── Coderbyte_CSharp
├── App.config
├── 3 Hard Challenges
│ ├── HardChallenges.txt
│ ├── Kaprekar.cs
│ ├── ChessBoard.cs
│ └── MatrixDeterminant.cs
├── 1 Easy Challenges
│ ├── MathSummation.cs
│ ├── ExponentTwo.cs
│ ├── AlphabetSorter.cs
│ ├── StringReverse.cs
│ ├── NumberCheck.cs
│ ├── Factorial.cs
│ ├── TimeConverter.cs
│ ├── MathFibonacci.cs
│ ├── PalindromeChecker.cs
│ ├── EasyChallenges.txt
│ ├── MedianMovement.cs
│ ├── StringSymbols.cs
│ ├── StringBrackets.cs
│ ├── SquareVowels.cs
│ ├── StringWords.cs
│ ├── UsernameValidation.cs
│ ├── ChangeLetter.cs
│ ├── StringPeriod.cs
│ ├── MathSequence.cs
│ ├── StringIntersection.cs
│ ├── MathProduct.cs
│ └── QuestionMarkSum.cs
├── 2 Medium Challenges
│ ├── MediumChallenges.txt
│ ├── ConsecutiveNumbers.cs
│ ├── NumberEncoder.cs
│ ├── PrimeNumber.cs
│ ├── StringCompression.cs
│ ├── StringUniqueSubstring.cs
│ ├── StringMinimumWindow.cs
│ ├── StringReducer.cs
│ └── TreeGraphs.cs
├── Properties
│ └── AssemblyInfo.cs
├── Program.cs
├── Coderbyte_CSharp.csproj
└── TestChallenge.cs
├── README.md
├── Coderbyte_CSharp.sln
├── .gitattributes
└── .gitignore
/Coderbyte_CSharp/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/3 Hard Challenges/HardChallenges.txt:
--------------------------------------------------------------------------------
1 | The list of challenges were originally coded in C++. Challenge solution with
2 | dates have been coded in C# and exist in this solution.
3 |
4 | Challenge: C# Date: Class:
5 | Chessboard Traveling 02/25/2021 Chessboard
6 | Kaprekars Constant 02/16/2021 Kaprekar
7 | Matrix Determinant 02/17/2021 Determinant
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Coderbyte_CSharp
2 | Coderbyte code challenges: This repository contains code solutions written in C# for code challenges.
3 |
4 | There is a directory for each difficulty level of completed code challenges. The difficult levels are Easy, Medium, and Hard.
5 |
6 | Each difficulty level directory contains a text file listing the completed challenges for that difficulty level. Each class for the code challenge contains the challenge description.
7 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/MathSummation.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace Coderbyte_CSharp.Easy_Challenges
8 | {
9 | class MathSummation
10 | {
11 | public int SimpleAdding(int num)
12 | {
13 | int result = 0;
14 |
15 | for (int index = 1; index <= num; index++)
16 | {
17 | result += index;
18 | }
19 |
20 | return result;
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/ExponentTwo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class ExponentTwo
6 | {
7 | public string PowersofTwo(int num)
8 | {
9 | string result = String.Empty;
10 | bool same = false;
11 |
12 | same = Same(num, 2);
13 |
14 | result = (same) ? "true" : "false";
15 | return result;
16 | }
17 |
18 | private static bool Same(int num, int baseValue)
19 | {
20 | bool same;
21 | double tolerance = Double.Epsilon;
22 | same = Math.Abs(Math.Ceiling(Math.Log(num, baseValue)) - Math.Floor(Math.Log(num, baseValue))) < tolerance;
23 | return same;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/AlphabetSorter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class AlphabetSorter
6 | {
7 | // Have the function AlphabetSoup(str) take the str string parameter being
8 | // passed and return the string with the letters in alphabetical order (ie.
9 | // hello becomes ehllo). Assume numbers and punctuation symbols will not
10 | // be included in the string.
11 |
12 | public String AlphabetSoup( String str)
13 | {
14 | String result = String.Empty;
15 |
16 | char[] charArray = str.ToCharArray();
17 | Array.Sort(charArray);
18 |
19 | result = new string(charArray);
20 |
21 | return result;
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/StringReverse.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Specialized;
3 |
4 | namespace Coderbyte_CSharp.Easy_Challenges
5 | {
6 | class StringReverse
7 | {
8 | // Have the function FirstReverse(str) take the str parameter being passed and
9 | // return the string in reversed order. For example: if the input string is
10 | // "Hello World and Coders" then your program should return the string
11 | // sredoC dna dlroW olleH.
12 | public string FirstReverse(string str)
13 | {
14 | string result = String.Empty;
15 |
16 | char[] charArray = str.ToCharArray();
17 | Array.Reverse(charArray);
18 | result = new string(charArray);
19 |
20 | return result;
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/NumberCheck.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class NumberCheck
6 | {
7 | // Have the function CheckNums(num1, num2) take both parameters being passed
8 | // and return the string true if num2 is greater than num1, otherwise return
9 | // the string false.If the parameter values are equal to each other then
10 | // return the string - 1.
11 | public string CheckNumber(int num1, int num2)
12 | {
13 | string result = String.Empty;
14 |
15 | if (num1 > num2)
16 | result = "false";
17 | else if (num2 > num1)
18 | result = "true";
19 | else
20 | result = "-1";
21 |
22 |
23 | return result;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/Factorial.cs:
--------------------------------------------------------------------------------
1 | namespace Coderbyte_CSharp.Easy_Challenges
2 | {
3 | class Factorial
4 | {
5 | // Have the function FirstFactorial(num) take the num parameter being passed and
6 | // return the factorial of it. For example: if num = 4, then your program should
7 | // return (4 * 3 * 2 * 1) = 24. For the test cases, the range will be between 1
8 | // and 18 and the input will always be an integer.
9 | public ulong FirstFactorial(int num)
10 | {
11 | ulong result = 0;
12 |
13 | if (num == 0)
14 | {
15 | result = 1;
16 | }
17 |
18 | else
19 | {
20 | result = (ulong)num * FirstFactorial(num - 1);
21 | }
22 |
23 | return result;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/2 Medium Challenges/MediumChallenges.txt:
--------------------------------------------------------------------------------
1 | The list of challenges were originally coded in C++. Challenge solution with
2 | dates have been coded in C# and exist in this solution.
3 |
4 | Challenge: C# Date: Class:
5 | Consecutive 02/12/2021 ConsecutiveNumbers
6 | K Unique Chars 02/12/2021 StringUniqueSubstring
7 | Number Encoding 02/12/2021 NumberEncoder
8 | Preorder Traversal 02/28/2021 TreeGraphs
9 | Prime Mover 02/12/2021 PrimeNumber
10 | Run Length 02/15/2021 StringCompression
11 | String Reduction 02/15/2021 StringReducer
12 | Symmetric Tree 02/28/2021 TreeGraphs
13 | Tree Constructor 02/15/2021 TreeGraphs
14 | Minimum Window Substring 02/12/2021 StringMinimumWindow
15 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/TimeConverter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 |
4 | namespace Coderbyte_CSharp.Easy_Challenges
5 | {
6 | class TimeConverter
7 | {
8 | // Have the function TimeConvert(num) take the num parameter being passed and
9 | // return the number of hours and minutes the parameter converts to (ie. if
10 | // num = 63 then the output should be 1:3). Separate the number of hours
11 | // and minutes with a colon.
12 |
13 | public String TimeConvert(int num)
14 | {
15 | string result = string.Empty;
16 | StringBuilder sb = new StringBuilder();
17 |
18 | int hours = num / 60;
19 | int minutes = num % 60;
20 |
21 | sb.Append(hours);
22 | sb.Append(":");
23 | sb.Append(minutes);
24 |
25 | result = sb.ToString();
26 |
27 | return result;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/MathFibonacci.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class MathFibonacci
6 | {
7 | public string FibonacciChecker(int num)
8 | {
9 | string result = String.Empty;
10 | bool isFibonacci = false;
11 |
12 | isFibonacci = IsValidFibonacci(1, 1, num);
13 |
14 | result = (isFibonacci) ? "yes" : "no";
15 |
16 | return result;
17 | }
18 |
19 | protected bool IsValidFibonacci(int x, int y, int num)
20 | {
21 | bool isFibonacci = false;
22 |
23 | if (num == 0 || num == 1)
24 | {
25 | isFibonacci = true;
26 | }
27 |
28 | else if (x + y == num)
29 | {
30 | isFibonacci = true;
31 | }
32 |
33 | else if (x + y < num)
34 | {
35 | isFibonacci = IsValidFibonacci(x + y, x, num);
36 | }
37 |
38 | else
39 | {
40 | isFibonacci = false;
41 | }
42 |
43 | return isFibonacci;
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/PalindromeChecker.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class PalindromeChecker
6 | {
7 | public string Palindrome(string str)
8 | {
9 | string result = String.Empty;
10 |
11 | result = (IsPalindrome(str)) ? "true" : "false";
12 |
13 | return result;
14 |
15 | }
16 |
17 | protected bool IsPalindrome(string str)
18 | {
19 | bool isPalindrome = false;
20 |
21 | String local = new string(' ',str.Length);
22 |
23 | foreach(char c in str)
24 | {
25 | if (!Char.IsWhiteSpace(c))
26 | {
27 | local += c;
28 | }
29 | }
30 |
31 | local = local.Trim();
32 |
33 | char[] charArray = local.ToCharArray();
34 | Array.Reverse(charArray);
35 |
36 | string backwards = new string(charArray);
37 |
38 | isPalindrome = String.Compare(local, backwards, StringComparison.Ordinal) == 0;
39 |
40 | return isPalindrome;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.28307.1169
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Coderbyte_CSharp", "Coderbyte_CSharp\Coderbyte_CSharp.csproj", "{F4056BC8-6438-4350-BF70-6920F21D78FC}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {F4056BC8-6438-4350-BF70-6920F21D78FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {F4056BC8-6438-4350-BF70-6920F21D78FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {F4056BC8-6438-4350-BF70-6920F21D78FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {F4056BC8-6438-4350-BF70-6920F21D78FC}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {7A2B2175-B63E-4215-B311-D6AC58A1853A}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/EasyChallenges.txt:
--------------------------------------------------------------------------------
1 | The list of challenges were originally coded in C++. Challenge solution with
2 | dates have been coded in C# and exist in this solution.
3 |
4 | Challenge: C# Date: Class
5 | Alphabet Soup 02/10/2021 AlphabetSorter
6 | ArithGeo 02/10/2021 MathSequence
7 | Check Numbers 02/10/2021 NumberCheck
8 | Fibonacci Checker 02/24/2021 MathFibonacci
9 | Find Intersection 02/11/2021 StringIntersection
10 | First Factorial 02/22/2021 Factorial
11 | First Reverse 02/22/2021 StringReverse
12 | Letter Capitalize 02/22/2021 ChangeLetter
13 | Letter Changes 02/22/2021 ChangeLetter
14 | Longest Word 02/23/2021 StringWords
15 | Moving Median 02/23/2021 MedianMovement
16 | Other Products 02/22/2021 MathProduct
17 | Palindrome 02/10/2021 PalindromeChecker
18 | Power of 2 02/22/2021 ExponentTwo
19 | Product Digits 02/22/2021 MathProduct
20 | Question Marks 02/24/2021 QuestionMarkSum
21 | Remove Brackets 02/24/2021 StringBrackets
22 | Simple Adding 02/24/2021 MathSummation
23 | Simple Symbols 02/24/2021 StringSymbols
24 | String Periods 02/24/2021 StringPeriod
25 | Time Convert 02/10/2021 TimeConverter
26 | Username Validation 02/24/2021 UsernameValidation
27 | Vowel Square 02/23/2021 SquareVowels
--------------------------------------------------------------------------------
/Coderbyte_CSharp/2 Medium Challenges/ConsecutiveNumbers.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Medium_Challenges
4 | {
5 | class ConsecutiveNumbers
6 | {
7 | // The function Consecutive(arr) has an integer array paameter. The function
8 | // returns the minimum number of integers needed to make the contents of arr
9 | // consecutive from the lowest number to the highest number.
10 |
11 | // For example: If arr contains [4, 8, 6] then the output should be 2 because
12 | // two numbers need to be added to the array (5 and 7) to make it a consecutive
13 | // array of numbers from 4 to 8. Negative numbers may be entered as parameters
14 | // and no array will have less than 2 elements.
15 | public int Consecutive(int[] arr, int length)
16 | {
17 | int missingCount = 0;
18 | int[] numbers = arr;
19 |
20 | Array.Sort(arr);
21 |
22 | //sort(numbers.begin(), numbers.end());
23 |
24 | for (int index = 0; index < length - 1; index++)
25 | {
26 | int addCount = 0;
27 | while (numbers[index + 1] != numbers[index] + 1 + addCount)
28 | {
29 | addCount++;
30 | }
31 |
32 | missingCount += addCount;
33 | }
34 |
35 |
36 | return missingCount;
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("Coderbyte_CSharp")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("HP Inc.")]
11 | [assembly: AssemblyProduct("Coderbyte_CSharp")]
12 | [assembly: AssemblyCopyright("Copyright © HP Inc. 2021")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("f4056bc8-6438-4350-bf70-6920f21d78fc")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
36 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/MedianMovement.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace Coderbyte_CSharp.Easy_Challenges
6 | {
7 | class MedianMovement
8 | {
9 | public string MovingMedian(int[] arr, int length)
10 | {
11 | string result = String.Empty;
12 | List nums = new List();
13 | int windowSize = arr[0];
14 | int median = 0;
15 | StringBuilder sb = new StringBuilder();
16 |
17 | for (int i = 1; i < length; i++)
18 | {
19 | nums.Add(arr[i]);
20 | if (nums.Count > windowSize)
21 | {
22 | nums.RemoveRange(0,1);
23 | }
24 |
25 | median = CalculateMedian(nums);
26 | sb.AppendFormat("{0},", median);
27 | }
28 |
29 | result = sb.ToString().TrimEnd(',');
30 |
31 | return result;
32 | }
33 |
34 | protected int CalculateMedian(List values)
35 | {
36 | int median = 0;
37 | List local = new List(values);
38 | int half = values.Count / 2;
39 |
40 | local.Sort();
41 |
42 | median = (local.Count % 2 == 0) ? (local[half - 1] + local[half]) / 2
43 | : local[half];
44 | return median;
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/StringSymbols.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class StringSymbols
6 | {
7 | // Have the function SimpleSymbols(str) take the str parameter being passed and
8 | // determine if it is an acceptable sequence by either returning the string true
9 | // or false. The str parameter will be composed of + and = symbols with several
10 | // characters between them (ie. ++d+===+c++==a) and for the string to be true
11 | // each letter must be surrounded by a + symbol. So the string to the left would
12 | // be false. The string will not be empty and will have at least one letter.
13 |
14 | public string SimpleSymbols(string str)
15 | {
16 | string result = String.Empty;
17 | bool found = false;
18 |
19 | for (int index = 0; index < str.Length && !found; ++index)
20 | {
21 | if (Char.IsSymbol(str[index]) || Char.IsLetterOrDigit(str[index]))
22 | {
23 | if ((index == 0) && (index == str.Length - 1))
24 | {
25 | break;
26 | }
27 | else if (index != str.Length-1 && index != 0 &&
28 | str[index - 1] == '+' && str[index + 1] == '+')
29 | {
30 | found = true;
31 | }
32 | }
33 | }
34 |
35 | result = found ? "true" : "false";
36 |
37 | return result;
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/StringBrackets.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class StringBrackets
6 | {
7 | // For this challenge you will determine how to create evenly matched brackets.
8 |
9 | // The function RemoveBrackets(str) take the str string parameter being passed,
10 | // which will contain only the characters "(" and ")", and determine the minimum
11 | // number of brackets that need to be removed to create a string of correctly
12 | // matched brackets.
13 |
14 | // For example: if str is "(()))" then your program should return the number 1.
15 | // The answer could potentially be 0, and there will always be at least one set
16 | // of matching brackets in the string.
17 | public int RemoveBrackets(string str)
18 | {
19 | int count = 0;
20 |
21 | Stack unmatched = new Stack();
22 |
23 | foreach (char c in str)
24 | {
25 | if (c == '(')
26 | {
27 | unmatched.Push(c);
28 | }
29 |
30 | // char is ')'
31 | else
32 | {
33 | // check for matching bracket in stack
34 | if (unmatched.Count != 0 && unmatched.Peek() == '(')
35 | {
36 | unmatched.Pop();
37 | }
38 | else
39 | {
40 | unmatched.Push(c);
41 | }
42 | }
43 | }
44 |
45 | // Stack contains unmatched brackets
46 | count = unmatched.Count;
47 |
48 | return count;
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/SquareVowels.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 |
4 | // ReSharper disable CheckNamespace
5 | namespace Coderbyte_CSharp.Easy_Challenges
6 | // ReSharper restore CheckNamespace
7 | {
8 | class SquareVowels
9 | {
10 | public string VowelSquare(string[] strArr, int length)
11 | {
12 | string result = String.Empty;
13 |
14 | StringBuilder sb = new StringBuilder();
15 | bool found = false;
16 |
17 | for (int row = 0; row < length && !found; row++)
18 | {
19 | int colLength = strArr[row].Length;
20 | for (int col = 0; col < colLength - 1 && !found; col++)
21 | {
22 | if (IsVowel(strArr[row][col]) && IsVowel(strArr[row][col + 1]) &&
23 | IsVowel(strArr[row + 1][col]) && IsVowel(strArr[row + 1][col + 1]))
24 | {
25 | sb.AppendFormat("{0}-{1}", row, col);
26 | result = sb.ToString();
27 | found = true;
28 | }
29 | }
30 | }
31 | return result;
32 | }
33 |
34 | protected bool IsVowel(char c)
35 | {
36 | bool isValid = false;
37 |
38 | switch (c)
39 | {
40 | case 'a':
41 | case 'e':
42 | case 'i':
43 | case 'o':
44 | case 'u':
45 | case 'y':
46 | isValid = true;
47 | break;
48 | // ReSharper disable once RedundantEmptySwitchSection
49 | default:
50 | break;
51 | }
52 |
53 | return isValid;
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/2 Medium Challenges/NumberEncoder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace Coderbyte_CSharp.Medium_Challenges
6 | {
7 | class NumberEncoder
8 | {
9 | // For this challenge you will encode a given string following a specific rule.
10 | // The function NumberEncoding(str) with str parameter and encode the
11 | // message according to the following rule: encode every letter into its
12 | // corresponding numbered position in the alphabet. Symbols and spaces will also
13 | // be used in the input.
14 |
15 | // For example: if str is "af5c a#!" then your program should return 1653 1#!.
16 | public string NumberEncoding(string str)
17 | {
18 | string result = string.Empty;
19 | StringBuilder sb = new StringBuilder();
20 | Dictionary alphabet = CreateAlphabetMap();
21 |
22 | foreach (char item in str)
23 | {
24 | // is a letter
25 | if (Char.IsLetter(item))
26 | {
27 | sb.Append(alphabet[item]);
28 | }
29 |
30 | // not a letter
31 | else
32 | {
33 | sb.Append(item);
34 | }
35 | }
36 |
37 | result = sb.ToString();
38 | return result;
39 | }
40 |
41 | protected Dictionary CreateAlphabetMap()
42 | {
43 | Dictionary alpha = new Dictionary();
44 |
45 | int value = 1;
46 |
47 | for (char key = 'a'; key <= 'z'; key++, value++)
48 | {
49 | alpha.Add(key, value);
50 | }
51 |
52 | return alpha;
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/2 Medium Challenges/PrimeNumber.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Coderbyte_CSharp.Medium_Challenges
4 | {
5 | class PrimeNumber
6 | {
7 | public int PrimeMover(int num)
8 | {
9 | int primeValue = 1;
10 |
11 | bool found = false;
12 | List primes = PrefillPrimeVector();
13 | int index = primes.Count;
14 |
15 | if (primes.Count >= num)
16 | {
17 | primeValue = primes[num - 1];
18 | found = true;
19 | }
20 |
21 | while (primes.Count < num)
22 | {
23 | bool isPrime = false;
24 |
25 | index++;
26 | isPrime = IsPrimeNumber(index, primes);
27 | if (isPrime)
28 | {
29 | primes.Add(index);
30 | if (primes.Count == num)
31 | {
32 | found = true;
33 | break;
34 | }
35 | }
36 | }
37 |
38 | if (found)
39 | {
40 | primeValue = primes[num - 1];
41 | }
42 | return primeValue;
43 | }
44 |
45 | protected List PrefillPrimeVector()
46 | {
47 | List primes = new List() { 2, 3, 5, 7, 11, 13, 17, 19 };
48 |
49 | return primes;
50 | }
51 |
52 | protected bool IsPrimeNumber(int num, List primes)
53 | {
54 | bool result = true;
55 |
56 | foreach (int index in primes)
57 | {
58 | if (num % index == 0)
59 | {
60 | result = false;
61 | break;
62 | }
63 | }
64 |
65 | return result;
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/StringWords.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class StringWords
6 | {
7 | public string LongestWord(string sentence)
8 | {
9 | string longest = String.Empty;
10 |
11 | char separator = ' ';
12 | int prevPos = 0, pos = 0;
13 |
14 | if (sentence.IndexOf(separator, pos) == -1)
15 | {
16 | longest = sentence;
17 | }
18 |
19 | else
20 | {
21 | string substring = String.Empty;
22 |
23 | while ((pos = sentence.IndexOf(separator, pos)) != -1)
24 | {
25 | // get substring
26 | substring = sentence.Substring(prevPos, pos - prevPos);
27 | for (int i = 0; i < substring.Length; ++i)
28 | {
29 | // remove punctuation
30 | if (Char.IsPunctuation(substring[i]))
31 | {
32 | //substring.erase(i--, 1);
33 | substring = substring.Remove(i--, 1);
34 | }
35 | }
36 |
37 | // check for longest word
38 | if (substring.Length > longest.Length)
39 | {
40 | longest = substring;
41 | }
42 |
43 | prevPos = ++pos;
44 | }
45 |
46 | for (int i = 0; i < substring.Length; ++i)
47 | {
48 | if (Char.IsPunctuation(substring[i]))
49 | {
50 | substring = substring.Remove(i--, 1);
51 | }
52 | }
53 | if (substring.Length > longest.Length)
54 | {
55 | longest = substring;
56 | }
57 | }
58 |
59 | return longest;
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp
4 | {
5 | class Program
6 | {
7 | // ReSharper disable once UnusedParameter.Local
8 | static void Main(string[] args)
9 | {
10 | Console.WriteLine("Welcome to Coderbyte C-Sharp code challenge solutions...");
11 | Console.WriteLine();
12 |
13 | TestChallenge tc = new TestChallenge();
14 |
15 | // Easy
16 | Console.WriteLine("Easy Code Challenges:");
17 | tc.Test_TimeConvert();
18 | tc.Test_AlphabetSoup();
19 | tc.Test_ArithGeoSequence();
20 | tc.Test_Palindrome();
21 | tc.Test_NumberCheck();
22 | tc.Test_FindIntersection();
23 | tc.Test_FirstFactorial();
24 | tc.Test_FirstReverse();
25 | tc.Test_LetterChanges();
26 | tc.Test_LetterCapitalize();
27 | tc.Test_PowerOfTwo();
28 | tc.Test_ProductDigits();
29 | tc.Test_OtherProducts();
30 | tc.Test_VowelSquare();
31 | tc.Test_LongestWord();
32 | tc.Test_MovingMedian();
33 | tc.Test_QuestionsMarks();
34 | tc.Test_RemoveBrackets();
35 | tc.Test_FibonacciChecker();
36 | tc.Test_SimpleAdding();
37 | tc.Test_SimpleSymbols();
38 | tc.Test_StringPeriods();
39 | tc.Test_UsernameValidation();
40 |
41 | // Medium
42 | Console.WriteLine("Medium Code Challenges:");
43 | tc.Test_Consecutive();
44 | tc.Test_KUniqueCharacters();
45 | tc.Test_NumberEncoding();
46 | tc.Test_PrimeMover();
47 | tc.Test_MinWindowSubstring();
48 | tc.Test_RunLength();
49 | tc.Test_StringReduction();
50 | tc.Test_TreeConstructor();
51 | tc.Test_SymmetricTree();
52 | tc.Test_PreorderTraversal();
53 |
54 | // Hard
55 | Console.WriteLine("Hard Code Challenges:");
56 | tc.Test_ChessboardTraveling();
57 | tc.Test_KaprekarsConstant();
58 | tc.Test_Determinant();
59 |
60 | Console.ReadKey();
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/2 Medium Challenges/StringCompression.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 |
4 | namespace Coderbyte_CSharp.Medium_Challenges
5 | {
6 | class StringCompression
7 | {
8 | // For this challenge you will determine the Run Length Encoding of a string.
9 | // The function RunLength(str) take the str parameter being passed and return
10 | // a compressed version of the string using the Run-length encoding algorithm.
11 | // This algorithm works by taking the occurrence of each repeating character
12 | // and outputting that number along with a single character of the repeating
13 | // sequence.
14 |
15 | // For example: "wwwggopp" would return 3w2g1o2p. The string will not contain
16 | // any numbers, punctuation, or symbols.
17 | public string RunLength(string str)
18 | {
19 | string result = String.Empty;
20 | int length = str.Length;
21 | StringBuilder sb = new StringBuilder();
22 |
23 | for (int index = 0; index < length; index++)
24 | {
25 | int count = 0;
26 |
27 | if (IsRepeatingChar(str, index, ref count))
28 | {
29 | sb.Append(count);
30 | sb.Append(str[index]);
31 | index += count - 1;
32 | }
33 |
34 | else
35 | {
36 | sb.Append(1);
37 | sb.Append(str[index]);
38 | }
39 | }
40 |
41 | result = sb.ToString();
42 | return result;
43 | }
44 |
45 | protected bool IsRepeatingChar(string str, int index, ref int count)
46 | {
47 | bool repeating = false;
48 |
49 | int length = str.Length;
50 | count = 1;
51 |
52 | if (index != length - 1)
53 | {
54 | while ((index < length - 1) && (str[index] == str[index + 1]))
55 | {
56 | count++;
57 | index++;
58 | }
59 | }
60 |
61 | repeating = (count > 1);
62 | return repeating;
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/UsernameValidation.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp._1_Easy_Challenges
4 | {
5 | class UsernameValidation
6 | {
7 | //Have the function CodelandUsernameValidation(str) take the str parameter being
8 | // passed and determine if the string is a valid username according to the
9 | //following rules :
10 |
11 | //1. The username is between 4 and 25 characters.
12 | //2. It must start with a letter.
13 | //3. It can only contain letters, numbers, and the underscore character.
14 | //4. It cannot end with an underscore character.
15 |
16 | //If the username is valid then your program should return the string true,
17 | //otherwise return the string false.
18 |
19 | public string CodelandUsernameValidation(string str)
20 | {
21 | string result = String.Empty;
22 |
23 | bool rule1 = ValidateLength(str);
24 | bool rule2 = ValidateStartWithLetter(str);
25 | bool rule3 = ValidateOnlyValidCharacters(str);
26 | bool rule4 = ValidateEndCharacter(str);
27 |
28 | result = (rule1 && rule2 && rule3 && rule4) ? "true" : "false";
29 |
30 |
31 | return result;
32 | }
33 |
34 | protected bool ValidateLength(string str)
35 | {
36 | bool isValid = false;
37 |
38 | int length = str.Length;
39 |
40 | isValid = (length >= 4 && length <= 25);
41 |
42 | return isValid;
43 | }
44 |
45 | protected bool ValidateStartWithLetter(string str)
46 | {
47 | bool isValid = false;
48 |
49 | isValid = Char.IsLetter(str[0]);
50 |
51 | return isValid;
52 | }
53 |
54 | protected bool ValidateOnlyValidCharacters(string str)
55 | {
56 | bool isValid = true;
57 |
58 | foreach (char c in str)
59 | {
60 | if (!Char.IsLetterOrDigit(c) && c != '_')
61 | {
62 | isValid = false;
63 | break;
64 | }
65 | }
66 |
67 | return isValid;
68 | }
69 |
70 | protected bool ValidateEndCharacter(string str)
71 | {
72 | bool isValid = false;
73 | int length = str.Length;
74 |
75 | isValid = (str[length - 1] != '_');
76 |
77 | return isValid;
78 | }
79 |
80 |
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/ChangeLetter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class ChangeLetter
6 | {
7 | // Have the function LetterChanges(str) take the str parameter being passed and
8 | // modify it using the following algorithm. Replace every letter in the string
9 | // with the letter following it in the alphabet (ie. c becomes d, z becomes a).
10 | // Then capitalize every vowel in this new string (a, e, i, o, u) and finally
11 | // return this modified string.
12 | public string LetterChanges(string str)
13 | {
14 | string result = String.Empty;
15 | char[] chars = str.ToCharArray();
16 | //chars[index] = newChar;
17 |
18 |
19 | // 1st increment ascii value, wrap z to a
20 | // 2nd capitalize vowels
21 | for (int index = 0; index < chars.Length; index++)
22 | {
23 | char c = chars[index];
24 |
25 | if (Char.IsLetter(chars[index]) && chars[index] != 'z')
26 | {
27 | chars[index]++;
28 | }
29 |
30 | else if (chars[index] == 'z')
31 | {
32 | chars[index] = 'a';
33 | }
34 |
35 | c = chars[index];
36 | if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
37 | {
38 | chars[index] = Char.ToUpper(c);
39 | }
40 | }
41 |
42 | result = new string(chars);
43 |
44 | return result;
45 | }
46 |
47 | // Have the function LetterCapitalize(str) take the str parameter being passed
48 | // and capitalize the first letter of each word. Words will be separated by
49 | // only one space.
50 | public string LetterCapitalize(string str)
51 | {
52 | string result = String.Empty;
53 | char[] chars = str.ToCharArray();
54 |
55 |
56 | for ( int index = 0; index < chars.Length; index++)
57 | {
58 | if (index == 0 && Char.IsLower(str[index]))
59 | {
60 | chars[index] = Char.ToUpper(chars[index]);
61 | }
62 |
63 | if (index > 0 && chars[index - 1] == ' ')
64 | {
65 | chars[index] = Char.ToUpper(chars[index]);
66 | }
67 | }
68 |
69 | result = new string(chars);
70 |
71 | return result;
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/StringPeriod.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 |
4 | namespace Coderbyte_CSharp.Easy_Challenges
5 | {
6 | class StringPeriod
7 | {
8 | // For this challenge you will need to find the smallest repeating substring.
9 |
10 | // The function StringPeriods(str) take the str parameter being passed and
11 | // determine if there is some substring K that can be repeated N > 1 times
12 | // to produce the input string exactly as it appears. Your program should
13 | // return the longest substring K, and if there is none it should return
14 | // the string -1.
15 |
16 | // For example: if str is "abcababcababcab" then your program should return
17 | // abcab because that is the longest substring that is repeated 3 times to
18 | // create the final string.
19 |
20 | // Another example: if str is "abababababab" then your program should return
21 | // ababab because it is the longest substring.
22 |
23 | // If the input string contains only a single character, your program should
24 | // return the string -1.
25 | public string StringPeriods(string str)
26 | {
27 | string result = String.Empty;
28 | string sub = String.Empty;
29 | int maxLength = -1;
30 | int strLength = str.Length;
31 |
32 |
33 | if (strLength > 1)
34 | {
35 | for (int i = 0; i < strLength / 2; i++)
36 | {
37 | sub = str.Substring(0, i + 1);
38 |
39 | int len = StringCheck(sub, str);
40 |
41 | if (len > maxLength)
42 | {
43 | maxLength = len;
44 | result = sub;
45 | }
46 | }
47 | }
48 |
49 | result = (maxLength != -1) ? result : maxLength.ToString();
50 |
51 |
52 | return result;
53 | }
54 |
55 | protected int StringCheck(string sub, string str)
56 | {
57 | int length = -1;
58 | int times = str.Length / sub.Length;
59 | StringBuilder sb = new StringBuilder();
60 |
61 | for (int index = 0; index < times; index++)
62 | {
63 | sb.Append(sub);
64 | }
65 |
66 | string temp = sb.ToString();
67 | if (temp == str)
68 | {
69 | length = sub.Length;
70 | }
71 |
72 |
73 | return length;
74 | }
75 |
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/3 Hard Challenges/Kaprekar.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 |
4 | namespace Coderbyte_CSharp.Hard_Challenges
5 | {
6 | class Kaprekar
7 | {
8 | // Have the function KaprekarsConstant(num) take the num parameter being passed
9 | // which will be a 4-digit number with at least two distinct digits. Your program
10 | // should perform the following routine on the number: Arrange the digits in
11 | // descending order and in ascending order (adding zeroes to fit it to a 4-digit
12 | // number), and subtract the smaller number from the bigger number. Then repeat
13 | // the previous step. Performing this routine will always cause you to reach a
14 | // fixed number: 6174. Then performing the routine on 6174 will always give you
15 | // 6174 (7641 - 1467 = 6174). Your program should return the number of times
16 | // this routine must be performed until 6174 is reached.
17 |
18 | // For example: if num is 3524 your program should return 3 because of the
19 | // following steps: (1) 5432 - 2345 = 3087, (2) 8730 - 0378 = 8352,
20 | // (3) 8532 - 2358 = 6174.
21 |
22 | public int KaprekarsConstant(int num)
23 | {
24 | int count = 0;
25 | int remainder = num;
26 |
27 | while (remainder != 6174)
28 | {
29 | remainder = DescendInt(remainder) - AscendInt(remainder);
30 | count++;
31 | }
32 |
33 | return count;
34 | }
35 |
36 | protected int AscendInt(int num)
37 | {
38 | int result = 0;
39 |
40 | result = AdjustInt(num, false);
41 | return result;
42 | }
43 |
44 | protected int DescendInt(int num)
45 | {
46 | int result = 0;
47 |
48 | result = AdjustInt(num, true);
49 | return result;
50 | }
51 |
52 | private int AdjustInt(int num, bool descend)
53 | {
54 | int result = 0;
55 | int[] arr = ConvertToIntArray(num);
56 |
57 | List valueList = arr.ToList();
58 | valueList.Sort();
59 |
60 | if (descend)
61 | {
62 | valueList.Reverse();
63 | }
64 |
65 | result = int.Parse(string.Join("", valueList));
66 | return result;
67 | }
68 |
69 | private int[] ConvertToIntArray(int value)
70 | {
71 | var numbers = new Stack();
72 |
73 | for (; value > 0; value /= 10)
74 | {
75 | numbers.Push(value % 10);
76 | }
77 |
78 | return numbers.ToArray();
79 | }
80 |
81 |
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/MathSequence.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class MathSequence
6 | {
7 | // The function ArithGeo(arr) takes an array of numbers stored in arr and return
8 | // the string "Arithmetic" if the sequence follows an arithmetic pattern or return
9 | // "Geometric" if it follows a geometric pattern.If the sequence doesn't follow
10 | // either pattern return -1. An arithmetic sequence is one where the difference
11 | // between each of the numbers is consistent, where as in a geometric sequence,
12 | // each term after the first is multiplied by some constant or common ratio.
13 |
14 | // Arithmetic example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54].
15 | // Negative numbers may be entered as parameters, 0 will not be entered, and
16 | // no array will contain all the same elements.
17 |
18 | public string ArithGeo(int[] arr, int length)
19 | {
20 | string result = String.Empty;
21 |
22 | if (IsArithematicSequence(arr, length))
23 | {
24 | result = "Arithmetic";
25 | }
26 |
27 | else if (IsGeometricSequence(arr, length))
28 | {
29 | result = "Geometric";
30 | }
31 |
32 | else
33 | {
34 | result = "-1";
35 | }
36 |
37 | return result;
38 | }
39 |
40 | protected bool IsArithematicSequence(int[] arr, int length)
41 | {
42 | bool result = false;
43 | bool isSequence = true;
44 |
45 | if (length >= 2)
46 | {
47 | int diff = arr[1] - arr[0];
48 |
49 | // Check is the difference is true for all elements
50 | // If true than the array is arithmetic
51 | for (int index = 0; index < length - 1 && isSequence; index++)
52 | {
53 | isSequence = false;
54 | if (arr[index] + diff == arr[index + 1])
55 | {
56 | isSequence = true;
57 | }
58 | }
59 | }
60 |
61 | result = isSequence;
62 | return result;
63 | }
64 | protected bool IsGeometricSequence(int[] arr, int length)
65 | {
66 | bool result = false;
67 | bool isSequence = true;
68 |
69 | if (length >= 2)
70 | {
71 | int diff = arr[1] / arr[0];
72 |
73 | // Iterate through array
74 | for (int index = 0; index < length - 1 && isSequence; index++)
75 | {
76 | isSequence = false;
77 |
78 | // Check for geometric pattern
79 | if (arr[index] * diff == arr[index + 1])
80 | {
81 | isSequence = true;
82 | }
83 | }
84 | }
85 |
86 | result = isSequence;
87 | return result;
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/StringIntersection.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace Coderbyte_CSharp.Easy_Challenges
6 | {
7 | class StringIntersection
8 | {
9 | // Have the function FindIntersection(strArr) read the array of strings stored
10 | // in strArr which will contain 2 elements: the first element will represent a
11 | // list of comma - separated numbers sorted in ascending order, the second
12 | // element will represent a second list of comma - separated numbers(also sorted).
13 | // Your goal is to return a comma - separated string containing the numbers that
14 | // occur in elements of strArr in sorted order.If there is no intersection,
15 | // return the string false.
16 |
17 | // For example : if strArr contains["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"] the
18 | // output should return "1,4,13" because those numbers appear in both strings.
19 | // The array given will not be empty, and each string inside the array will be
20 | // of numbers sorted in ascending order and may contain negative numbers.
21 |
22 | public string FindIntersection(string[] strArr)
23 | {
24 | string result = String.Empty;
25 | char delim = ',';
26 |
27 | int[] first = TokenizeInt(strArr[0], delim);
28 | int[] second = TokenizeInt(strArr[1], delim);
29 |
30 | List matches = new List();
31 |
32 | // find matches between an arrays
33 | foreach(int value1 in first)
34 | {
35 | foreach(int value2 in second)
36 | {
37 | if (value1 == value2)
38 | {
39 | matches.Add(value1);
40 | }
41 | }
42 | }
43 |
44 | // Convert list to output string
45 | StringBuilder sb = new StringBuilder();
46 |
47 | int count = matches.Count;
48 | foreach( int value in matches)
49 | {
50 | sb.Append(value);
51 | if (value != matches[count-1])
52 | {
53 | sb.Append(",");
54 | }
55 | }
56 |
57 | result = sb.ToString();
58 |
59 | return result;
60 | }
61 |
62 | protected int[] TokenizeInt(string str, char delim)
63 | {
64 | string[] strValues = str.Split(delim);
65 | int[] nums = new int[strValues.Length];
66 |
67 | for(int index = 0; index < strValues.Length; index++)
68 | {
69 | try
70 | {
71 | nums[index] = Int32.Parse(strValues[index]);
72 | }
73 | catch (FormatException e)
74 | {
75 | Console.WriteLine("Unable to parse {0}", strValues[index]);
76 | Console.Error.Write(e.Message);
77 | }
78 | }
79 |
80 | return nums;
81 | }
82 | }
83 | }
84 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/3 Hard Challenges/ChessBoard.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Coderbyte_CSharp.Easy_Challenges;
3 |
4 | namespace Coderbyte_CSharp._3_Hard_Challenges
5 | {
6 | class ChessBoard
7 | {
8 | // Have the function ChessboardTraveling(str) read str which will be a string
9 | // consisting of the location of a space on a standard 8x8 chess board with
10 | // no pieces on the board along with another space on the chess board. The
11 | // structure of str will be the following: "(x y)(a b)" where (x y) represents
12 | // the position you are currently on with x and y ranging from 1 to 8 and
13 | // (a b) represents some other space on the chess board with a and b also
14 | // ranging from 1 to 8 where a > x and b > y. Your program should determine
15 | // how many ways there are of traveling from (x y) on the board to (a b)
16 | // moving only up and to the right. For example: if str is (1 1)(2 2) then your
17 | // program should output 2 because there are only two possible ways to travel
18 | // from space (1 1) on a chessboard to space (2 2) while making only moves up
19 | // and to the right.
20 | public int ChessboardTraveling(string str)
21 | {
22 | int result = 0;
23 | int x, y, a, b;
24 | //char* token = nullptr;
25 | //char* data = const_cast(str.c_str());
26 | //char* next = nullptr;
27 |
28 | //token = strtok_s(data, "( )", &next); x = *token - '0';
29 | //token = strtok_s(NULL, "( )", &next); y = *token - '0';
30 | //token = strtok_s(NULL, "( )", &next); a = *token - '0';
31 | //token = strtok_s(NULL, "( )", &next); b = *token - '0';
32 |
33 |
34 | ParseInput(str, out x, out y, out a, out b);
35 |
36 | int row = a - x;
37 | int col = b - y;
38 |
39 | result = Ckn(row, row + col);
40 |
41 | return result;
42 | }
43 |
44 | protected void ParseInput(string str, out int x, out int y, out int a, out int b)
45 | {
46 | x = y = a = b = 0;
47 |
48 | // remove index = 0, length-1 for outer parentheses
49 | str = str.Substring(1, str.Length - 2);
50 |
51 | // Get strings for 2 positions
52 | string[] input = str.Split(")(".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
53 | string[] starting = input[0].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
54 | string[] ending = input[1].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
55 |
56 | x = Convert.ToInt32(starting[0]);
57 | y = Convert.ToInt32(starting[1]);
58 | a = Convert.ToInt32(ending[0]);
59 | b = Convert.ToInt32(ending[1]);
60 | }
61 |
62 | protected int Ckn(int k, int n)
63 | {
64 | int result = 0;
65 | int c = 1;
66 |
67 | for (int i = n, j = 0; j < k; i--, j++)
68 | {
69 | c *= i;
70 | }
71 |
72 | Factorial factorial = new Factorial();
73 |
74 | var nFact = factorial.FirstFactorial(n);
75 | var nkFact = factorial.FirstFactorial(n-k);
76 | var kFact = factorial.FirstFactorial(k);
77 |
78 | result = (int)(nFact / (kFact * nkFact));
79 | return result;
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/2 Medium Challenges/StringUniqueSubstring.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Coderbyte_CSharp.Medium_Challenges
5 | {
6 | class StringUniqueSubstring
7 | {
8 | // For this challenge you will be searching a string for a particular substring.
9 | // have the function KUniqueCharacters(str) take the str parameter being passed
10 | // and find the longest substring that contains k unique characters, where k will
11 | // be the first character from the string. The substring will start from the second
12 | // position in the string because the first character will be the integer k.
13 |
14 | // For example: if str is "2aabbacbaa" there are several substrings that all contain
15 | // 2 unique characters, namely: ["aabba", "ac", "cb", "ba"], but your program should
16 | // return "aabba" because it is the longest substring. If there are multiple longest
17 | // substrings, then return the first substring encountered with the longest length.
18 | // k will range from 1 to 6.
19 | public string KUniqueCharacters(string str)
20 | {
21 | string result = String.Empty;
22 | bool done = false;
23 | int uniqueLength = (int)char.GetNumericValue(str[0]);
24 | string localStr = str.Substring(1);
25 | int substrLength = localStr.Length;
26 |
27 | while (!done)
28 | {
29 | int uniqueCount = 0;
30 |
31 | List substrings = CreateSubstrings(localStr, substrLength);
32 | if (substrings.Count == 0)
33 | {
34 | continue;
35 | }
36 |
37 | foreach(string s in substrings)
38 | {
39 | uniqueCount = ComputeUniqueChars(s);
40 | if (uniqueCount == uniqueLength && s.Length > result.Length)
41 | {
42 | result = s;
43 | done = true;
44 | }
45 | }
46 |
47 | substrings.Clear();
48 | substrLength--;
49 | }
50 | return result;
51 | }
52 |
53 | protected int ComputeUniqueChars(string str)
54 | {
55 | int count = 1;
56 | Dictionary charCount = new Dictionary(); ;
57 |
58 | foreach (char c in str)
59 | {
60 | if (charCount.ContainsKey(c))
61 | {
62 | charCount[c]++;
63 | }
64 |
65 | else
66 | {
67 | charCount.Add(c, 1);
68 | }
69 | }
70 |
71 | count = charCount.Count;
72 | return count;
73 | }
74 |
75 | protected List CreateSubstrings(string str, int length)
76 | {
77 | List substrings = new List();
78 | int strLength = str.Length;
79 |
80 | if (length == strLength)
81 | {
82 | substrings.Add(str);
83 | }
84 |
85 | else if (length < strLength)
86 | {
87 | string substr;
88 |
89 | for (int index = 0; index + length <= strLength; index++)
90 | {
91 | substr = str.Substring(index, length);
92 | substrings.Add(substr);
93 | }
94 | }
95 |
96 | return substrings;
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/MathProduct.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace Coderbyte_CSharp.Easy_Challenges
6 | {
7 | class MathProduct
8 | {
9 | // Challenge
10 | // function ProductDigits(num) has a num parameter, which is a positive integer.
11 | // Determine the least amount of digits you need to multiply to produce the
12 | // value .
13 |
14 | // For example : if num is 24 then you can multiply 8 by 3 which produces 24,
15 | // so your program should return 2 because there is a total of only 2 digits
16 | // that are needed.
17 |
18 | // Another example : if num is 90, you can multiply 10 * 9, so in this case
19 | // your program should output 3 because you cannot reach 90 without using a
20 | // total of 3 digits in your multiplication.
21 |
22 | //Sample Test Cases
23 | // Input : 6
24 | // Output : 2
25 | // Input : 23
26 | // Output : 3
27 | public int ProductDigits(int num)
28 | {
29 | int result = num.ToString().Length + 1;
30 |
31 | int factor;
32 | int value;
33 | for (int index = 1; index <= Math.Sqrt(num); index++)
34 | {
35 | // Is index a factor of num
36 | if (num % index == 0)
37 | {
38 | factor = num / index;
39 | value = index.ToString().Length + factor.ToString().Length ;
40 | result = Math.Min(result, value);
41 | }
42 | }
43 |
44 |
45 | return result;
46 | }
47 |
48 | // Have the function OtherProducts(arr) take the array of numbers stored in arr
49 | // and return a new list of the products of all the other numbers in the array
50 | // for each element.
51 |
52 | // For example: if arr is [1, 2, 3, 4, 5] then the new array,
53 | // where each location in the new array is the product of all other elements,
54 | // is [120, 60, 40, 30, 24]. The following calculations were performed to get
55 | // this answer: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]. You
56 | // should generate this new array and then return the numbers as a string
57 | // joined by a hyphen: 120-60-40-30-24. The array will contain at most 10
58 | // elements and at least 1 element of only positive integers.
59 | public string OtherProducts(int[] arr, int length)
60 | {
61 | // ReSharper disable once RedundantAssignment
62 | string result = String.Empty;
63 | List productValues = new List(length);
64 | // ReSharper disable once TooWideLocalVariableScope
65 | int product = 1;
66 |
67 | for (int index = 0; index < length; index++)
68 | {
69 | product = ComputeProduct(arr, index);
70 | productValues.Add(product);
71 | }
72 |
73 | StringBuilder sb = new StringBuilder();
74 |
75 | foreach (int item in productValues)
76 | {
77 | sb.Append(item);
78 | sb.Append("-");
79 | }
80 |
81 | result = sb.ToString();
82 | result = result.Remove(result.Length - 1);
83 |
84 | return result;
85 | }
86 |
87 | protected int ComputeProduct(int[] arr, int index)
88 | {
89 | int result = 1;
90 | int length = arr.Length;
91 |
92 | for (int i = 0; i < length; i++)
93 | {
94 | if (i == index) { continue; }
95 | result *= arr[i];
96 | }
97 |
98 | return result;
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/1 Easy Challenges/QuestionMarkSum.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Coderbyte_CSharp.Easy_Challenges
4 | {
5 | class QuestionMarkSum
6 | {
7 | // Have the function QuestionsMarks(str) take the str string parameter, which
8 | // will contain single digit numbers, letters, and question marks, and check
9 | // if there are exactly 3 question marks between every pair of two numbers
10 | // that add up to 10. If so, then your program should return the string true,
11 | // otherwise it should return the string false.If there aren't any two numbers
12 | // that add up to 10 in the string, then your program should return false as well.
13 |
14 | // For example : if str is "arrb6???4xxbl5???eee5" then your program should return
15 | // true because there are exactly 3 question marks between 6 and 4, and 3 question
16 | // marks between 5 and 5 at the end of the string.
17 | public string QuestionsMarks(string str)
18 | {
19 | string result = String.Empty;
20 | bool pass = false;
21 | int firstPos = -1;
22 | int secondPos = -1;
23 | int index = 0;
24 |
25 | while (index < str.Length)
26 | {
27 | if (FindNumbersInString(str, index, out firstPos, out secondPos))
28 | {
29 |
30 | int first = (int)Char.GetNumericValue(str[firstPos]);
31 | int second = (int)Char.GetNumericValue(str[secondPos]);
32 |
33 |
34 | // 2 integers must equal 10
35 | if ((first + second) == 10)
36 | {
37 | // There must be exactly 3 question marks between 2 integers
38 | pass = IsQuestionMarksExist(str, firstPos, secondPos);
39 | }
40 |
41 | index = secondPos + 1;
42 | }
43 |
44 | // No numbers found in string
45 | else
46 | {
47 | pass = false;
48 | break;
49 | }
50 | }
51 |
52 | result = pass ? "true" : "false";
53 |
54 | return result;
55 | }
56 |
57 | protected bool FindNumbersInString(string str, int start, out int first, out int second)
58 | {
59 | bool result = false;
60 | first = -1;
61 | second = -1;
62 |
63 | if (start == str.Length - 1)
64 | {
65 | return false;
66 | }
67 |
68 | for (int index = start; index < str.Length; index++)
69 | {
70 | if (Char.IsDigit(str[index]))
71 | {
72 | if (first == -1)
73 | {
74 | first = index;
75 | }
76 |
77 | else
78 | {
79 | second = index;
80 | break;
81 | }
82 | }
83 | }
84 |
85 | result = (first != -1 && second != -1);
86 |
87 | return result;
88 | }
89 |
90 | protected bool IsQuestionMarksExist(string str, int start, int end)
91 | {
92 | bool result = false;
93 |
94 | int num1 = start + 1;
95 | int num2 = end;
96 | int count = 0;
97 |
98 | if (num2 - num1 >= 3)
99 | {
100 | for (int index = num1; index < num2; index++)
101 | {
102 | if (str[index] == '?')
103 | {
104 | count++;
105 | }
106 | }
107 |
108 | result = (count == 3);
109 | }
110 |
111 |
112 | return result;
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/2 Medium Challenges/StringMinimumWindow.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Coderbyte_CSharp.Medium_Challenges
5 | {
6 | class StringMinimumWindow
7 | {
8 | // Have the function MinWindowSubstring(strArr) take the array of strings stored
9 | // in strArr, which will contain only two strings, the first parameter being the
10 | // string N and the second parameter being a string K of some characters, and your
11 | // goal is to determine the smallest substring of N that contains all the characters
12 | // in K.
13 | //
14 | // For example: if strArr is ["aaabaaddae", "aed"] then the smallest substring of N
15 | // that contains the characters a, e, and d is "dae" located at the end of the string.
16 | // So for this example your program should return the string dae.
17 |
18 | // Another example: if strArr is ["aabdccdbcacd", "aad"] then the smallest substring
19 | // of N that contains all of the characters in K is "aabd" which is located at the
20 | // beginning of the string. Both parameters will be strings ranging in length from
21 | // 1 to 50 characters and all of K's characters will exist somewhere in the string N.
22 | // Both strings will only contains lowercase alphabetic characters.
23 |
24 | // Examples
25 | // Input: {"ahffaksfajeeubsne", "jefaa"}
26 | // Output: aksfaje
27 |
28 | // Input: {"aaffhkksemckelloe", "fhea"}
29 | // Output: affhkkse
30 |
31 | public string MinWindowSubstring(string[] strArr, int arrLength)
32 | {
33 | string result = string.Empty;
34 |
35 | string text = strArr[0];
36 | string pattern = strArr[1];
37 |
38 | Dictionary countMap = CreateCountMap(pattern);
39 | List windows = ExtractWindows(text, pattern.Length);
40 |
41 | foreach (string window in windows)
42 | {
43 | if (IsValidWindow(window, countMap))
44 | {
45 | if (String.IsNullOrEmpty(result))
46 | {
47 | result = window;
48 | }
49 | else if (window.Length < result.Length)
50 | {
51 | result = window;
52 | }
53 | }
54 | }
55 |
56 | return result;
57 | }
58 |
59 | protected Dictionary CreateCountMap(string str)
60 | {
61 | Dictionary countMap = new Dictionary();
62 |
63 | foreach (char c in str)
64 | {
65 | if (countMap.ContainsKey(c))
66 | {
67 | countMap[c]++;
68 | }
69 |
70 | else
71 | {
72 | countMap.Add(c, 1);
73 | }
74 | }
75 | return countMap;
76 | }
77 |
78 | protected List ExtractWindows(string str, int length)
79 | {
80 | List windows = new List();
81 | int strLength = str.Length;
82 |
83 |
84 | for (int start = 0; start < strLength; start++)
85 | {
86 | for (int end = start + length; end < strLength + 1; end++)
87 | {
88 | windows.Add(str.Substring(start, end - start));
89 | }
90 | }
91 |
92 | return windows;
93 | }
94 |
95 | protected bool IsValidWindow(string window, Dictionary patternMap)
96 | {
97 | bool isValid = true;
98 |
99 | Dictionary windowMap = CreateCountMap(window);
100 |
101 | foreach(var item in patternMap)
102 | {
103 | var key = item.Key;
104 | var val = item.Value;
105 |
106 | if (!windowMap.ContainsKey(key) || windowMap[key] < val)
107 | {
108 | isValid = false;
109 | }
110 | }
111 |
112 | return isValid;
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/Coderbyte_CSharp.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {F4056BC8-6438-4350-BF70-6920F21D78FC}
8 | Exe
9 | Coderbyte_CSharp
10 | Coderbyte_CSharp
11 | v4.6.1
12 | 512
13 | true
14 | true
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/2 Medium Challenges/StringReducer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Text;
3 |
4 | namespace Coderbyte_CSharp.Medium_Challenges
5 | {
6 | class StringReducer
7 | {
8 | // For this challenge you will manipulate a string of characters using a simple
9 | // reduction method.
10 |
11 | // The function StringReduction(str) take the str parameter being passed and
12 | // return the smallest number you can get through the following reduction
13 | // method. The method is: Only the letters a, b, and c will be given in str and
14 | // you must take two different adjacent characters and replace it with the third.
15 |
16 | // For example "ac" can be replaced with "b" but "aa" cannot be replaced with
17 | // anything. This method is done repeatedly until the string cannot be further
18 | // reduced, and the length of the resulting string is to be outputted.
19 |
20 | // For example: if str is "cab", "ca" can be reduced to "b" and you get "bb" (you
21 | // can also reduce it to "cc"). The reduction is done so the output should be 2.
22 | // If str is "bcab", "bc" reduces to "a", so you have "aab", then "ab" reduces to
23 | // "c", and the final string "ac" is reduced to "b" so the output should be 1.
24 | public int StringReduction(string str)
25 | {
26 | int result = 0;
27 | string localStr = str;
28 | int length = str.Length;
29 | bool done = false;
30 |
31 | if (length == 1)
32 | {
33 | result = 1;
34 | }
35 |
36 | else if (length == 2)
37 | {
38 | string temp = ConvertChar(str[0], str[1]);
39 | result = temp.Length;
40 | }
41 |
42 | else
43 | {
44 | while (!done)
45 | {
46 | string temp;
47 |
48 | //cout << "Reduction: " << localStr;
49 | for (int index = 0; index < localStr.Length - 1 && !done; index++)
50 | {
51 | temp = ConvertChar(localStr[index], localStr[index + 1]);
52 |
53 | // remove chars
54 | localStr = localStr.Remove(index, 2);
55 |
56 | // replace chars
57 | localStr = localStr.Insert(index, temp);
58 |
59 | // check if end criteria met
60 | done = IsDone(localStr);
61 | }
62 |
63 | if (done)
64 | {
65 | result = localStr.Length;
66 | }
67 |
68 | else
69 | {
70 | //cout << "Need another iteration" << endl;
71 | }
72 | }
73 | }
74 |
75 | return result;
76 | }
77 |
78 | protected string ConvertChar(char first, char second)
79 | {
80 | string result = String.Empty;
81 |
82 | if (first == second)
83 | {
84 | StringBuilder sb = new StringBuilder();
85 |
86 | sb.Append(first);
87 | sb.Append(second);
88 |
89 | result = sb.ToString();
90 | }
91 |
92 | else
93 | {
94 | if ((first == 'a' && second == 'b') ||
95 | (first == 'b' && second == 'a'))
96 | {
97 | result = "c";
98 | }
99 |
100 | else if ((first == 'a' && second == 'c') ||
101 | (first == 'c' && second == 'a'))
102 | {
103 | result = "b";
104 | }
105 |
106 | else if ((first == 'b' && second == 'c') ||
107 | (first == 'c' && second == 'b'))
108 | {
109 | result = "a";
110 | }
111 | }
112 |
113 | return result;
114 | }
115 |
116 | protected bool IsDone(string str)
117 | {
118 | bool done = false;
119 |
120 | int length = str.Length;
121 |
122 | if (length == 1)
123 | {
124 | done = true;
125 | }
126 |
127 | else
128 | {
129 | done = true;
130 | char checkchar = str[0];
131 |
132 | for (int index = 1; index < length && done; index++)
133 | {
134 | done = (checkchar == str[index]);
135 | }
136 | }
137 |
138 | return done;
139 | }
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
--------------------------------------------------------------------------------
/Coderbyte_CSharp/3 Hard Challenges/MatrixDeterminant.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Coderbyte_CSharp.Hard_Challenges
5 | {
6 | class Determinant
7 | {
8 | // Have the function MatrixDeterminant(strArr) read strArr which will be an
9 | // array of integers represented as strings.Within the array there will also
10 | // be "<>" elements which represent break points.The array will make up a
11 | // matrix where the(number of break points + 1) represents the number of
12 | // rows.Here is an example of how strArr may look : ["1", "2", "<>", "3", "4"].
13 | //
14 | // The contents of this array are row1 = [1 2] and row2 = [3 4]. Your program
15 | // should take the given array of elements, create the proper matrix, and then
16 | // calculate the determinant. For the example above, your program should return -2.
17 | // If the matrix is not a square matrix, return -1. The maximum size of strArr
18 | // will be a 6x6 matrix.The determinant will always be an integer.
19 | public int MatrixDeterminant(string[] strArr, int size)
20 | {
21 | int determinant = 0;
22 |
23 | List> matrix = new List>();
24 |
25 | ParseMatrix(strArr, size, ref matrix);
26 |
27 |
28 | if (IsSquareMatrix(matrix))
29 | {
30 | determinant = ComputeDeterminant(matrix);
31 | }
32 |
33 | else
34 | {
35 | Console.WriteLine("matrix is not square");
36 | }
37 |
38 | return determinant;
39 | }
40 |
41 | protected bool IsSquareMatrix(List> matrix)
42 | {
43 | bool isSquare = true;
44 |
45 | // checking if input matrix is square
46 | for (int row = 0; row < matrix.Count; row++)
47 | {
48 | if (matrix[row].Count != matrix.Count)
49 | {
50 | isSquare = false;
51 | break;
52 | }
53 | }
54 |
55 | return isSquare;
56 | }
57 |
58 | protected void ParseMatrix(string[] strArr, int size, ref List> matrix)
59 | {
60 | List rowData = new List();
61 |
62 | for (int x = 0; x < size; x++)
63 | {
64 | // condition to check for breakpoints
65 | if (strArr[x] == "<>")
66 | {
67 | // Create a separate copy of rowData for matrix
68 | matrix.Add(new List(rowData));
69 | rowData.Clear();
70 | }
71 | else
72 | {
73 | // converting to int
74 | int value = 0;
75 |
76 | // convert to snippet
77 | try
78 | {
79 | value = Int32.Parse(strArr[x]);
80 | }
81 | catch (FormatException e)
82 | {
83 | Console.WriteLine("Unable to parse {0}", strArr[x]);
84 | Console.Error.Write(e.Message);
85 | }
86 |
87 | // adding to our row
88 | rowData.Add(value);
89 | }
90 | }
91 | // adding last row
92 | // Create a separate copy of rowData for matrix
93 | matrix.Add(new List(rowData));
94 | }
95 |
96 | protected int ComputeDeterminant(List> matrix)
97 | {
98 | int determinant = 0;
99 |
100 | if (matrix.Count == 1)
101 | {
102 | determinant = matrix[0][0];
103 | }
104 | // check for 2-by-2 matrix perform det calculation
105 | else if (matrix.Count == 2)
106 | {
107 | determinant = (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
108 | }
109 |
110 | // otherwise determine cofactor, submatrix and recursively compute determinant
111 | else
112 | {
113 | int cofactor = 0;
114 | // iterate across first row to set cofactor
115 | for (int p = 0; p < matrix[0].Count; p++)
116 | {
117 | // create submatrix
118 | List> subMatrix = new List>();
119 | int matrixSize = matrix.Count;
120 |
121 | for (int i = 1; i < matrixSize; i++)
122 | {
123 | // iteration will start from row one cancelling the first row values
124 | List tempRow = new List();
125 |
126 | for (int j = 0; j < matrixSize; j++)
127 | {
128 | // iteration will pass all cells of the i row excluding the j
129 | //value that match p column
130 | if (j != p)
131 | {
132 | tempRow.Add(matrix[i][j]);//add current cell to TempRow
133 | }
134 | }
135 |
136 | // Adding each row to submatrix
137 | if (tempRow.Count > 0)
138 | {
139 | subMatrix.Add(tempRow);
140 | }
141 | }
142 |
143 | // recursively calculate the determinant value
144 | cofactor = matrix[0][p];
145 | determinant += (int)(Math.Pow(-1, p)) * cofactor * ComputeDeterminant(subMatrix);
146 | }
147 | }
148 |
149 | return determinant;
150 | }
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/2 Medium Challenges/TreeGraphs.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Data.SqlTypes;
4 | using System.Linq;
5 | using System.Net.Http.Headers;
6 | using System.Text;
7 |
8 | namespace Coderbyte_CSharp.Medium_Challenges
9 | {
10 | class Node
11 | {
12 | public string Key;
13 | public Node Left;
14 | public Node Right;
15 |
16 | public Node(string item)
17 | {
18 | Key = item;
19 | Left = null;
20 | Right = null;
21 | }
22 | }
23 |
24 | class TreeGraphs
25 | {
26 | public string TreeConstructor(string[] strArr, int length)
27 | {
28 | string result = String.Empty;
29 |
30 | bool validTree = true;
31 | List input = strArr.ToList();
32 | List> data = new List>();
33 | Dictionary> parents = new Dictionary>();
34 | Dictionary childCount = new Dictionary();
35 | int root = 0;
36 |
37 | data = ParseInput(input);
38 |
39 | foreach (var item in data)
40 | {
41 | int key = item.Key;
42 |
43 | // parents[item.first] = item.second;
44 | // Key Exists - add to list
45 | if (!parents.TryGetValue(key, out List valueList))
46 | {
47 | valueList = new List();
48 | parents.Add(key, valueList);
49 | }
50 |
51 | valueList.Add(item.Value);
52 |
53 | if (childCount.ContainsKey(item.Value))
54 | {
55 | childCount[item.Value]++;
56 | }
57 |
58 | else
59 | {
60 | childCount.Add(item.Value, 1);
61 | }
62 | }
63 |
64 | // find root
65 | foreach (var item in data)
66 | {
67 | if (parents.ContainsKey(item.Value))
68 | {
69 | root = item.Value;
70 | }
71 | }
72 |
73 | validTree = (root != 0);
74 |
75 | // check for > 2 children
76 | foreach (var item in childCount)
77 | {
78 | if (item.Value > 2)
79 | {
80 | validTree = false;
81 | }
82 | }
83 |
84 | // check for child with multiple parents
85 | foreach (var item in parents)
86 | {
87 | // Check if List is count > 1
88 | if (item.Value.Count > 1)
89 | {
90 | validTree = false;
91 | break;
92 | }
93 | }
94 |
95 | result = (validTree) ? "true" : "false";
96 |
97 | return result;
98 | }
99 |
100 | // For this challenge you will traverse a binary tree and determine if it is symmetric.
101 | // The function SymmetricTree(strArr) take the array of strings stored in strArr,
102 | // which will represent a binary tree, and determine if the tree is symmetric (a
103 | // mirror image of itself). The array will be implemented similar to how a binary
104 | // heap is implemented, except the tree may not be complete and NULL nodes on any
105 | // level of the tree will be represented with a #.
106 |
107 | // For example: if strArr is ["1", "2", "2", "3", "#", "#", "3"]
108 | // Tree:
109 | // 1
110 | // 2 2
111 | // 3 # # 3
112 |
113 | // For the input above, your program should return the string true because the
114 | // binary tree is symmetric.
115 |
116 | public string SymmetricTree(string[] strArr, int length)
117 | {
118 | string result = String.Empty;
119 | bool isSymmetric = false;
120 | List input = new List(strArr);
121 |
122 | Node root = CreateTreeNode(input[0]);
123 |
124 | //populate tree
125 | root = FillTree(input, root, 0, input.Count);
126 |
127 | // check for symmetry
128 | isSymmetric = IsTreeSymmetric(root, root);
129 |
130 |
131 | result = (isSymmetric) ? "true" : "false";
132 |
133 |
134 |
135 |
136 | return result;
137 | }
138 |
139 | // For this challenge you will be traversing a binary tree.
140 | // have the function PreorderTraversal(strArr) take the array of strings stored
141 | // in strArr, which will represent a binary tree with integer values in a format
142 | // similar to how a binary heap is implemented with NULL nodes at any level
143 | // represented with a #. Your goal is to return the pre-order traversal of the
144 | // tree with the elements separated by a space.
145 | // For example: if strArr is ["5", "2", "6", "1", "9", "#", "8", "#", "#", "#",
146 | // "#", "4", "#"]
147 | public string PreorderTraversal(string[] strArr, int length)
148 | {
149 | string result = String.Empty;
150 |
151 | List input = new List(strArr);
152 |
153 | // create tree
154 | Node root = CreateTreeNode(input[0]);
155 | root = FillTree(input, root, 0, input.Count);
156 |
157 | result = CreatePreorderOutput(root);
158 |
159 | return result;
160 | }
161 |
162 | protected string CreatePreorderOutput(Node node)
163 | {
164 | string result = String.Empty;
165 |
166 | StringBuilder sb = new StringBuilder();
167 |
168 | if ((node != null) && !node.Key.Equals(value: "#"))
169 | {
170 | /* first print data of node */
171 | if (!node.Key.Equals("#"))
172 | {
173 | sb.AppendFormat("{0} ",node.Key);
174 | }
175 |
176 | /* then recur on left sutree */
177 | var left = CreatePreorderOutput(node.Left);
178 | sb.Append(left);
179 |
180 | /* now recur on right subtree */
181 | var right = CreatePreorderOutput(node.Right);
182 | sb.Append(right);
183 |
184 |
185 | result = sb.ToString();
186 | }
187 |
188 | return result;
189 | }
190 |
191 | private Node FillTree(List arr, Node root, int index, int length)
192 | {
193 | if (index < length)
194 | {
195 | Node temp = CreateTreeNode(arr[index]);
196 | root = temp;
197 |
198 | if (temp != null)
199 | {
200 | int childIndex = 2 * index + 1;
201 |
202 | if (childIndex == length)
203 | {
204 | childIndex -= 2;
205 | }
206 | // insert left child
207 | root.Left = FillTree(arr, root.Left, childIndex, length);
208 |
209 | // insert right child
210 | root.Right = FillTree(arr, root.Right, childIndex+1, length);
211 | }
212 | }
213 |
214 | return root;
215 | }
216 |
217 |
218 | protected List> ParseInput(List input)
219 | {
220 | List> data = new List>();
221 |
222 | // parse input into data vector
223 | foreach (string str in input)
224 | {
225 | int num1 = 0;
226 | int num2 = 0;
227 | KeyValuePair dataItem;
228 |
229 | ParseInputString(str, ref num1, ref num2);
230 | dataItem = new KeyValuePair(num1, num2);
231 | data.Add(dataItem);
232 | }
233 |
234 | return data;
235 | }
236 |
237 | protected void ParseInputString(string str, ref int num1, ref int num2)
238 | {
239 | // assume correct structure
240 | // find comma -> substr-> trim '('
241 | // substr rest of str -> trim ')'
242 |
243 | int pos;
244 | string delimiter = new string(',', 1);
245 | string temp;
246 |
247 | // extract first number
248 | pos = str.IndexOf(delimiter, StringComparison.Ordinal);
249 | if (pos != -1)
250 | {
251 | // remove ( char
252 | temp = str.Substring(pos - 1, 1);
253 |
254 | try
255 | {
256 | num1 = Int32.Parse(temp);
257 | }
258 | catch (FormatException e)
259 | {
260 | Console.WriteLine("Unable to parse {0}", temp);
261 | Console.Error.Write(e.Message);
262 | }
263 | }
264 |
265 | else
266 | {
267 | // pos == -1 --> delimiter not found assumed to exist
268 | }
269 |
270 | // extract 2nd number
271 | temp = str.Substring(pos + 1, 1);
272 | try
273 | {
274 | num2 = Int32.Parse(temp);
275 | }
276 | catch (FormatException e)
277 | {
278 | Console.WriteLine("Unable to parse {0}", temp);
279 | Console.Error.Write(e.Message);
280 | }
281 | }
282 |
283 | protected Node CreateTreeNode(string data)
284 | {
285 | Node node = null;
286 |
287 | if (!data.Equals("#"))
288 | {
289 | node = new Node(data);
290 | }
291 |
292 | return node;
293 | }
294 |
295 |
296 | protected bool IsTreeSymmetric(Node node1, Node node2)
297 | {
298 | bool isSymmetric = false;
299 |
300 | // empty tree
301 | if (node1 == null && node2 == null)
302 | {
303 | isSymmetric = true;
304 | }
305 |
306 | // For two trees to be mirror images,
307 | // the following three conditions must be true
308 | // 1 - Their root node's data must be same
309 | // 2 - left subtree of left tree and right subtree of right tree are equal
310 | // 3 - right subtree of left tree and left subtree of right tree are equal
311 | else if (node1 != null && node2 != null && node1.Key == node2.Key)
312 | {
313 | isSymmetric = IsTreeSymmetric(node1.Left, node2.Right) &&
314 | IsTreeSymmetric(node1.Right, node2.Left);
315 | }
316 | return isSymmetric;
317 | }
318 | }
319 | }
320 |
--------------------------------------------------------------------------------
/Coderbyte_CSharp/TestChallenge.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using Coderbyte_CSharp._1_Easy_Challenges;
6 | using Coderbyte_CSharp._3_Hard_Challenges;
7 | using Coderbyte_CSharp.Easy_Challenges;
8 | using Coderbyte_CSharp.Hard_Challenges;
9 | using Coderbyte_CSharp.Medium_Challenges;
10 |
11 | namespace Coderbyte_CSharp
12 | {
13 | class TestChallenge
14 | {
15 | #region Support Methods
16 | protected void PrintArray(int[] arr, int length)
17 | {
18 |
19 | List data = arr.ToList();
20 |
21 | Console.Write("Array: [");
22 | StringBuilder sb = new StringBuilder();
23 |
24 | foreach(var value in data)
25 | {
26 | sb.Append(value);
27 | sb.Append(",");
28 | }
29 |
30 | // Remove last comma
31 | sb.Remove(sb.Length - 1, 1);
32 |
33 | Console.Write("{0}]", sb);
34 | Console.WriteLine();
35 | }
36 |
37 | protected void PrintArray(string[] arr, int length)
38 | {
39 |
40 | List data = arr.ToList();
41 |
42 | Console.Write("Array: [");
43 | StringBuilder sb = new StringBuilder();
44 |
45 | foreach (var value in data)
46 | {
47 | sb.Append(value);
48 | sb.Append(",");
49 | }
50 |
51 | // Remove last comma
52 | sb.Remove(sb.Length - 1, 1);
53 |
54 | Console.Write("{0}]", sb);
55 | Console.WriteLine();
56 | }
57 |
58 | #endregion
59 |
60 | #region Easy Challenges
61 | public void Test_TimeConvert()
62 | {
63 | int totalMinutes = 73;
64 | TimeConverter tc = new TimeConverter();
65 |
66 | Console.WriteLine("TimeConvert:");
67 | Console.WriteLine("Input: {0} minutes", totalMinutes);
68 | Console.WriteLine("Output: {0}", tc.TimeConvert(totalMinutes));
69 | Console.WriteLine();
70 |
71 | }
72 |
73 | public void Test_AlphabetSoup()
74 | {
75 | string text = "jgklsgtiowegtankvlae";
76 | AlphabetSorter alpha = new AlphabetSorter();
77 |
78 | Console.WriteLine("Alphabet Soup:");
79 | Console.WriteLine("Input: {0}", text);
80 | Console.WriteLine("Output: {0}", alpha.AlphabetSoup(text));
81 | Console.WriteLine();
82 | }
83 |
84 | public void Test_ArithGeoSequence()
85 | {
86 | int[] arr = { 2, 4, 8, 16 };
87 | int length = 4;
88 | MathSequence sequence = new MathSequence();
89 |
90 | Console.WriteLine("ArithGeo Sequence:");
91 | PrintArray(arr, length);
92 | Console.WriteLine("Output: {0}", sequence.ArithGeo(arr, length));
93 | Console.WriteLine();
94 |
95 | }
96 |
97 | public void Test_Palindrome()
98 | {
99 | string text = "jgklsgtiowegtankvlae";
100 | PalindromeChecker checker = new PalindromeChecker();
101 |
102 | Console.WriteLine("Palindrome:");
103 | Console.WriteLine("Input: {0}", text);
104 | Console.WriteLine("Output: {0}", checker.Palindrome(text));
105 | Console.WriteLine();
106 |
107 |
108 | text = "helleh";
109 | Console.WriteLine("Input: {0}", text);
110 | Console.WriteLine("Output: {0}", checker.Palindrome(text));
111 |
112 | Console.WriteLine();
113 |
114 | }
115 |
116 | public void Test_NumberCheck()
117 | {
118 | int num1 = 34;
119 | int num2 = 56;
120 |
121 | NumberCheck checker = new NumberCheck();
122 |
123 | Console.WriteLine("Number Check:");
124 |
125 | Console.WriteLine("Input: {0}, {1}", num1, num2);
126 | Console.WriteLine("Output: {0}", checker.CheckNumber(num1, num2));
127 | Console.WriteLine();
128 |
129 | num1 = 79;
130 | num2 = 13;
131 | Console.WriteLine("Input: {0}, {1}", num1, num2);
132 | Console.WriteLine("Output: {0}", checker.CheckNumber(num1, num2));
133 | Console.WriteLine();
134 |
135 | num1 = num2;
136 | Console.WriteLine("Input: {0}, {1}", num1, num2);
137 | Console.WriteLine("Output: {0}", checker.CheckNumber(num1, num2));
138 |
139 | Console.WriteLine();
140 | }
141 |
142 | public void Test_FindIntersection()
143 | {
144 | string[] strArr = new string[2];
145 | string one = "3, 4, 7, 11, 21";
146 | string two = "4, 6, 7, 13, 21";
147 |
148 | strArr[0] = one;
149 | strArr[1] = two;
150 |
151 | StringIntersection si = new StringIntersection();
152 |
153 | Console.WriteLine("FindIntersection: ");
154 | Console.WriteLine("Input: first: {0} , second: {1}", strArr[0], strArr[1]);
155 | Console.WriteLine("Output: {0}", si.FindIntersection(strArr));
156 |
157 | Console.WriteLine();
158 | }
159 |
160 | public void Test_FirstFactorial()
161 | {
162 | Console.WriteLine("First Factorial:");
163 | Factorial compute = new Factorial();
164 |
165 | int num = 5;
166 | Console.WriteLine("Input: {0}", num);
167 | Console.WriteLine("Output: {0}", compute.FirstFactorial(num));
168 |
169 | num = 10;
170 | Console.WriteLine("Input: {0}", num);
171 | Console.WriteLine("Output: {0}", compute.FirstFactorial(num));
172 |
173 | num = 18;
174 | Console.WriteLine("Input: {0}", num);
175 | Console.WriteLine("Output: {0}", compute.FirstFactorial(num));
176 | Console.WriteLine();
177 | }
178 |
179 | public void Test_FirstReverse()
180 | {
181 | StringReverse reverser = new StringReverse();
182 |
183 | string str = "Hello World and Coders";
184 |
185 | Console.WriteLine("First Reverse:");
186 | Console.WriteLine("Input: {0}", str);
187 | Console.WriteLine("Output: {0}", reverser.FirstReverse(str));
188 | Console.WriteLine();
189 | }
190 |
191 | public void Test_LetterChanges()
192 | {
193 | ChangeLetter changer = new ChangeLetter();
194 |
195 | string str = "applez";
196 |
197 | Console.WriteLine("Letter Changes:");
198 | Console.WriteLine("Input: {0}", str);
199 | Console.WriteLine("Output: {0}", changer.LetterChanges(str));
200 | Console.WriteLine();
201 |
202 | str = "coderbyte";
203 |
204 | Console.WriteLine("Input: {0}", str);
205 | Console.WriteLine("Output: {0}", changer.LetterChanges(str));
206 | Console.WriteLine();
207 | }
208 | public void Test_LetterCapitalize()
209 | {
210 | ChangeLetter changer = new ChangeLetter();
211 |
212 | string str = "applez";
213 |
214 | Console.WriteLine("Letter Capitalize:");
215 | Console.WriteLine("Input: {0}", str);
216 | Console.WriteLine("Output: {0}", changer.LetterCapitalize(str));
217 | Console.WriteLine();
218 |
219 | str = "coder byte";
220 |
221 | Console.WriteLine("Input: {0}", str);
222 | Console.WriteLine("Output: {0}", changer.LetterCapitalize(str));
223 | Console.WriteLine();
224 | }
225 |
226 | public void Test_PowerOfTwo()
227 | {
228 | ExponentTwo power = new ExponentTwo();
229 |
230 | int num = 16;
231 |
232 | Console.WriteLine("Powers of Two:");
233 | Console.WriteLine("Input: {0}", num);
234 | Console.WriteLine("Output: {0}", power.PowersofTwo(num));
235 | Console.WriteLine();
236 |
237 | num = 34;
238 |
239 | Console.WriteLine("Input: {0}", num);
240 | Console.WriteLine("Output: {0}", power.PowersofTwo(num));
241 | Console.WriteLine();
242 | }
243 |
244 | public void Test_ProductDigits()
245 | {
246 | MathProduct prod = new MathProduct();
247 | int num = 90;
248 |
249 | Console.WriteLine("Product Digits:");
250 | Console.WriteLine("Input: {0}", num);
251 | Console.WriteLine("Output: {0}", prod.ProductDigits(num));
252 | Console.WriteLine();
253 |
254 | num = 6;
255 | Console.WriteLine("Product Digits:");
256 | Console.WriteLine("Input: {0}", num);
257 | Console.WriteLine("Output: {0}", prod.ProductDigits(num));
258 | Console.WriteLine();
259 |
260 | num = 23;
261 | Console.WriteLine("Product Digits:");
262 | Console.WriteLine("Input: {0}", num);
263 | Console.WriteLine("Output: {0}", prod.ProductDigits(num));
264 | Console.WriteLine();
265 | }
266 |
267 | public void Test_OtherProducts()
268 | {
269 | MathProduct prod = new MathProduct();
270 | int[] arr = {1, 2, 3, 4, 5 };
271 |
272 |
273 | Console.WriteLine("Other Products:");
274 | PrintArray(arr, arr.Length);
275 | Console.WriteLine("Output: {0}", prod.OtherProducts(arr, arr.Length));
276 | Console.WriteLine();
277 |
278 | }
279 |
280 | public void Test_VowelSquare()
281 | {
282 | SquareVowels square = new SquareVowels();
283 |
284 | Console.WriteLine("Letter Changes:");
285 |
286 | string[] strArr = { "abcd", "eikr", "oufj" };
287 | PrintArray(strArr, strArr.Length);
288 | Console.WriteLine("Output: {0}", square.VowelSquare(strArr, strArr.Length));
289 | Console.WriteLine();
290 |
291 | string[] strArr2 = { "lbzk", "ncdf", "mxio", "pqau" };
292 | PrintArray(strArr2, strArr2.Length);
293 | Console.WriteLine("Output: {0}", square.VowelSquare(strArr2, strArr2.Length));
294 | Console.WriteLine();
295 | }
296 |
297 | public void Test_LongestWord()
298 | {
299 | StringWords longest = new StringWords();
300 |
301 | string str = "The fox wouldn't lazy in the forest.";
302 |
303 | Console.WriteLine("Longest Word:");
304 | Console.WriteLine("Input: {0}", str);
305 | Console.WriteLine("Output: {0}", longest.LongestWord(str));
306 | Console.WriteLine();
307 | }
308 |
309 | public void Test_MovingMedian()
310 | {
311 | MedianMovement mover = new MedianMovement();
312 |
313 | Console.WriteLine("Moving Median:");
314 | int[] arr = {3, 1, 3, 5, 10, 6, 4, 3, 1};
315 |
316 | PrintArray(arr, arr.Length);
317 | Console.WriteLine("Output: {0}", mover.MovingMedian(arr, arr.Length));
318 | Console.WriteLine();
319 |
320 | }
321 |
322 | public void Test_QuestionsMarks()
323 | {
324 | QuestionMarkSum sum = new QuestionMarkSum();
325 |
326 | string str = "arrb6???4xxbl5???eee5";
327 | Console.WriteLine("Question Marks:");
328 | Console.WriteLine("Input: {0}", str);
329 | Console.WriteLine("Output: {0}", sum.QuestionsMarks(str));
330 | Console.WriteLine();
331 |
332 | str = "arrb6??4xxbl5???eee8";
333 | Console.WriteLine("Question Marks:");
334 | Console.WriteLine("Input: {0}", str);
335 | Console.WriteLine("Output: {0}", sum.QuestionsMarks(str));
336 | Console.WriteLine();
337 | }
338 |
339 | public void Test_RemoveBrackets()
340 | {
341 | StringBrackets brackets = new StringBrackets();
342 | Console.WriteLine("Remove Brackets:");
343 |
344 | string str = "(()))";
345 | Console.WriteLine("Input: {0}", str);
346 | Console.WriteLine("Output: {0}", brackets.RemoveBrackets(str));
347 | Console.WriteLine();
348 |
349 | str = "(())";
350 | Console.WriteLine("Input: {0}", str);
351 | Console.WriteLine("Output: {0}", brackets.RemoveBrackets(str));
352 | Console.WriteLine();
353 | }
354 |
355 | public void Test_FibonacciChecker()
356 | {
357 | MathFibonacci fibonacci = new MathFibonacci();
358 | Console.WriteLine("Fibonacci Checker:");
359 |
360 | int num = 5;
361 | Console.WriteLine("Input: {0}", num);
362 | Console.WriteLine("Output: {0}", fibonacci.FibonacciChecker(num));
363 | Console.WriteLine();
364 |
365 | num = 34;
366 | Console.WriteLine("Input: {0}", num);
367 | Console.WriteLine("Output: {0}", fibonacci.FibonacciChecker(num));
368 | Console.WriteLine();
369 |
370 | num = 54;
371 | Console.WriteLine("Input: {0}", num);
372 | Console.WriteLine("Output: {0}", fibonacci.FibonacciChecker(num));
373 | Console.WriteLine();
374 | }
375 |
376 | public void Test_SimpleAdding()
377 | {
378 | MathSummation sum = new MathSummation();
379 | Console.WriteLine("Simple Adding:");
380 |
381 | int num = 5;
382 | Console.WriteLine("Input: {0}", num);
383 | Console.WriteLine("Output: {0}", sum.SimpleAdding(num));
384 | Console.WriteLine();
385 |
386 | num = 15;
387 | Console.WriteLine("Input: {0}", num);
388 | Console.WriteLine("Output: {0}", sum.SimpleAdding(num));
389 | Console.WriteLine();
390 |
391 | num = 215;
392 | Console.WriteLine("Input: {0}", num);
393 | Console.WriteLine("Output: {0}", sum.SimpleAdding(num));
394 | Console.WriteLine();
395 | }
396 |
397 | public void Test_SimpleSymbols()
398 | {
399 | StringSymbols symbols = new StringSymbols();
400 | Console.WriteLine("Simple Symbols:");
401 |
402 | string str = "++d+===+c++==a";
403 | Console.WriteLine("Input: {0}", str);
404 | Console.WriteLine("Output: {0}", symbols.SimpleSymbols(str));
405 | Console.WriteLine();
406 | }
407 |
408 | public void Test_StringPeriods()
409 | {
410 | StringPeriod period = new StringPeriod();
411 | Console.WriteLine("Simple Periods:");
412 |
413 | string str = "abcababcababcab";
414 | Console.WriteLine("Input: {0}", str);
415 | Console.WriteLine("Output: {0}", period.StringPeriods(str));
416 | Console.WriteLine();
417 |
418 | str = "abababababab";
419 | Console.WriteLine("Input: {0}", str);
420 | Console.WriteLine("Output: {0}", period.StringPeriods(str));
421 | Console.WriteLine();
422 |
423 | str = "abcxabc";
424 | Console.WriteLine("Input: {0}", str);
425 | Console.WriteLine("Output: {0}", period.StringPeriods(str));
426 | Console.WriteLine();
427 | }
428 |
429 | public void Test_UsernameValidation()
430 | {
431 | UsernameValidation validation = new UsernameValidation();
432 | Console.WriteLine("Username Validation:");
433 |
434 | string str = "jgklfnklg_";
435 | Console.WriteLine("Input: {0}", str);
436 | Console.WriteLine("Output: {0}", validation.CodelandUsernameValidation(str));
437 | Console.WriteLine();
438 |
439 | str = "quick_gamester";
440 | Console.WriteLine("Input: {0}", str);
441 | Console.WriteLine("Output: {0}", validation.CodelandUsernameValidation(str));
442 | Console.WriteLine();
443 |
444 | str = "jkfld%jfkdsl";
445 | Console.WriteLine("Input: {0}", str);
446 | Console.WriteLine("Output: {0}", validation.CodelandUsernameValidation(str));
447 | Console.WriteLine();
448 |
449 | }
450 |
451 |
452 | #endregion
453 |
454 | #region Medium Challenges
455 | public void Test_Consecutive()
456 | {
457 | ConsecutiveNumbers numbers = new ConsecutiveNumbers();
458 |
459 | int[] arr = {4, 6, 8};
460 |
461 | Console.WriteLine("ArithGeo Sequence:");
462 |
463 | PrintArray(arr, arr.Length);
464 | Console.WriteLine("Output: {0}", numbers.Consecutive(arr, arr.Length));
465 | Console.WriteLine();
466 |
467 | }
468 |
469 | public void Test_KUniqueCharacters()
470 | {
471 | string str = "2aabbacbaa";
472 | StringUniqueSubstring unique = new StringUniqueSubstring();
473 |
474 | Console.WriteLine("K Unique Characters:");
475 |
476 | Console.WriteLine("Input: {0}", str);
477 | Console.WriteLine("Output: {0}", unique.KUniqueCharacters(str));
478 |
479 | Console.WriteLine();
480 | }
481 |
482 | public void Test_NumberEncoding()
483 | {
484 | NumberEncoder encoder = new NumberEncoder();
485 |
486 | Console.WriteLine("Number Encoding:");
487 |
488 | string str = "af5c a#!";
489 | Console.WriteLine("Input: {0}", str);
490 | Console.WriteLine("Output: {0}", encoder.NumberEncoding(str));
491 | Console.WriteLine();
492 |
493 | str = "bg&h q@l";
494 | Console.WriteLine("Input: {0}", str);
495 | Console.WriteLine("Output: {0}", encoder.NumberEncoding(str));
496 | Console.WriteLine();
497 | }
498 |
499 | public void Test_PrimeMover()
500 | {
501 | PrimeNumber prime = new PrimeNumber();
502 | int num = 3;
503 |
504 | Console.WriteLine("Prime Mover:");
505 |
506 | Console.WriteLine("Input: {0}", num);
507 | Console.WriteLine("Output: {0}", prime.PrimeMover(num));
508 | Console.WriteLine();
509 |
510 | num = 100;
511 | Console.WriteLine("Input: {0}", num);
512 | Console.WriteLine("Output: {0}", prime.PrimeMover(num));
513 | Console.WriteLine();
514 | }
515 |
516 | public void Test_MinWindowSubstring()
517 | {
518 | StringMinimumWindow minFinder = new StringMinimumWindow();
519 |
520 | string text = "ahffaksfajeeubsne";
521 | string pattern = "jefaa";
522 |
523 | string[] strArr = { text, pattern };
524 |
525 | Console.WriteLine("Minimum Window Substring:");
526 |
527 | Console.WriteLine("Input: {0} {1}", text, pattern);
528 | Console.WriteLine("Output: {0}", minFinder.MinWindowSubstring(strArr, strArr.Length));
529 | Console.WriteLine();
530 |
531 | text = "aaffhkksemckelloe";
532 | pattern = "fhea";
533 | strArr[0] = text;
534 | strArr[1] = pattern;
535 |
536 | Console.WriteLine("Input: {0} {1}", text, pattern);
537 | Console.WriteLine("Output: {0}", minFinder.MinWindowSubstring(strArr, strArr.Length));
538 | Console.WriteLine();
539 |
540 | }
541 |
542 | public void Test_RunLength()
543 | {
544 | StringCompression compress = new StringCompression();
545 | string str = "wwwggopp";
546 |
547 | Console.WriteLine("Run Length:");
548 |
549 | Console.WriteLine("Input: {0}", str);
550 | Console.WriteLine("Output: {0}", compress.RunLength(str));
551 | Console.WriteLine();
552 |
553 | str = "wwwbbbw";
554 | Console.WriteLine("Input: {0}", str);
555 | Console.WriteLine("Output: {0}", compress.RunLength(str));
556 | Console.WriteLine();
557 |
558 |
559 | }
560 |
561 | public void Test_StringReduction()
562 | {
563 | StringReducer reducer = new StringReducer();
564 | string str = "ac";
565 |
566 | Console.WriteLine("String Reduction:");
567 |
568 | Console.WriteLine("Input: {0}", str);
569 | Console.WriteLine("Output: {0}", reducer.StringReduction(str));
570 | Console.WriteLine();
571 |
572 | str = "cab";
573 | Console.WriteLine("Input: {0}", str);
574 | Console.WriteLine("Output: {0}", reducer.StringReduction(str));
575 | Console.WriteLine();
576 |
577 |
578 | }
579 |
580 | public void Test_TreeConstructor()
581 | {
582 | TreeGraphs tree = new TreeGraphs();
583 | string[] strArr = { "(1,2)", "(2,4)", "(7,2)" };
584 |
585 | Console.WriteLine("Tree Constructor:");
586 | PrintArray(strArr, strArr.Length);
587 | Console.WriteLine("Output: {0}", tree.TreeConstructor(strArr, strArr.Length));
588 | Console.WriteLine();
589 |
590 | string[] strArr2 = { "(1,2)", "(9,2)", "(2,4)", "(7,2)" };
591 | PrintArray(strArr2, strArr2.Length);
592 | Console.WriteLine("Output: {0}", tree.TreeConstructor(strArr2, strArr2.Length));
593 | Console.WriteLine();
594 |
595 | string[] strArr3 = { "(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)" };
596 | PrintArray(strArr3, strArr3.Length);
597 | Console.WriteLine("Output: {0}", tree.TreeConstructor(strArr3, strArr3.Length));
598 | Console.WriteLine();
599 | }
600 |
601 | public void Test_SymmetricTree()
602 | {
603 | TreeGraphs tree = new TreeGraphs();
604 | Console.WriteLine("Symmetric Tree:");
605 |
606 |
607 | string[] strArr = new[] { "1", "2", "2", "3", "#", "#", "3" };
608 |
609 | PrintArray(strArr, strArr.Length);
610 | Console.WriteLine("Output: {0}", tree.SymmetricTree(strArr, strArr.Length));
611 | Console.WriteLine();
612 |
613 | string[] strArr2 = new[] { "1", "2", "2", "3", "#", "3", "3" };
614 |
615 | PrintArray(strArr2, strArr2.Length);
616 | Console.WriteLine("Output: {0}", tree.SymmetricTree(strArr2, strArr2.Length));
617 | Console.WriteLine();
618 | }
619 |
620 | public void Test_PreorderTraversal()
621 | {
622 | TreeGraphs tree = new TreeGraphs();
623 | Console.WriteLine("Preorder Traversal:");
624 |
625 |
626 | string[] strArr = new[] { "5", "2", "6", "1", "9", "#", "8", "#", "#", "#", "#", "4", "#" };
627 |
628 | PrintArray(strArr, strArr.Length);
629 | Console.WriteLine("Output: {0}", tree.PreorderTraversal(strArr, strArr.Length));
630 | Console.WriteLine();
631 | }
632 | #endregion
633 |
634 | #region Hard Challenges
635 | public void Test_KaprekarsConstant()
636 | {
637 | Kaprekar k = new Kaprekar();
638 | int value = 3524;
639 |
640 | Console.WriteLine("Kaprekars Constant:");
641 | Console.WriteLine("Input: {0} ", value);
642 | Console.WriteLine("Output: {0}", k.KaprekarsConstant(value));
643 | Console.WriteLine();
644 | }
645 |
646 | public void Test_Determinant()
647 | {
648 | Determinant d = new Determinant();
649 |
650 | string[] array = { "1", "4", "3", "<>", "2", "3", "0", "<>", "5", "-3", "4" };
651 |
652 | Console.WriteLine("Matrix Determinant:");
653 | PrintArray(array, array.Length);
654 | Console.WriteLine("Output: {0}", d.MatrixDeterminant(array, array.Length));
655 | Console.WriteLine();
656 |
657 | }
658 |
659 | public void Test_ChessboardTraveling()
660 | {
661 | ChessBoard board = new ChessBoard();
662 | Console.WriteLine("Chessboard Traveling:");
663 |
664 | string str = "(1 1)(2 2)";
665 | Console.WriteLine("Input: {0}", str);
666 | Console.WriteLine("Output: {0}", board.ChessboardTraveling(str));
667 | Console.WriteLine();
668 |
669 | str = "(1 1)(5 4)";
670 | Console.WriteLine("Input: {0}", str);
671 | Console.WriteLine("Output: {0}", board.ChessboardTraveling(str));
672 | Console.WriteLine();
673 |
674 | }
675 | #endregion
676 | }
677 | }
678 |
--------------------------------------------------------------------------------