代码高尔夫系列似乎相当受欢迎。 我遇到了一些将数字转换为其单词表示形式的代码。 一些例子是(为了编程的乐趣而使用 2 的幂):
- 2 -> 2 两个
- 1024-> 一千二十四
- 1048576 -> 一百四十八千五百七十六
我的同事提出的算法几乎有两百行长。 似乎会有一种更简洁的方法来做到这一点。
当前指南:
- 欢迎以任何编程语言提交(对此我深表歉意)
PhiLho 对于这一点最初缺乏清晰度)
- 最大输入 2^64(请参阅以下单词链接,谢谢 mmeyers)
- 短规模,首选英文输出,但欢迎任何算法。 只需与编程语言一起注释所使用的方法即可。
The code golf series seem to be fairly popular. I ran across some code that converts a number to its word representation. Some examples would be (powers of 2 for programming fun):
- 2 -> Two
- 1024 -> One Thousand Twenty Four
- 1048576 -> One Million Forty Eight Thousand Five Hundred Seventy Six
The algorithm my co-worker came up was almost two hundred lines long. Seems like there would be a more concise way to do it.
Current guidelines:
- Submissions in any programming language welcome (I apologize to
PhiLho for the initial lack of clarity on this one)
- Max input of 2^64 (see following link for words, thanks mmeyers)
- Short scale with English output preferred, but any algorithm is welcome. Just comment along with the programming language as to the method used.
发布评论
评论(22)
好的,我想是时候在 Windows BATCH 脚本中自己实现了(应该适用于 Windows 2000 或更高版本)。
这是代码:
这是我使用的测试脚本:
这是我从测试脚本得到的输出:
如果我能找到更多 大数字的名称,脚本将支持更大的数字。 但目前,该脚本将适用于从 -(10^66-1) 到 (10^66-1) 的所有数字。
我不得不提的是,我在 BATCH 中解决这个问题时获得了很多乐趣。 :)
Ok, I think it's time for my own implementation in Windows BATCH script (should work on Windows 2000 or later).
Here is the code:
This is the test script I used:
And this is the output I got from my test script:
If I could find some more names of large numbers, the script would support even bigger numbers. Currently, though, the script will work with all numbers from -(10^66-1) to (10^66-1).
I have to mention, that I had a lot of fun solving this in BATCH. :)
C# - 30 行,包括 方法声明和 { }s:
考虑前面提到的所有逗号、and 和连字符。 我只包含了十亿,因为decimal.MaxValue仅在十亿中。 对于更大的整数,您需要将相应的项目添加到hou[]数组中,并且可能将数字作为字符串传递,修改该行以使用最后3个字符而不是像我在这里那样使用模来提取块。
调用使用:
输出:
C# - 30 lines incl. method declaration and { }s:
Takes into account all the previously aforementioned commas, ands and hyphens. I've only included up to octillion because decimal.MaxValue is only in the octillions. For bigger integers you would need to add corresponding items to the thou[] array and perhaps pass the number in as a string, modifying the line to extract the block by using the last 3 chars instead of using modulo as I have here.
Called using:
Output:
在 A86 汇编 中 - 汇编为 .COM 可执行文件:
这是一个 454 字节的可执行文件。
这是(稍小)代码。 由于 A86 是仅限 8086 的汇编程序,因此我必须手动编写 32 位扩展代码:
文本使用 Huffman 编码存储。 命令行作为字符串传递,因此转换它很简单 - 将字符串分成三组,并解析每个组(百位、十位和个位),每个组后面跟随当前乘数(百万、千等)。
In A86 assember - assembles to a .COM executable:
That's a 454 byte executable.
Here's the (slightly smaller) code. Since A86 is an 8086 only assembler, I've had to hand code the 32bit extensions:
The text is stored using Huffman encoding. The command line is passed as a string so converting it is simple - split the string into groups of three and parse each group (hundreds, tens and units) following each with the current multiplier (millions, thousands, etc).
Lisp,仅使用标准函数:
奖励:
Lisp, using only standard functions:
Bonus:
C++,15 行:
用法:
C++, 15 lines:
Usage:
这是作弊吗?
Is this cheating?
Paul Fischer 和 Darius:你们有一些很棒的想法,但我讨厌看到它们以如此过于冗长的方式实现。 :) 开个玩笑,你的解决方案很棒,但我又压缩了
1430 个字节,同时保持在 79 列之内并保持 python 3 兼容性。这是我的 79 列中的 416 字节 python:(谢谢大家,我站在你们的肩膀上)
和测试:
Paul Fischer and Darius: You guys have some great ideas, but I hate to see them implemented in such an overly verbose fashion. :) Just kidding, your solution is awesome, but I squeezed
1430 more bytes out, while staying inside of 79 columns and maintaining python 3 compatibility.So here's my 416 byte python within 79 columns: (thanks guys, I'm standing on your shoulders)
And the tests:
请参阅递归的更好答案。 好多了。
疯狂地向 Darius 寻求灵感。 你的大
W
(现在是我的p
)特别聪明。我用这个测试它:
此时,这是对 Darius 当前解决方案的调整,这又是对我旧解决方案的调整,这是受到他的启发,并且他在评论中给出了一些错误提示。 这也是对Python的犯罪。
下面有剧透,rot13为了保护您,因为高尔夫的一半乐趣
弄清楚如何。 我强烈推荐 mnenhy Firefox
内联解码此(和其他简单编码方案)的扩展。
Pbafgnagf(Veranzrq gurz guvf erivfvba gb ubcrshyyl znxr gurzpynere。)
R
:Gur rzcgl frg。E
:Gung juvpu vf va pbzzba orgjrra pbhagvat va gur "grraf" (egrra,svsgrra、fvkgrra...) naq va gur graf (egl、svsgl、 >fvkgl....)
Z
、P
:Jung gurl ner va Ebzna ahzrenyf。M
:Nyy gur ahzoref sebz bar gb gjragl。Shapgvbaf(fbzr nyfberanzrq guvf ebhaq)
j
:Gur choyvp-snpvat shapgvba,juvpu gheaf n ahzore vagb jbeqf。_
:Erphefviryl gheaf gur ahzore vagb jbeqf,gubhfnaq-ol-gubhfnaq。a
vfgur ahzore,
y
vf ubj sne guebhtu gur cbjref bs 1000 jr ner。 耳格赫夫yvfg bs fvatyrgba yvfgf bs rnpu jbeq va gur ahzore, rt
[['bar'],['gubhfnaq'],['gjragl'],['sbhe']]
。c
: sbe rnpu jbeq va gur fcnpr-frcnengrq jbeq yvfgn
, nccraqfo
nf nfhssvk naq chgf gurz rnpu vagb n fvatyrgba yvfg。 Sbe rknzcyr,
c("zo ge","vyyvba") == [['zvyyvba'],['ovyyvba'],['gevyyvba']]
。See recursive's better answer. It's way betterer.
Mad props to Darius for inspiration on this one. Your big-
W
(now myp
) was especially clever.I test it with this:
At this point, this is a tweak of Darius' current solution, which is in turn a tweak of my older one, which was inspired by his, and he gave some bug hints in the comments. It is also a crime against Python.
Spoilers below, rot13'd for your protection, because half the fun of golf
figuring out how. I highly recommend the mnenhy Firefox
extension to decode this (and other simple encoding schemes) inline.
Pbafgnagf (V eranzrq gurz guvf erivfvba gb ubcrshyyl znxr gurz pyrnere.)
R
: Gur rzcgl frg.E
: Gung juvpu vf va pbzzba orgjrra pbhagvat va gur "grraf" (egrra,svsgrra, fvkgrra...) naq va gur graf (egl, svsgl, fvkgl....)
Z
,P
: Jung gurl ner va Ebzna ahzrenyf.M
: Nyy gur ahzoref sebz bar gb gjragl.Shapgvbaf (fbzr nyfb eranzrq guvf ebhaq)
j
: Gur choyvp-snpvat shapgvba, juvpu gheaf n ahzore vagb jbeqf._
: Erphefviryl gheaf gur ahzore vagb jbeqf, gubhfnaq-ol-gubhfnaq.a
vfgur ahzore,
y
vf ubj sne guebhtu gur cbjref bs 1000 jr ner. Ergheaf nyvfg bs fvatyrgba yvfgf bs rnpu jbeq va gur ahzore, r.t.
[['bar'],['gubhfnaq'],['gjragl'],['sbhe']]
.c
: sbe rnpu jbeq va gur fcnpr-frcnengrq jbeq yvfgn
, nccraqfo
nf nfhssvk naq chgf gurz rnpu vagb n fvatyrgba yvfg. Sbe rknzcyr,
c("z o ge","vyyvba") == [['zvyyvba'],['ovyyvba'],['gevyyvba']]
.Python,446 字节。 所有行都在 80 列以下,该死。 这是 Paul Fisher 的解决方案,几乎每一行都进行了编码调整,从他的488字节版本; 从那以后他又挤出了几个字节,我承认。 快去为他的答案投票吧!
历史已经变得复杂起来。 我从下面未混淆的代码开始,它支持负数和范围检查,并在一些数字中加上破折号以获得更好的英语:
然后我通过混淆将其压缩到大约 540 字节(对我来说是新的),Paul Fisher 找到了一个更短的算法(去掉破折号)以及一些极其可怕的 Python 编码技巧。 我窃取了编码技巧,将结果降到 508(仍然没有获胜)。 我尝试使用新算法重新启动,但该算法无法击败费舍尔的算法。 最后这是他的代码的调整。 尊重!
混淆后的代码已经针对干净的代码进行了测试,干净的代码是在一堆案例上通过眼球检查的。
Python, 446 bytes. All lines under 80 columns, dammit. This is Paul Fisher's solution with coding tweaks on almost every line, down from his 488-byte version; he's since squeezed out several more bytes, and I concede. Go vote for his answer!
The history has gotten complicated. I started with the unobfuscated code below, which supports negative numbers and range-checking, plus dashes in some numbers for better English:
Then I squeezed it to about 540 bytes via obfuscation (new to me), and Paul Fisher found a shorter algorithm (dropping the dashes) along with some marvelously horrible Python coding tricks. I stole the coding tricks to get down to 508 (which still did not win). I tried restarting fresh with a new algorithm, which was unable to beat Fisher's. Finally here's the tweak of his code. Respect!
The obfuscated code has been tested against the clean code, which was checked by eyeball on a bunch of cases.
一个T-SQL(SQL Server 2005)函数,包括测试用例:
A T-SQL (SQL Server 2005) function, including test cases:
好的,这是 F#,试图保持可读性,大约 830 字节:
这是单元测试
Ok, here's F#, trying to stay readable, at about 830 bytes:
and here are the unit tests
这是一个相对简单的 C 实现(52 行)。
注意:这不会执行任何边界检查; 调用者必须确保调用缓冲区足够大。
这是一个更加混乱的版本(682 个字符)。 如果我真的尝试的话,它可能会减少一点。
Here's a relatively straightforward implementation in C (52 lines).
NOTE: this does not perform any bounds checking; the caller must ensure that the calling buffer is large enough.
And here's a much more obfuscated version of that (682 characters). It could probably be pared down a little more if I really tried.
这是一个 Scala 解决方案。 我不高兴试图让它看起来很短——我牺牲了一点可读性:(
用法是:
Here's a Scala solution. I'm not happy about trying to make it look short -- I sacrificed a bit of readability :(
Usage is:
Perl 5.10
注释:
split()
似乎是主要问题。 现在,字符串占据了大部分字符。my
和local
来缩短它,并将它们全部放在一行上。严格
和警告
下工作。Perl 5.10
Notes:
split()
that seems to be the main problem. As it sits now the strings take up the bulk of the characters.my
's, and thelocal
, as well as putting it all on one line.strict
andwarnings
.嗯,你可能把门槛设得有点高,无论是在极限(18,446,744,073,709,552,000,我什至不知道如何写!)还是在目标(其他代码高尔夫导致了短代码,这个会很长)至少对于数据(单词))。
无论如何,作为记录,我在 PHP 中给出了一个众所周知的法语解决方案(不是我的!): 法语Écriture des nombres en français。 :-)
请注意您措辞的歧义(自愿或非自愿):“欢迎以任何语言提交”
我首先将其视为“自然语言”,然后才理解您可能的意思是“编程语言......
该算法在英语中可能更简单(并且区域变体较少......)。
Mmm, you might have put the bar a bit high, both on the limit (18,446,744,073,709,552,000, I don't even know how to write that!) and on the goal (the other code golfs resulted in short code, this one will be long at least for the data (words)).
Anyway, for the record, I give an well known solution (not mine!) for French, in PHP: Écriture des nombres en français. :-)
Note the ambiguity (voluntary or not) of your wording: "Submissions in any language welcome"
I first took it as "natural language", before understand you probably meant "programming language...
The algorithm is probably simpler in English (and with less regional variants...).
在 D 编程语言
在这里尝试一下
In the D programming language
Try it out here
我现在找不到该文件,但这是我上学时遇到的编程入门问题(学期末)。 我们必须能够将浮点数转换为有效的书面数字以用于支票。
作业完成后,教授展示了一些 C++ 代码,这些代码仅使用我们已经介绍过的概念解决了问题。 它只运行了 43 行,并且有详细的文档记录。
I can't find the file now, but this was an Intro to Programming problem (late in the term) where I went to school. We had to be able to turn a float into a valid written number for use on a check.
After the assignment was completed the professor showed some C++ code that solved the problem using only concepts we'd already covered. It ran just 43 lines, and was well-documented.
有人计划很快添加适当的逗号和“和”吗? 或者用连字符连接二十一到九十九? 否则没有什么意义,恕我直言:)
“九十九九千九百九十九”
与
“九十九万九千九百九十九”
(不,我的不起作用。但是。)
Does anyone plan on adding the appropriate commas and 'and' any time soon? Or hyphenating twenty-one through ninety-nine? Not much point otherwise, IMHO :)
'Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine'
vs
'Nine hundred and ninety-nine thousand, nine hundred and ninety-nine'
(And no, mine doesn't work. Yet.)
Perl 和 CPAN 协同工作:
Perl & CPAN working together:
几年前,我用 C# 创建了这个用于多语言应用程序。
这个是基类:
这个是用于 wordify..
这个是用于土耳其 Lera (TRY):
它的使用方式是这样的:
A few years ago I created this in C# for multi language applications.
This one is base class:
This one is for wordify..
And this one is for Turkish Lera (TRY):
And it is used this way:
这是 PHP 中的一个,来自 Convert Numbers to Words:
返回
,如果您想要一个更棒的可以处理逗号和数字的工具,请查看 zac hesters 的工作 语言显示函数:
Here's one in PHP, from Convert Numbers to Words:
returns
and if you want an even more awesome one that handles commas and numbers up to vigintillion check out zac hesters work at Language Display Functions: