🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of gottaTw

gottaTw's solution

to Rational Numbers in the Delphi Pascal Track

Published at Mar 10 2021 · 0 comments
Instructions
Test suite
Solution

A rational number is defined as the quotient of two integers a and b, called the numerator and denominator, respectively, where b != 0.

The absolute value |r| of the rational number r = a/b is equal to |a|/|b|.

The sum of two rational numbers r1 = a1/b1 and r2 = a2/b2 is r1 + r2 = a1/b1 + a2/b2 = (a1 * b2 + a2 * b1) / (b1 * b2).

The difference of two rational numbers r1 = a1/b1 and r2 = a2/b2 is r1 - r2 = a1/b1 - a2/b2 = (a1 * b2 - a2 * b1) / (b1 * b2).

The product (multiplication) of two rational numbers r1 = a1/b1 and r2 = a2/b2 is r1 * r2 = (a1 * a2) / (b1 * b2).

Dividing a rational number r1 = a1/b1 by another r2 = a2/b2 is r1 / r2 = (a1 * b2) / (a2 * b1) if a2 * b1 is not zero.

Exponentiation of a rational number r = a/b to a non-negative integer power n is r^n = (a^n)/(b^n).

Exponentiation of a rational number r = a/b to a negative integer power n is r^n = (b^m)/(a^m), where m = |n|.

Exponentiation of a rational number r = a/b to a real (floating-point) number x is the quotient (a^x)/(b^x), which is a real number.

Exponentiation of a real number x to a rational number r = a/b is x^(a/b) = root(x^a, b), where root(p, q) is the qth root of p.

Implement the following operations:

  • addition, subtraction, multiplication and division of two rational numbers,
  • absolute value, exponentiation of a given rational number to an integer power, exponentiation of a given rational number to a real (floating-point) power, exponentiation of a real number to a rational number.

Your implementation of rational numbers should always be reduced to lowest terms. For example, 4/4 should reduce to 1/1, 30/60 should reduce to 1/2, 12/8 should reduce to 3/2, etc. To reduce a rational number r = a/b, divide a and b by the greatest common divisor (gcd) of a and b. So, for example, gcd(12, 8) = 4, so r = 12/8 can be reduced to (12/4)/(8/4) = 3/2.

Assume that the programming language you are using does not have an implementation of rational numbers.

Hints

  • Operator overloading is being introduced in this exercise. The Embarcadero docwiki on the subject will be very helpful to you in understanding how overriding class operators is possible along with Implicit and Explicit casting.

Testing

In order to run the tests for this track, you will need to install DUnitX. Please see the installation instructions for more information.

Loading Exercises into Delphi

If Delphi is properly installed, and *.dpr file types have been associated with Delphi, then double clicking the supplied *.dpr file will start Delphi and load the exercise/project. control + F9 is the keyboard shortcut to compile the project or pressing F9 will compile and run the project.

Alternatively you may opt to start Delphi and load your project via. the File drop down menu.

When Questions Come Up

We monitor the Pascal-Delphi support room on gitter.im to help you with any questions that might arise.

Submitting Exercises

Note that, when trying to submit an exercise, make sure the exercise file you're submitting is in the exercism/delphi/<exerciseName> directory.

For example, if you're submitting ubob.pas for the Bob exercise, the submit command would be something like exercism submit <path_to_exercism_dir>/delphi/bob/ubob.pas.

Source

Wikipedia https://en.wikipedia.org/wiki/Rational_number

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you may request help from a mentor.

RationalNumbersTest.dpr

program RationalNumbersTest;

{$IFNDEF TESTINSIGHT}
{$APPTYPE CONSOLE}
{$ENDIF}{$STRONGLINKTYPES ON}
uses
  System.SysUtils,
  {$IFDEF TESTINSIGHT}
  TestInsight.DUnitX,
  {$ENDIF }
  DUnitX.Loggers.Console,
  DUnitX.Loggers.Xml.NUnit,
  DUnitX.TestFramework,
  uRationalNumbersTests in 'uRationalNumbersTests.pas',
  uRationalNumbers in 'uRationalNumbers.pas';

var
  runner : ITestRunner;
  results : IRunResults;
  logger : ITestLogger;
  nunitLogger : ITestLogger;
begin
{$IFDEF TESTINSIGHT}
  TestInsight.DUnitX.RunRegisteredTests;
  exit;
{$ENDIF}
  try
    //Check command line options, will exit if invalid
    TDUnitX.CheckCommandLine;
    //Create the test runner
    runner := TDUnitX.CreateRunner;
    //Tell the runner to use RTTI to find Fixtures
    runner.UseRTTI := True;
    //tell the runner how we will log things
    //Log to the console window
    logger := TDUnitXConsoleLogger.Create(true);
    runner.AddLogger(logger);
    //Generate an NUnit compatible XML File
    nunitLogger := TDUnitXXMLNUnitFileLogger.Create(TDUnitX.Options.XMLOutputFile);
    runner.AddLogger(nunitLogger);
    runner.FailsOnNoAsserts := True; //When true, Assertions must be made during tests;

    //Run tests
    results := runner.Execute;
    if not results.AllPassed then
      System.ExitCode := EXIT_ERRORS;

    {$IFNDEF CI}
    //We don't want this happening when running under CI.
    if TDUnitX.Options.ExitBehavior = TDUnitXExitBehavior.Pause then
    begin
      System.Write('Done.. press <Enter> key to quit.');
      System.Readln;
    end;
    {$ENDIF}
  except
    on E: Exception do
      System.Writeln(E.ClassName, ': ', E.Message);
  end;
end.

uRationalNumbersTests.pas

unit uRationalNumbersTests;

interface
uses
  DUnitX.TestFramework;

const
  CanonicalVersion = '1.1.0.2';

type

  [TestFixture('Addition')]
  TAdditionTests = class(TObject)
  public
    [Test]
//    [Ignore('Comment the "[Ignore]" statement to run the test')]
    procedure AddTwoPositiveRationalNumbers;

    [Test]
    [Ignore]
    procedure AddAPositiveRationalNumberAndANegativeRationalNumber;

    [Test]
    [Ignore]
    procedure AddTwoNegativeRationalNumbers;

    [Test]
    [Ignore]
    procedure AddARationalNumberToItsAdditiveInverse;
  end;

  [TestFixture('Subtraction')]
  TSubtractionTests = class(TObject)
  public
    [Test]
    [Ignore]
    procedure SubtractTwoPositiveRationalNumbers;

    [Test]
    [Ignore]
    procedure SubtractAPositiveRationalNumberAndANegativeRationalNumber;

    [Test]
    [Ignore]
    procedure SubtractTwoNegativeRationalNumbers;

    [Test]
    [Ignore]
    procedure SubtractARationalNumberFromItself;
  end;

  [TestFixture('Multiplication')]
  TMultiplicationTests = class(TObject)
  public
    [Test]
    [Ignore]
    procedure MultiplyTwoPositiveRationalNumbers;

    [Test]
    [Ignore]
    procedure MultiplyANegativeRationalNumberByAPositiveRationalNumber;

    [Test]
    [Ignore]
    procedure MultiplyTwoNegativeRationalNumbers;

    [Test]
    [Ignore]
    procedure MultiplyARationalNumberByItsReciprocal;

    [Test]
    [Ignore]
    procedure MultiplyARationalNumberByOne;

    [Test]
    [Ignore]
    procedure MultiplyARationalNumberByZero;
  end;

  [TestFixture('Division')]
  TDivisionTests = class(TObject)
  public
    [Test]
    [Ignore]
    procedure DivideTwoPositiveRationalNumbers;

    [Test]
    [Ignore]
    procedure DivideAPositiveRationalNumberByANegativeRationalNumber;

    [Test]
    [Ignore]
    procedure DivideTwoNegativeRationalNumbers;

    [Test]
    [Ignore]
    procedure DivideARationalNumberByOne;

    [Test]
    [Ignore]
    procedure DivideAWholeNumberByARationalNumber;
  end;

  [TestFixture('Absolute value')]
  TAbsoluteValueTests = class(TObject)
  public
    [Test]
    [Ignore]
    procedure AbsoluteValueOfAPositiveRationalNumber;

    [Test]
    [Ignore]
    procedure AbsoluteValueOfAPositiveRationalNumberWithNegativeNumeratorAndDenominator;

    [Test]
    [Ignore]
    procedure AbsoluteValueOfANegativeRationalNumber;

    [Test]
    [Ignore]
    procedure AbsoluteValueOfANegativeRationalNumberWithNegativeDenominator;

    [Test]
    [Ignore]
    procedure AbsoluteValueOfZero;
  end;

  [TestFixture('Exponentiation of a rational number')]
  TExpoRationalNumberTests = class(TObject)
  public
    [Test]
    [Ignore]
    procedure RaiseAPositiveRationalNumberToAPositiveIntegerPower;

    [Test]
    [Ignore]
    procedure RaiseANegativeRationalNumberToAPositiveIntegerPower;

    [Test]
    [Ignore]
    procedure RaiseZeroToAnIntegerPower;

    [Test]
    [Ignore]
    procedure RaiseOneToAnIntegerPower;

    [Test]
    [Ignore]
    procedure RaiseAPositiveRationalNumberToThePowerOfZero;

    [Test]
    [Ignore]
    procedure RaiseANegativeRationalNumberToThePowerOfZero;
  end;

  [TestFixture('Exponentiation of a real number to a rational number')]
  TExpoRealToRatNumber = class(TObject)
  public
    [Test]
    [Ignore]
    procedure RaiseARealNumberToAPositiveRationalNumber;

    [Test]
    [Ignore]
    procedure RaiseARealNumberToANegativeRationalNumber;

    [Test]
    [Ignore]
    procedure RaiseARealNumberToAZeroRationalNumber;
  end;

  [TestFixture('Reduction to lowest terms')]
  TReduceTests = class(TObject)
  public
    [Test]
    [Ignore]
    procedure ReduceAPositiveRationalNumberToLowestTerms;

    [Test]
    [Ignore]
    procedure ReduceANegativeRationalNumberToLowestTerms;

    [Test]
    [Ignore]
    procedure ReduceARationalNumberWithANegativeDenominatorToLowestTerms;

    [Test]
    [Ignore]
    procedure ReduceZeroToLowestTerms;

    [Test]
    [Ignore]
    procedure ReduceAnIntegerToLowestTerms;

    [Test]
    [Ignore]
    procedure ReduceOneToLowestTerms;
  end;

implementation
uses
  System.Math, uRationalNumbers;


{$region 'TAdditionTests'}

procedure TAdditionTests.AddAPositiveRationalNumberAndANegativeRationalNumber;
var
  LPositiveRationalValue: TFraction;
  LNegativeRationalValue: TFraction;
  Expected: string;
  Actual: TFraction;
begin
  Expected := '-1/6';
  LPositiveRationalValue := TFraction.CreateFrom(1, 2);
  LNegativeRationalValue := TFraction.CreateFrom(2, 3);
  Actual := LPositiveRationalValue + -LNegativeRationalValue;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TAdditionTests.AddARationalNumberToItsAdditiveInverse;
var
  LRationalNumber: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '0/1';
  LRationalNumber := TFraction.CreateFrom(1, 2);
  Actual := LRationalNumber + -LRationalNumber;
  Assert.AreEqual(Expected, string(actual));
end;

procedure TAdditionTests.AddTwoNegativeRationalNumbers;
var
  lNegFracA: TFraction;
  lNegFracB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '-7/6';
  LNegFracA := TFraction.CreateFrom(-1, 2);
  LNegFracB := TFraction.CreateFrom(-2 ,3);
  Actual := LNegFracA + LNegFracB;
  Assert.AreEqual(Expected, string(actual));
end;

procedure TAdditionTests.AddTwoPositiveRationalNumbers;
var
  lPosFracA: TFraction;
  lPosFracB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '7/6';
  LPosFracA := TFraction.CreateFrom(1, 2);
  LPosFracB := TFraction.CreateFrom(2 ,3);
  Actual := LPosFracA + LPosFracB;
  Assert.AreEqual(Expected, string(actual));
