1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 11:09:07 +01:00
CodeWars/3kyu/binomial_expansion/solution.cs

104 lines
2.8 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
public class KataSolution {
public static IEnumerable<long> Combinations(long n) {
if (n < 0) {
Console.WriteLine("Error happened");
throw new ArgumentException("n cannot be negative");
}
for (
long k = 0, nCk = 1;
k <= n;
nCk = nCk * (n - k) / (k + 1), k++
) {
yield return nCk;
}
}
public static IEnumerable<long> Range(long count) {
for (var i = 0; i < count; i++) {
yield return i;
}
}
public static IEnumerable<long> Expand(int a, int b, int n) {
long aExpd = (long) Math.Pow(a, n);
long bExpd = 1;
foreach (var nCk in Combinations(n)) {
yield return nCk * aExpd * bExpd;
aExpd /= a;
bExpd *= b;
}
}
public static (int, int, string) ParseInner(string expr) {
var innerPart = expr.Split('^')[0];
innerPart = innerPart.Substring(1, innerPart.Length - 2);
var coeffA = new String(
innerPart.TakeWhile(c => !char.IsLetter(c)).ToArray()
);
var variable = new String(
innerPart.SkipWhile(c => !char.IsLetter(c)).TakeWhile(char.IsLetter).ToArray()
);
var coeffB = new String(
innerPart.SkipWhile(c => !char.IsLetter(c)).SkipWhile(char.IsLetter).ToArray()
);
var parsedCoeffA = coeffA switch {
"" => 1,
"-" => -1,
_ => int.Parse(coeffA)
};
return (parsedCoeffA, int.Parse(coeffB), variable);
}
public static int ParseExponent(string expr) {
var splitExpr = expr.Split('^');
return int.Parse(splitExpr[1]);
}
public static string FormatTerm(long coefficient, string variable, long exponent) {
var prefix = (coefficient > 0) ? "+" : "";
if (coefficient == 0) {
return "";
}
if ((coefficient == 1 || coefficient == -1) && exponent == 0) {
return $"{prefix}{coefficient}";
}
var coeff = coefficient switch {
0 => "",
1 => prefix,
-1 => "-",
_ => $"{prefix}{coefficient}"
};
var varExp = exponent switch {
0 => "",
1 => variable,
_ => $"{variable}^{exponent}"
};
return $"{coeff}{varExp}";
}
public static string Expand(string expr) {
var n = ParseExponent(expr);
var (a, b, variable) = ParseInner(expr);
var result = "";
foreach (var (exponent, coefficient) in Range(n + 1).Reverse().Zip(Expand(a, b, n))) {
result += FormatTerm(coefficient, variable, exponent);
}
return result.TrimStart(new char[] {'+'});
}
}