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

makafakachka's solution

to Rational Numbers in the Delphi Pascal Track

Published at May 02 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

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 receive assistance 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,
  uRationalNumbersTest in 'uRationalNumbersTest.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.

uRationalNumbersTest.pas

unit uRationalNumbersTest;

interface
uses
  DUnitX.TestFramework;

const
  CanonicalVersion = '1.1.0.1';

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

type
  TFraction = record
    private
      FNumerator, FDenominator: Integer;
    public
      constructor CreateFrom(numerator, denominator: Integer);
      function Inverse: TFraction;
      function Reduced: TFraction;
      {operations}
      class operator Add(A, B: TFraction): TFraction;
      class operator Subtract(A, B: TFraction): TFraction;
      class operator Multiply(A, B: TFraction): TFraction;
      class operator Multiply(Fraction: TFraction; Number: Integer): TFraction;
      class operator Divide(A, B: TFraction): TFraction;
      class operator Divide(Number: Integer; Fraction: TFraction): TFraction;
      class operator Divide(Fraction: TFraction; Number: Integer): TFraction;
      {implicit}
      class operator Implicit(Fraction: TFraction): String;
      class operator Implicit(Value: Double): TFraction;
      class operator Implicit(Fraction: TFraction): Double;
      {negative value}
      class operator Negative(Fraction: TFraction): TFraction;
  end;

  function ABS(Fraction: TFraction): Double;

implementation

uses
  System.Math,
  System.Sysutils;

function ABS(Fraction: TFraction): Double;
begin
  Result := System.Abs(Double(Fraction));
end;


                            { TFraction }

{Constructor}
constructor TFraction.CreateFrom(numerator, denominator: Integer);

  function GCD(a, b: Integer): Integer;
  begin
    a := System.Abs(a);
    b := System.Abs(b);

    if a mod b = 0 then exit(b);
    if b mod a = 0 then exit(a);

    while (a <> b) do
      if a > b then
        a := a - b
      else
        b := b - a;

    Result := a;
  end;

begin
  var divisor := GCD(numerator, denominator);
  var denSign := Sign(denominator);
  FNumerator := (numerator * denSign) div divisor;
  FDenominator := (denominator * denSign) div divisor;
end;


{"+" and "-"}
class operator TFraction.Add(A, B: TFraction): TFraction;
begin
  var num := A.FNumerator * B.FDenominator + B.FNumerator * A.FDenominator;
  var denum := A.FDenominator * B.FDenominator;
  Result := TFraction.CreateFrom(num, denum);
end;

class operator TFraction.Negative(Fraction: TFraction): TFraction;
begin
  Result := TFraction.CreateFrom(-Fraction.FNumerator, Fraction.FDenominator);
end;

class operator TFraction.Subtract(A, B: TFraction): TFraction;
begin
  Result := A + (-B);
end;


{"*"}
class operator TFraction.Multiply(Fraction: TFraction;
  Number: Integer): TFraction;
begin
  Result := TFraction.CreateFrom(
    Fraction.FNumerator * Number, Fraction.FDenominator);
end;

class operator TFraction.Multiply(A, B: TFraction): TFraction;
begin
  Result := TFraction.CreateFrom(
    A.FNumerator * B.FNumerator, A.FDenominator * B.FDenominator);
end;

{useful inverse func, "A^(-1)"}
function TFraction.Inverse: TFraction;
begin
  Result := TFraction.CreateFrom(FDenominator, FNumerator);
end;

{"/"}
class operator TFraction.Divide(Number: Integer;
  Fraction: TFraction): TFraction;
begin
  Result := TFraction.CreateFrom(Number, 1) / Fraction;
end;

class operator TFraction.Divide(A, B: TFraction): TFraction;
begin
  Result := A * B.Inverse;
end;

class operator TFraction.Divide(Fraction: TFraction;
  Number: Integer): TFraction;
begin
  Result := Fraction * TFraction.CreateFrom(1, Number);
end;

{implicit operators}
class operator TFraction.Implicit(Fraction: TFraction): String;
begin
  Result := Fraction.FNumerator.ToString +
    '/' + Fraction.FDenominator.ToString;
end;

class operator TFraction.Implicit(Value: Double): TFraction;
const
  AccuracyVal = 100000; // five digits
begin
{frac_part*100000/100000 + trunc_part/1}
  Result :=
    TFraction.CreateFrom(Trunc(Frac(Value) * AccuracyVal), AccuracyVal) +
    TFraction.CreateFrom(Trunc(Value), 1);
end;

class operator TFraction.Implicit(Fraction: TFraction): Double;
begin
  Result := Fraction.FNumerator / Fraction.FDenominator;
end;

{Reduced}
function TFraction.Reduced: TFraction;
begin
  Result := Self;
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?