Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of amoradell

amoradell's solution

to Collatz Conjecture in the Delphi Pascal Track

Published at Jul 13 2018 · 1 comment
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

The Collatz Conjecture or 3x+1 problem can be summarized as follows:

Take any positive integer n. If n is even, divide n by 2 to get n / 2. If n is odd, multiply n by 3 and add 1 to get 3n + 1. Repeat the process indefinitely. The conjecture states that no matter which number you start with, you will always reach 1 eventually.

Given a number n, return the number of steps required to reach 1.

Examples

Starting with n = 12, the steps would be as follows:

  1. 12
  2. 6
  3. 3
  4. 10
  5. 5
  6. 16
  7. 8
  8. 4
  9. 2
  10. 1

Resulting in 9 steps. So for input n = 12, the return value would be 9.

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

An unsolved problem in mathematics named after mathematician Lothar Collatz https://en.wikipedia.org/wiki/3x_%2B_1_problem

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

uCollatzconjectureTest.pas

unit uCollatzconjectureTest;

interface
uses
  DUnitX.TestFramework;

const
  CanonicalVersion = '1.2.0';

type
  [TestFixture]
  CollatzconjectureTest = class(TObject)
  public
    [Testcase('Zero steps for one', '1, 0')]
//    [Ignore('Comment the "[Ignore]" statement to run the test')]
    procedure Zero_steps_for_one(const aNumber: integer; const aExpected: integer);

    [Testcase('Divide if even','16, 4')]
    [Ignore]
    procedure Divide_if_even(const aNumber: integer; const aExpected: integer);

    [Testcase('Even and odd steps','12, 9')]
    [Ignore]
    procedure Even_and_odd_steps(const aNumber: integer; const aExpected: integer);

    [Testcase('Large number of even and odd steps', '1000000, 152')]
    [Ignore]
    procedure Large_number_of_even_and_odd_steps(const aNumber: integer; const aExpected: integer);

    [Testcase('Zero is an error', '0,error: Only positive numbers are allowed')]
    [Ignore]
    procedure Zero_is_an_error(const aNumber: integer; const aExpected: string);

    [Testcase('Negative value is an error', '-15,error: Only positive numbers are allowed')]
    [Ignore]
    procedure Negative_value_is_an_error(const aNumber: integer; const aExpected: string);
  end;

implementation
uses uCollatzconjecture;

procedure CollatzconjectureTest.Zero_steps_for_one(const aNumber: integer; const aExpected: integer);
begin
  Assert.AreEqual(aExpected, collatzSteps(aNumber));
end;

procedure CollatzconjectureTest.Divide_if_even(const aNumber: integer; const aExpected: integer);
begin
  Assert.AreEqual(aExpected, collatzSteps(aNumber));
end;

procedure CollatzconjectureTest.Even_and_odd_steps(const aNumber: integer; const aExpected: integer);
begin
  Assert.AreEqual(aExpected, collatzSteps(aNumber));
end;

procedure CollatzconjectureTest.Large_number_of_even_and_odd_steps(const aNumber: integer; const aExpected: integer);
begin
  Assert.AreEqual(aExpected, collatzSteps(aNumber));
end;

procedure CollatzconjectureTest.Zero_is_an_error(const aNumber: integer; const aExpected: string);
var MyProc: TTestLocalMethod;
begin
  MyProc := procedure
            begin
              collatzSteps(aNumber);
            end;

  Assert.WillRaiseWithMessage(MyProc, EIllegalNumber, aExpected);
end;

procedure CollatzconjectureTest.Negative_value_is_an_error(const aNumber: integer; const aExpected: string);
var MyProc: TTestLocalMethod;
begin
  MyProc := procedure
            begin
              collatzSteps(aNumber);
            end;

  Assert.WillRaiseWithMessage(MyProc, EIllegalNumber, aExpected);
end;

initialization
  TDUnitX.RegisterTestFixture(CollatzconjectureTest);
end.
unit uCollatzconjecture;

interface

uses System.Sysutils;

type
  EIllegalNumber = Exception;

function collatzSteps(const aNumber: integer): integer;

implementation



function collatzSteps(const aNumber: integer): integer;
var limit: UInt64;

  function convergingToOne(aLimit: UInt64): UInt64;
  begin
    if Odd(aLimit) then
      result := aLimit * 3 + 1
    else
      result := aLimit div 2 ;
  end;

begin
  // edge case 1
  if (aNumber < 1) then
    raise EIllegalNumber.Create('error: Only positive numbers are allowed');
  // normal case
  result := 0;
  limit := aNumber;
  while ((limit > 1) or (result > 999)) do
  begin
    limit := convergingToOne(limit);
    Inc(result);
  end;
end;

end.

Community comments

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

@amoradell that is exactly what I am talking about. I like your function name, it helps me understand how it is driving the loop. Doesn't really tell me what the function is actually doing. I guess I am on the fence about what is more important here? What does the function do for the loop or what is the function doing? If you were to consider the ladder then computeCollatzNumber would be another way to go for naming the function. Thanks for the good work! Keep it up.

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?