3
$\begingroup$

I am new to Wolfram language (Mathematica) programming, I have below problems.

To summarise the problem : The input is a positive integer, and the output is a recursive list of the lengths of the Roman numerals of input x. Stop the list when the list starts to repeat.

For example : StringLength[RomanNumeral[#]] &@123 gives 6; StringLength[RomanNumeral[#]] &@6 gives 2 (Stop here, because the function starts to repeat afterwards 2); StringLength[RomanNumeral[#]] &@2 gives 2. So, the correct output for x=123 should be a list {123, 6, 2}

 romanListLength[x_Integer?Positive] := 
 NestWhileList[StringLength[RomanNumeral[#]] &, x, DuplicateFreeQ]

and I tested for 123, and get error message: enter image description here

I appreciate if anyone can help

$\endgroup$
1
  • $\begingroup$ Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. $\endgroup$ – bbgodfrey Jun 7 at 4:30
1
$\begingroup$

Perhaps FixedPointListsatisfies your need. Can you try the following?

romanListLength[x_Integer?Positive] := FixedPointList[StringLength[RomanNumeral[#]] &, x]
$\endgroup$
1
  • $\begingroup$ romanListLength2[x_Integer?Positive] := Most@FixedPointList[StringLength[RomanNumeral[#]] &, x], added 'Most' as bbgodfrey suggested, then the duplicate element is removed. Thanks $\endgroup$ – Normal Student Jun 7 at 5:50
6
$\begingroup$

DuplicateFreeQ in the code is applied to the each value computed by NestWhileList, not to the cumulative List of values computed. To achieve the goal of the question, compare the current value computed with preceding ones.

romanListLength[x_Integer?Positive] := 
    Most@NestWhileList[StringLength[RomanNumeral[#]] &, x, UnsameQ, All]

Then,

romanListLength[123]
(* {123, 6, 2} *)

as desired. (Most discards the last value, which always is a duplicate.) Here are some more values.

Table[romanListLength[n], {n, 25}]
(* {{1}, {2}, {3}, {4, 2}, {5, 1}, {6, 2}, {7, 3}, {8, 4, 2}, {9, 2}, 
    {10, 1}, {11, 2}, {12, 3}, {13, 4, 2}, {14, 3}, {15, 2}, {16, 3}, 
    {17, 4, 2}, {18, 5, 1}, {19, 3}, {20, 2}, {21, 3}, {22, 4, 2}, 
    {23, 5, 1}, {24, 4, 2}, {25, 3}} *)
$\endgroup$
1
  • $\begingroup$ Thank you. The code works. $\endgroup$ – Normal Student Jun 7 at 5:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.