Chukwuma
I would cherish if someone would share an idea on how to solve the Simple Algebra Problem.
using System;
using System.Collections.Generic;
using System.Linq;
public abstract class Expr
{
public class Exp : Expr
{
public Expr Inner { get; }
public Exp(Expr inner) => Inner = inner;
}
public class Log : Expr
{
public Expr Inner { get; }
public Log(Expr inner) => Inner = inner;
}
public class X : Expr { }
}
public class Parser
{
public (Expr, List<string>) ParseExpr(List<string> tokens)
{
if (!tokens.Any())
throw new Exception("Unexpected end of expression");
var rest = tokens.Skip(1).ToList();
switch (tokens.First())
{
case "exp":
var (innerExp, restExp) = ParseExpr(rest);
return (new Expr.Exp(innerExp), restExp);
case "log":
var (innerLog, restLog) = ParseExpr(rest);
return (new Expr.Log(innerLog), restLog);
case "(":
var (innerParen, restParen) = ParseExpr(rest);
if (!restParen.Any() || restParen.First() != ")")
throw new Exception("Missing closing parenthesis");
return (innerParen, restParen.Skip(1).ToList());
default:
return (new Expr.X(), tokens);
}
}
public string SolveExpr(Expr expr, float a)
{
if (a < 0.0)
return "No";
return expr switch
{
Expr.Exp _ when a == 0.0 => "No",
_ => "Yes",
};
}
public string Solve(string f, float a)
{
var tokens = f.Split('(').ToList();
var (expr, _) = ParseExpr(tokens);
return SolveExpr(expr, a);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
public abstract class Expr
{
public class Exp : Expr
{
public Expr Inner { get; }
public Exp(Expr inner) => Inner = inner;
}
public class Log : Expr
{
public Expr Inner { get; }
public Log(Expr inner) => Inner = inner;
}
public class X : Expr { }
}
public class Parser
{
public (Expr, List<string>) ParseExpr(List<string> tokens)
{
if (!tokens.Any())
throw new Exception("Unexpected end of expression");
var rest = tokens.Skip(1).ToList();
switch (tokens.First())
{
case "exp":
var (innerExp, restExp) = ParseExpr(rest);
return (new Expr.Exp(innerExp), restExp);
case "log":
var (innerLog, restLog) = ParseExpr(rest);
return (new Expr.Log(innerLog), restLog);
case "(":
var (innerParen, restParen) = ParseExpr(rest);
if (!restParen.Any() || restParen.First() != ")")
throw new Exception("Missing closing parenthesis");
return (innerParen, restParen.Skip(1).ToList());
default:
return (new Expr.X(), tokens);
}
}
public string SolveExpr(Expr expr, float a)
{
if (a < 0.0)
return "No";
return expr switch
{
Expr.Exp _ when a == 0.0 => "No",
_ => "Yes",
};
}
public string Solve(string f, float a)
{
var tokens = f.Split('(').ToList();
var (expr, _) = ParseExpr(tokens);
return SolveExpr(expr, a);
}
}
2 replies