Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs

Dashboard
Notifications
Mark all as read
Challenges

Decode periodic decimal fractions

+4
−0

Rational numbers in decimal representation can have an infinite periodic part. One common way to write this down is to repeat the periodic digits and then add three dots. Numbers without those three dots are taken to be non-periodic (or equivalently, have a periodic 0 after the given digits). Your task is to decode this representation into a fully cancelled fraction.

In particular, the numbers to decode are given as follows:

  • There is an optional sign (+ or -). If omitted, + is assumed.

  • There is an integral part. If empty, it is taken to be 0.

  • There is a decimal point, which is optional if the number is an integer and the integral part was not omitted.

  • There is an fractional part following the integer.

  • If the fractional part has at least one digit, it may be followed by three dots.

The program shall take a string as input, and give a fully cancelled fraction (as pair numerator/denominator) as result. It may assume that the given string conforms to the number format.

The string has to be interpreted as follows:

  • If the string does not end in three dots, it is interpreted as exact number.

  • If the string does end in three dots, find the longest repeating digit sequence in the fractional part preceding the three dots. If no such repeating sequence is found, the period consists of just the last digit. Otherwise it consists of that longest repeating digit sequence.

  • Output the fraction that corresponds to the determined periodic digit sequence. The denominator shall be positive. The fraction shall be completely cancelled.

  • Your code must handle at least up to 6 digits before and up to 6 digits after the decimal point.

This is code-golf, that is the shortest code wins.

Test cases:

                "0" -> 0/1
               "-0" -> 0/1
             "+0.0" -> 0/1
               "42" -> 42/1
               "+2" -> 2/1
               "-6" -> -6/1
             "-2.0" -> -2/1
             "0815" -> 815/1
                "." -> 0/1
               "+." -> 0/1
               "-." -> 0/1
               ".0" -> 0/1
            "+00.0" -> 0/1
              "-.2" -> -1/5
             "3.14" -> 157/50
            ".3..." -> 1/3
          "+.11..." -> 1/9
           "1.0..." -> 1/1
           "2.9..." -> 3/1
         "0.121..." -> 109/900
        "0.1212..." -> 4/33
       "0.12121..." -> 4/33
       "0.12122..." -> 1091/9000
       ".122122..." -> 122/999
       ".022122..." -> 1991/90000
      ".0221221..." -> 221/9990
"-123456.123434..." -> -611107811/4950
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

Scoring criterion (2 comments)

2 answers

+2
−0

Haskell, 352 bytes

f a=let{(d,e)=y$filter(>'-')a;f=drop 1e;g=0!h;h=fst n;i=scanr(:)[]h;(j,k)=elem '.'f%(1!head(filter(\a->a>[]&&elem(a++a)i)i++[[last$'0':h]]));(l,m)=(read('0':d)::Integer,1)#g#(j,k*snd g);n=y f}in(last$l:[-l|elem '-'a],m)
y=break(<'0')
a!b=(b>[])%(read b,10^length b-a)
(a,b)#(c,d)=let{e=a*d+b*c;f=b*d;g=(`div`gcd e f)}in(e>0)%(g e,g f)
a%b|a=b|0<1=(0,1)

Explanation: We first parse the sign, integral part, fractional part and the repeating decimals as four separate rational numbers, then combine them using rational addition and multiplication. Addition implicitly cancels the fraction.

Try it online!

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

+2
−0

JavaScript (Node.js), 242 234 bytes

s=>([l,p,i,j,_,r]=/(-)?\+?(\d*)\.?(\d*?)(((\d+)\6|\d)\.|$)/.exec(s),[i,r]=c(c([i|0,1],[j|0,10**(l=j.length)]),[r=r||'0',10**l*(10**r.length-1)]),[(p?-i:i)/(j=d(i,r)),r/j])
c=(a,b)=>[a[0]*b[1]+b[0]*a[1],a[1]*b[1]]
d=(a,b)=>b?d(b,a%b):a

Try it online!

Regexes are love, regexes are life.

Explanation

The meat of it is this regex here:

/(-)?\+?(\d*)\.?(\d*?)(((\d+)\6|\d)\.|$)/

In order:

  1. /(-)?\+? Captures the optional negative or positive sign (we don't actually care about the positive sign, so it is outside the group.

  2. (\d*) Capture the integer part, if any

  3. \.? Optional period

  4. (\d*?) Captures the non-repeating decimal part

  5. (((\d+)\6|\d)\.|$) The complicated one. Captures either:

    • (\d+)\6 A repeating part of the decimal followed by a period \.
    • \d The last digit followed by a period \.
    • Nothing, we've reached the end of the string ($) and there is no period, meaning there is no repeating part

Once that's done it's a relatively simple formula to get the fraction. We just add together the integer part, the decimal part, and the fractional part as fractions, for which we have a helper method c which takes two fractions and outputs their sum as a (non-reduced) fraction.

$$ \frac{i}{1}+\frac{j}{10^{\text{#digits of }j}}+\frac{r}{10^{\text{#digits of }j}\cdot(10^{\text{#digits of }r}-1)} $$

Finally, we have a helper method d which computes the greatest common divisor using Euclid's method. We divide by this to reduce the fraction, and at the same time multiply the numerator by whatever the sign was to get the final answer.

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »

This community is part of the Codidact network. We have other communities too — take a look!

You can also join us in chat!

Want to advertise this community? Use our templates!