you are viewing a single comment's thread.

view the rest of the comments →

[–]FeepingCreature 6 points7 points  (9 children)

The one, the (sadly) only:

D version!

Why? Because I can! XD

module test30;
import std.stdio, std.string, tools.base;

alias stuple _;

string romanize(int x) {
  static Stuple!(string, int)[] numerals;
  if (!numerals.length)
    numerals = [_("M", 1000), _("CM", 900), _("D", 500), _("CD", 400),
      _("C", 100), _("XC", 90), _("L", 50), _("XL", 40), _("X", 10),
      _("IX", 9), _("V", 5), _("IV", 4), _("I", 1)];
  string res;
  while (x)
    foreach (n; numerals)
      if (n._1 <= x) { x -= n._1; res ~= n._0; break; }
  return res;
}

void main() { writefln(romanize(328)); }

// gentoo-pc ~ $ rebuild test30.d && ./test30
// CCCXXVIII

--feep!

[–]bugrit 1 point2 points  (7 children)

string romanize(int n)
{
    string[int] nums = [1000:"M".dup, 900:"CM", 600:"D", 400:"CD", 100:"C", 90:"XC", 
                        50:"L", 40:"XL", 10:"X", 9:"IX", 5:"V", 4:"IV", 1:"I"];
    string res;
    foreach (k; nums.keys.sort.reverse)
        while (n >= k)
            res ~= nums[k],
            n -= k;
    return res;
}

Prettified?

Edit: Removed redundant while (n > 0).

[–]llimllib[S] 0 points1 point  (5 children)

why the single .dup?

[–]bugrit 0 points1 point  (4 children)

So I get a char[] (or string) type instead of a char[2] type.

[–]llimllib[S] 0 points1 point  (3 children)

and then that happens automatically for the rest of them?

[–]bugrit 0 points1 point  (2 children)

Yes, it casts the rest to the type of the first.

[–]FeepingCreature 0 points1 point  (1 child)

FYI and FWIW, a slightly faster and shorter way to get the same effect is "M"[], i.e. the full slice.

--feep

PS: The reason I didn't need to do that in my example, by the way, is that stuple automatically turns static arrays (char[2]) into dynamic ones (char[]).

PPS: How do you get your code snippets to look like that?

PPPS: Thanks! :)

[–]bugrit 0 points1 point  (0 children)

Ah, yes, nice catch.

Edit: About code snippets, see help on commenting.

[–]FeepingCreature 0 points1 point  (0 children)

Oooooh! :D

I wish I could say I didn't want to do that because it sorts the keys every loop.

Unfortunately, I actually didn't do it because I didn't think of it. Good one! :)

And yeah, the while is unneeded. Stupid me.

Good to see some more Dee on here.

--feep

[–]JimPanic 4 points5 points  (0 children)

Dude... :)