Competitive programming in Nim
2021-09-26 16:00:00
Author: maskray.me(查看原文)
阅读量:26
收藏
UNDER CONSTRUCTION
In the afternoon, I came cross the Nim programming language again on Lobsters. I first learned some basics of the language in 2015, but had not touched it since then. An idea popped into my mind: why not solve some coding challenges in Nim?
"Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula.", according to its website.
As a niche language, it is not supported on many coding challenge websites. Fortunately, the Nim compiler generates C code. With a small amount of work, we can build a self-contained C source file suitable for submission.
Let's take a LeetCode challenge as an example. We write the main algorithm in Nim and use the emit pragma to write a C wrapper.
The LeetCode environment includes some glibc headers like <stdio> which result in some conflicts due to duplicate definitions of struct _IO_FILE and some GNU extern inline functions. Let's write a Nim program to remove the duplicate definitions.
import strutils var body: seq[string] = @[] i = 0 for line in lines "a_comb.c": body.add(line)
while i < body.len: if body[i].startsWith("struct _IO_FILE {"): whilenot body[i].startsWith "}": i += 1 i += 1 continue if body[i].startsWith("__inline extern") or body[i].startsWith("int main("): var c = 0 var changed = false i += 1 whiletrue: c += body[i].count('{') - body[i].count('}') changed = changed or c > 0 i += 1 if c == 0and changed: break continue
echo body[i] i += 1
1
nim c --run --verbosity:0 x > for-submit.c
Finally, run { echo '/*'; cat a.nim; echo '*/'; cat for-submit.c; } | xclip -i -selection clipboard and paste the content into the LeetCode editor:) Well, the Nim source is not really needed but it is useful for archive purposes.
for-submitted.c is suitable for 64-bit Linux environment.
TODO Figure out how to support Codeforces (Windows with a 64KiB source code size limit).