end;
{$endregion}

{$region 'TSubtractionTests'}

procedure TSubtractionTests.SubtractAPositiveRationalNumberAndANegativeRationalNumber;
var
  LPosRatNum: TFraction;
  LNegRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '7/6';
  LPosRatNum := TFraction.CreateFrom(1, 2);
  LNegRatNum := TFraction.CreateFrom(-2, 3);
  Actual := LPosRatNum - LNegRatNum;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TSubtractionTests.SubtractARationalNumberFromItself;
var
  LRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '0/1';
  LRatNum := TFraction.CreateFrom(1, 2);
  Actual := LRatNum - LRatNum;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TSubtractionTests.SubtractTwoNegativeRationalNumbers;
var
  LNegRatNumA: TFraction;
  LNegRatNumB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/6';
  LNegRatNumA := TFraction.CreateFrom(-1, 2);
  LNegRatNumB := TFraction.CreateFrom(-2, 3);
  Actual := LNegRatNumA - LNegRatNumB;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TSubtractionTests.SubtractTwoPositiveRationalNumbers;
var
  LPosRatNumA: TFraction;
  LPosRatNumB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '-1/6';
  LPosRatNumA := TFraction.CreateFrom(1, 2);
  LPosRatNumB := TFraction.CreateFrom(2, 3);
  Actual := LPosRatNumA - LPosRatNumB;
  Assert.AreEqual(Expected, string(Actual));
end;
{$endregion}

{$region 'TMultiplicationTests'}

procedure TMultiplicationTests.MultiplyANegativeRationalNumberByAPositiveRationalNumber;
var
  LNegRatA: TFraction;
  LPosRatB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '-1/3';
  LNegRatA := TFraction.CreateFrom(-1, 2);
  LPosRatB := TFraction.CreateFrom(2, 3);
  Actual := LNegRatA * LPosRatB;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TMultiplicationTests.MultiplyARationalNumberByItsReciprocal;
var
  LRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/1';
  LRatNum := TFraction.CreateFrom(1, 2);
  Actual := LRatNum * (1 / LRatNum);
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TMultiplicationTests.MultiplyARationalNumberByOne;
var
  LRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/2';
  LRatNum := TFraction.CreateFrom(1, 2);
  Actual := LRatNum * 1;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TMultiplicationTests.MultiplyARationalNumberByZero;
var
  LRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '0/1';
  LRatNum := TFraction.CreateFrom(1, 2);
  Actual := LRatNum * 0;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TMultiplicationTests.MultiplyTwoNegativeRationalNumbers;
var
  LNegRatA: TFraction;
  LNegRatB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/3';
  LNegRatA := TFraction.CreateFrom(-1, 2);
  LNegRatB := TFraction.CreateFrom(-2, 3);
  Actual := LNegRatA * LNegRatB;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TMultiplicationTests.MultiplyTwoPositiveRationalNumbers;
var
  LPosRatA: TFraction;
  LPosRatB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/3';
  LPosRatA := TFraction.CreateFrom(1, 2);
  LPosRatB := TFraction.CreateFrom(2, 3);
  Actual := LPosRatA * LPosRatB;
  Assert.AreEqual(Expected, string(Actual));
end;
{$endregion}

{$region 'TDivisionTests'}

procedure TDivisionTests.DivideAPositiveRationalNumberByANegativeRationalNumber;
var
  LPosRatA: TFraction;
  LNegRatB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '-3/4';
  LPosRatA := TFraction.CreateFrom(1, 2);
  LNegRatB := TFraction.CreateFrom(-2, 3);
  Actual := LPosRatA / LNegRatB;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TDivisionTests.DivideARationalNumberByOne;
var
  LRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/2';
  LRatNum := TFraction.CreateFrom(1, 2);
  Actual := LRatNum / 1;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TDivisionTests.DivideAWholeNumberByARationalNumber;
var
  LRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '14/1';
  LRatNum := TFraction.CreateFrom(2, 7);
  Actual := 4 / LRatNum;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TDivisionTests.DivideTwoNegativeRationalNumbers;
var
  LNegRatA: TFraction;
  LNegRatB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '3/4';
  LNegRatA := TFraction.CreateFrom(-1, 2);
  LNegRatB := TFraction.CreateFrom(-2, 3);
  Actual := LNegRatA / LNegRatB;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TDivisionTests.DivideTwoPositiveRationalNumbers;
var
  LPosRatA: TFraction;
  LPosRatB: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '3/4';
  LPosRatA := TFraction.CreateFrom(1, 2);
  LPosRatB := TFraction.CreateFrom(2, 3);
  Actual := LPosRatA / LPosRatB;
  Assert.AreEqual(Expected, string(Actual));
end;
{$endregion}

{$region 'TAbsoluteValueTests'}

procedure TAbsoluteValueTests.AbsoluteValueOfANegativeRationalNumber;
var
  LNegRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/2';
  LNegRatNum := TFraction.CreateFrom(-1, 2);
  Actual := TFraction(Abs(LNegRatNum));
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TAbsoluteValueTests.AbsoluteValueOfANegativeRationalNumberWithNegativeDenominator;
var
  LNegRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/2';
  LNegRatNum := TFraction.CreateFrom(1, -2);
  Actual := TFraction(Abs(LNegRatNum));
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TAbsoluteValueTests.AbsoluteValueOfAPositiveRationalNumber;
var
  LPosRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/2';
  LPosRatNum := TFraction.CreateFrom(1, 2);
  Actual := TFraction(Abs(LPosRatNum));
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TAbsoluteValueTests.AbsoluteValueOfAPositiveRationalNumberWithNegativeNumeratorAndDenominator;
var
  LNegRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/2';
  LNegRatNum := TFraction.CreateFrom(-1, -2);
  Actual := TFraction(Abs(LNegRatNum));
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TAbsoluteValueTests.AbsoluteValueOfZero;
var
  LZero: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '0/1';
  LZero := TFraction.CreateFrom(0, 1);
  Actual := TFraction(Abs(LZero));
  Assert.AreEqual(Expected, string(Actual));
end;
{$endregion}

{$region 'TExpoRationalNumberTests'}

procedure TExpoRationalNumberTests.RaiseANegativeRationalNumberToAPositiveIntegerPower;
var
  NegRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '-1/8';
  NegRatNum := TFraction.CreateFrom(-1, 2);
  Actual := TFraction(System.Math.Power(NegRatNum,3));
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TExpoRationalNumberTests.RaiseANegativeRationalNumberToThePowerOfZero;
var
  NegRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/1';
  NegRatNum := TFraction.CreateFrom(-1, 2);
  Actual := TFraction(System.Math.Power(NegRatNum,0));
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TExpoRationalNumberTests.RaiseAPositiveRationalNumberToAPositiveIntegerPower;
var
  PosRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/8';
  PosRatNum := TFraction.CreateFrom(1, 2);
  Actual := TFraction(System.Math.Power(PosRatNum, 3));
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TExpoRationalNumberTests.RaiseAPositiveRationalNumberToThePowerOfZero;
var
  PosRatNum: TFraction;
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/1';
  PosRatNum := TFraction.CreateFrom(1, 2);
  Actual := TFraction(System.Math.Power(PosRatNum, 0));
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TExpoRationalNumberTests.RaiseOneToAnIntegerPower;
var
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/1';
  Actual := TFraction(System.Math.Power(1, 4));
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TExpoRationalNumberTests.RaiseZeroToAnIntegerPower;
var
  Actual: TFraction;
  Expected: string;
begin
  Expected := '0/1';
  Actual := TFraction(System.Math.Power(0, 5));
  Assert.AreEqual(Expected, string(Actual));
end;
{$endregion}

{$region 'TExpoRealToRatNumber'}

procedure TExpoRealToRatNumber.RaiseARealNumberToANegativeRationalNumber;
var
  NegRatNum: TFraction;
  Actual: Double;
  Expected: Double;
begin
  Expected := 1 / 3;
  NegRatNum := TFraction.CreateFrom(-1, 2);
  Actual := System.Math.Power(9, NegRatNum);
  Assert.AreEqual(Expected, Actual);
end;

procedure TExpoRealToRatNumber.RaiseARealNumberToAPositiveRationalNumber;
var
  PosRatNum: TFraction;
  Actual: Double;
  Expected: Double;
begin
  Expected := 16.0;
  PosRatNum := TFraction.CreateFrom(4, 3);
  Actual := System.Math.Power(8, PosRatNum);
  Assert.AreEqual(Expected, Actual);
end;

procedure TExpoRealToRatNumber.RaiseARealNumberToAZeroRationalNumber;
var
  ZeroRatNum: TFraction;
  Actual: Double;
  Expected: Double;
begin
  Expected := 1.0;
  ZeroRatNum := TFraction.CreateFrom(0, 1);
  Actual := System.Math.Power(2, ZeroRatNum);
  Assert.AreEqual(Expected, Actual);
end;
{$endregion}

{$region 'TReduceTests'}

procedure TReduceTests.ReduceANegativeRationalNumberToLowestTerms;
var
  Actual: TFraction;
  Expected: string;
begin
  Expected := '-2/3';
  Actual := TFraction.CreateFrom(-4, 6).Reduced;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TReduceTests.ReduceAnIntegerToLowestTerms;
var
  Actual: TFraction;
  Expected: string;
begin
  Expected := '-2/1';
  Actual := TFraction.CreateFrom(-14, 7).Reduced;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TReduceTests.ReduceAPositiveRationalNumberToLowestTerms;
var
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/2';
  Actual := TFraction.CreateFrom(2, 4).Reduced;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TReduceTests.ReduceARationalNumberWithANegativeDenominatorToLowestTerms;
var
  Actual: TFraction;
  Expected: string;
begin
  Expected := '-1/3';
  Actual := TFraction.CreateFrom(3, -9).Reduced;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TReduceTests.ReduceOneToLowestTerms;
var
  Actual: TFraction;
  Expected: string;
begin
  Expected := '1/1';
  Actual := TFraction.CreateFrom(13, 13).Reduced;
  Assert.AreEqual(Expected, string(Actual));
end;

procedure TReduceTests.ReduceZeroToLowestTerms;
var
  Actual: TFraction;
  Expected: string;
begin
  Expected := '0/1';
  Actual := TFraction.CreateFrom(0, 6).Reduced;
  Assert.AreEqual(Expected, string(Actual));
end;
{$endregion}

initialization
  TDUnitX.RegisterTestFixture(TAdditionTests);
  TDUnitX.RegisterTestFixture(TSubtractionTests);
  TDUnitX.RegisterTestFixture(TMultiplicationTests);
  TDUnitX.RegisterTestFixture(TDivisionTests);
  TDUnitX.RegisterTestFixture(TAbsoluteValueTests);
  TDUnitX.RegisterTestFixture(TExpoRationalNumberTests);
  TDUnitX.RegisterTestFixture(TExpoRealToRatNumber);
  TDUnitX.RegisterTestFixture(TReduceTests);
end.
unit uRationalNumbers;

interface
uses
  System.SysUtils;

type
  TFraction = record
  strict private
    Numerator: Integer;
    Denominator: Integer;

  public
    class function CreateFrom(const aNumerator: Integer; const aDenominator: Integer): TFraction; static;
    function Reduced(): TFraction;
    class operator Add(aFirstFraction, aSecondFraction: TFraction): TFraction;
    class operator Subtract(aFirstFraction, aSecondFraction: TFraction): TFraction;
    class operator Multiply(aFirstFraction, aSecondFraction: TFraction): TFraction;
    class operator Divide(aFirstFraction, aSecondFraction: TFraction): TFraction;
    class operator Negative(const aFraction: TFraction): TFraction;
    class operator Explicit(const aFraction: TFraction): string;
    class operator Explicit(const aNumber: Double): TFraction;
    class operator Implicit(const aNumber: Integer): TFraction;
    class operator Implicit(const aFraction: TFraction): Double;
  end;

  function GCD(aFirstNumber, aSecondNumber: Integer): Integer;

implementation

