Skip to content

Instantly share code, notes, and snippets.

@SebiBasti
Created April 13, 2023 21:08
Show Gist options
  • Save SebiBasti/90c0843ea712103cfa9d6aef75b5e108 to your computer and use it in GitHub Desktop.
Save SebiBasti/90c0843ea712103cfa9d6aef75b5e108 to your computer and use it in GitHub Desktop.
FactFinder Challenge
using System;
public class Class1 { // find a more descriptive class name
public static bool IsFormat(string str, string f) // rename f to format and rename to IsFormatValid
{
var allowedDict = new Dictionary<string, bool>() // use an Array instead of a Dictionary
{
{ "number",true},
{ "date",true},
{ "timespan",true}
};
int isNotAllowed = 0; // rename to isAllowed and use a boolean instead (initial value should be false)
for (var i = 1; i < allowedDict.Count; i++) // iterate over array instead of dictionary and start the loop with 0
{
if (f == allowedDict.Keys.ToArray()[i - 1]) // with array you can get rid of keys.ToArray()
{
isNotAllowed |= 1 << i; // rename to isAllowed and set to true
}
}
if (isNotAllowed > 0) // rename to isAllowed and use !isAllowed
throw new Exception("Format not allowed."); // interpolate the format in the message and use ArgumentException instead
// if the code reaches this point it's enough to return true
// (function got initialized with boolean as its return value
if (f.ToLower() == "number")
return Int32.TryParse(str, out var _);
else if (f.ToLower() == "date")
return DateTime.TryParse(str, out var _);
else if (f.ToLower() == "timespan")
return DateTime.TryParse(str, out var _); // use TimeSpan.TryParse instead
throw new Exception("Unknown format."); // this line will never be reached
}
}
def getMiddle(string)
length = string.length
if length.odd?
string[(length - 1) / 2]
else
ind_1 = (length / 2 - 1)
ind_2 = (length / 2)
string[ind_1..ind_2]
end
end
puts 'Question 1/3 tests'
p getMiddle('test') == 'es'
p getMiddle('testing') == 't'
p getMiddle('middle') == 'dd'
p getMiddle('A') == 'A'
# --------------------------
def markdownConverter(input)
hash_count = input.scan(/#/).length
space_count = input.scan(/ /).length
if space_count == 1 && hash_count.between?(1, 6)
"<h#{hash_count}>" +
"#{input.gsub(/[ |#]+/, '')}" +
"</h#{hash_count}>"
else
input
end
end
puts 'Question 2/3 tests'
p markdownConverter('# Header') == '<h1>Header</h1>'
p markdownConverter('## Header') == '<h2>Header</h2>'
p markdownConverter('###### Header') == '<h6>Header</h6>'
p markdownConverter('####### Header') == '####### Header' # (too many hashes)
p markdownConverter('### Header') == '### Header' # (too many spaces between)
p markdownConverter('Header') == 'Header' # (no hashes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment