Friday, August 30, 2013

Problem 33 - Bash, for a change of pace

Recently, most of my solutions have been either in very nice or very esoteric languages. For this problem, I decided to use bash: certainly a very real language, just not exactly one that is normally used for the likes of Project Euler. Anyway, this problem went fairly well, even though I had to do something fairly silly to account for all variables storing integers (I only operation I perform once I have the value of a fraction is comparison...so I just multiply all fractions by 1000 to store them as integers) - and I was a bit of a wimp on the last step (finding the denominator of a simplified fraction in a way that only works when the numerator of the simplified fraction is 1, instead of a more generalized method) - but nonetheless, everything worked out well, and another language is crossed off my list of options. Notably, using bash reminded me that I still haven't used assembly language...
#!/bin/bash

RETURN=0
function div {
    let RETURN=$[1000*$1/$2 | bc -l]
}

ORIGINAL=0
NUMERATOR=1
DENOMINATOR=1
for i in `seq 10 99`;
do
    for j in `seq $[$i+1] 99`
    do
        div $i $j
        let ORIGINAL=$RETURN
        if [ $[j / 10] -eq $[$i % 10] ]; then
            if [ $[$j % 10] -gt 0 ]; then
                div $[$i / 10] $[$j % 10]
                if [ $ORIGINAL -eq $RETURN ]; then
                    let NUMERATOR*=$i
                    let DENOMINATOR*=$j
                fi
            fi
        fi
    done
done

#This is obviously not generally how one finds the denominator
#of a lowest-terms fraction...but it is in this case, as the
#numerator is a factor of the denominator
echo $[$DENOMINATOR / $NUMERATOR]

No comments:

Post a Comment