//Greatest common Divider using Euclids algorithm
Function GCD(aFirstNumber, aSecondNumber: Integer): Integer;
var
  lFirstNumber: Integer;
  lSecondNumber: Integer;
begin
  lFirstNumber := Abs(aFirstNumber);
  lSecondNumber := Abs(aSecondNumber);
  while lFirstNumber > 0 do
  begin
    if lFirstNumber < lSecondNumber then
    begin
      lFirstNumber := lFirstNumber + lSecondNumber;
      lSecondNumber := lFirstNumber - lSecondNumber;
      lFirstNumber := lFirstNumber - lSecondNumber;
    end;

    lFirstNumber := lFirstNumber mod lSecondNumber;
  end;

  Result := lSecondNumber;
end;

{ TFraction }
class function TFraction.Reduced: TFraction;
var
  lGCD: Integer;
begin
  if Numerator <> 0 then
  begin
    lGCD := GCD(Numerator, Denominator);
    Result.Numerator := Numerator div lGCD;
    Result.Denominator := Denominator div lGCD;
  end
  else
  begin
    Result.Numerator := 0;
    Result.Denominator := 1;//Reduce 0/x to 0/1
  end;

  if(Result.Denominator < 0) then
  begin
    Result.Numerator := Result.Numerator * - 1;
    Result.Denominator := Result.Denominator * -1;
  end;
end;

class function TFraction.CreateFrom(const aNumerator: Integer; const aDenominator: Integer): TFraction;
begin
  Result.Numerator := aNumerator;
  Result.Denominator := aDenominator;
end;

class operator TFraction.Add(aFirstFraction, aSecondFraction: TFraction): TFraction;
begin
 Result.Numerator := (aFirstFraction.Numerator * aSecondFraction.Denominator) + (aSecondFraction.Numerator * aFirstFraction.Denominator);
 Result.Denominator := aFirstFraction.Denominator * aSecondFraction.Denominator;
 Result := Result.Reduced;
end;

class operator TFraction.Subtract(aFirstFraction, aSecondFraction: TFraction): TFraction;
begin
  Result.Numerator := (aFirstFraction.Numerator * aSecondFraction.Denominator) - (aSecondFraction.Numerator * aFirstFraction.Denominator);
  Result.Denominator := aFirstFraction.Denominator * aSecondFraction.Denominator;
  Result := Result.Reduced;
end;

class operator TFraction.Multiply(aFirstFraction, aSecondFraction: TFraction): TFraction;
begin
  Result.Numerator := aFirstFraction.Numerator * aSecondFraction.Numerator;
  Result.Denominator := aFirstFraction.Denominator * aSecondFraction.Denominator;
  Result := Result.Reduced;
end;

class operator TFraction.Divide(aFirstFraction, aSecondFraction: TFraction): TFraction;
begin
  Result.Numerator := aFirstFraction.Numerator * aSecondFraction.Denominator;
  Result.Denominator := aFirstFraction.Denominator * aSecondFraction.Numerator;
  Result := Result.Reduced;
end;

class operator TFraction.Negative(const aFraction: Tfraction): TFraction;
begin
  Result := TFraction.CreateFrom((aFraction.Numerator * -1) , aFraction.Denominator);
  Result := Result.Reduced;
end;

class operator TFraction.Explicit(const aFraction: TFraction): string;
begin
  Result := (aFraction.Numerator.ToString + '/' + aFraction.Denominator.ToString);
end;

class operator TFraction.Implicit(const aNumber: Integer): TFraction;
begin
  Result.Numerator := aNumber;
  Result.Denominator := 1;
end;

class operator TFraction.Implicit(const aFraction: TFraction): Double;
var
  temp: TFraction;
begin
  temp := aFraction.Reduced;
  Result := temp.Numerator / temp.Denominator;
end;

class operator TFraction.Explicit(const aNumber: Double): TFraction;
const
  LargeNumberForAccuracy: Integer = 1000000;
begin
  Result.Numerator := Trunc(aNumber * LargeNumberForAccuracy);
  Result.Denominator := LargeNumberForAccuracy;
  Result := Result.Reduced;
end;

end.

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?