Slashdot Mirror


Singapore's Prime Minister Shares His C++ Sudoku Solver Code

itwbennett writes: Several weeks ago, during a speech at the Founders Forum Smart Nation Singapore Reception, Singapore's prime minister Lee Hsien Loong said that he used to enjoy programming, and that the last program he wrote was a Sudoku solver in C++. To back that up, earlier today he announced (on Facebook and Twitter) that his code is available to download. He wrote on Facebook that he wrote the program 'several years ago' and that the code does 'a backtrack search, choosing the next cell to guess which minimises the fanout.'

36 of 230 comments (clear)

  1. It may have a .cpp extension but it's all C code by Anonymous Coward · · Score: 2, Informative

    I guess C++ just sounds higher tech.

  2. Technically C++ by Imagix · · Score: 4, Insightful

    Well... probably more accurate to call that C code. It's compilable under a C++ complier, but offhand I didn't spot anything that really made it C++-specific. Not a knock on the Prime Minister, but it might even be a little more geek cred to call it a Sudoku solver in C.

    1. Re:Technically C++ by Dutch+Gun · · Score: 4, Insightful

      Heh, leave it to the tech community to start nitpicking which language was actually used rather than the fact that we're seeing the very rare sight of a computer programmer in political office.

      I took a look at the code - yeah, it's really just C code, but that's fine for a tiny project like this. Nice code, very clean and readable, but not very well commented.

      --
      Irony: Agile development has too much intertia to be abandoned now.
    2. Re:Technically C++ by Bite+The+Pillow · · Score: 4, Insightful

      Since Dice, and really well before, fuck all of that technicality. If the dude can solve sudoku in anything other than a pencil, should we really nitpick?

    3. Re:Technically C++ by fisted · · Score: 3, Insightful

      everything has to be declared at the top of the function... Always.

      That's not true, and has never been. Until about 16 years ago, you had to declare your variables at the beginning of a block/compound statement. That can be well within the function.

      As of about 16 years ago, you're even allowed to freely mix your declarations and code.

      [incoherent gibberish]. And stuff like that.

      Yeah. The kind of stuff you seem largely unfamiliar with.

      General hint: If your functions are so long that having to (suppose this was indeed the case) declare/define all your variables at the top becomes a serious annoyance, then chances are that your functions are too long/do too much. Fix that instead.

    4. Re:Technically C++ by Threni · · Score: 3

      The comments are definitely c++.

    5. Re: Technically C++ by Sique · · Score: 4, Informative

      I guess, Angela Merkel knows. At least she wrote a program to simulate electron movements for her PhD thesis.

      --
      .sig: Sique *sigh*
  3. Put in context by Anonymous Coward · · Score: 5, Informative

    The guy was a Senior Wrangler (top math undergrad) at Cambridge before going to governance. I would hope he'd have picked up some coding skills along the way.

    Now with some other leaders, I'm impressed when they spell their names right.

    1. Re: Put in context by Anonymous Coward · · Score: 5, Informative

      Wiki link to those who aren't across Cambridge lingo

      http://en.m.wikipedia.org/wiki/Senior_Wrangler_%28University_of_Cambridge%29

      The Senior Wrangler is the top mathematics undergraduate at Cambridge University in England, a position once regarded as "the greatest intellectual achievement attainable in Britain."

    2. Re: Put in context by Anonymous Coward · · Score: 2, Informative

      The Senior Wrangler is the top mathematics undergraduate at Cambridge University in England, a position once regarded as "the greatest intellectual achievement attainable in Britain."

      In other news wiping an adult mans arse was once considered the greatest political achievement attainable not by birth in Britain.

  4. Re:It may have a .cpp extension but it's all C cod by AuMatar · · Score: 4, Informative

    Its also all legal C++. Just because it doesn't use the advanced features doesn't mean it isn't C++. I'd argue that for something this simple its even better code this way.

    --
    I still have more fans than freaks. WTF is wrong with you people?
  5. The actual code by Anonymous Coward · · Score: 5, Informative

    How's about including a link to the actual code?

    Here you go:

    https://drive.google.com/folde...

    OR:

    https://github.com/Doppp/LHL-S...

  6. Free Amos Yee by Anonymous Coward · · Score: 2, Interesting

    Hey, The guy released his Sudoku solver code, and that's great!
    Now how about using the same logical prowess to release Amos Yee?

    https://youtu.be/dD4y3U4TfeY

  7. Not that big of a deal... by Nutria · · Score: 3, Funny

    after all our President is a "coder" too!!! :eyeroll:

    --
    "I don't know, therefore Aliens" Wafflebox1
    1. Re:Not that big of a deal... by gnasher719 · · Score: 4, Insightful

      The code resembles something you expect from a first-year programming student - there's an input buffer overflow bug waiting to happen, the array size is odd (80 byte array? why? scanf() is still called without a field length specifier, and you only use 9 of those 80 bytes in a normal case).

      You seem to be very optimistic in your views of first year programming students.

      Here's what I see: Many years ago, I had a lovely job helping to teach people to program, and I had to review their homework. There were some whose thought processes were all over the place. There was one guy who managed to write the most convoluted code that always worked perfectly well, but I would never have hired him because reviewing it was just too painful. And there was one student who wrote code that I could scan in half a minute and see that it was correct and worked. And that's what this guy's code looks like.

      "Perhaps it was written by him in his spare time". OF COURSE it was written in his spare time. His a prime minister, he doesn't write code on the job. What comments do you want? The code is simple and obvious. What data structures to explain? If you are too stupid to understand them immediately, then you shouldn't be programming. What lack of error checking? What scenario do you suggest where error checking would help?

      Your last sentence is a totally unfounded, vicious attack on the intellectual honesty of the man. It's disgusting. Unless you have any evidence for it, you should apologise.

  8. Well... by EmeraldBot · · Score: 3, Informative

    While not utilizing any of c++'s features, it is still valid c++. I think he might call it this because he may usually program in c++, but maybe just for this one project he did it in c, and since it's still legal c++ he finds it easier to just label it as c++. I actually quite like it - could use a bit more commenting, but overall very clean and readable. Should compile with a decent c or c++compiler...

    --
    "Set a man a fire, he'll be warm for the rest of the night. Set a man afire, he'll be warm for the rest of his life."
  9. From his Facebook post on his Sudoku solver by cciRRus · · Score: 5, Interesting
    He posted this on his Facebook.

    For techies: the program does a backtrack search, choosing the next cell to guess which minimises the fanout.

    Here’s a question for those reading the source code: if x is an (binary) integer, what does (x & -x) compute?

    Hope you have fun playing with this. Please tell me if you find any bugs! – LHL

    ===========

    As several of you noted, (x & –x) returns the least significant ‘1’ bit of x, i.e. the highest power of two that divides x. This assumes two’s complement notation for negative numbers, as some of you also pointed out. e.g. if x=12 (binary 1100), then (x & -x) = 4 (binary 100). I didn’t invent this; it is an old programming trick.

    Nice!

    --
    w00t
    1. Re:From his Facebook post on his Sudoku solver by UnknownSoldier · · Score: 2, Informative

      That's common knowledge.

      Bit Twiddling Hacks

    2. Re:From his Facebook post on his Sudoku solver by Anonymous Coward · · Score: 5, Insightful

      Not among prime ministers

    3. Re:From his Facebook post on his Sudoku solver by Anonymous Coward · · Score: 2, Funny

      I have been around for a long time and no well adjusted kid has ever known what a binary integer was let alone a trick that utilizes it to determine the largest power of two that divides it.

  10. Stupid sudoku solver? by Taco+Cowboy · · Score: 4, Insightful

    It might be a 'stupid sudoku solver', like you say, but at least, that is a program that does something, rather than the congress critters who do nothing but producing massive amount of HOT AIR

    --
    Muchas Gracias, Señor Edward Snowden !
    1. Re:Stupid sudoku solver? by antiperimetaparalogo · · Score: 5, Funny

      It might be a 'stupid sudoku solver', like you say, but at least, that is a program that does something, rather than the congress critters who do nothing but producing massive amount of HOT AIR

      Imagine that you are a zombie apocalypse survivor, naked and wet, in a freezing winter Alaskan night, tired to death, and you can share a tent either with this Singapore's prime minister who wants you to stay awake with him and solve stupid Sudoku puzzles or with one of those "congress critters who do nothing but producing massive amount of HOT AIR" - who would be you choice?

      --
      Antisthenes: "Wisdom begins by examining the words/names." - excuse my English, i am (slightly...) better with my Greek!
    2. Re:Stupid sudoku solver? by antiperimetaparalogo · · Score: 2

      The Germans taught that to the Greeks when they forcefully took a loan from a conquered Greece during WW2, then spent the money and refused to repay when the war was over.

      Hmmm... i am surprised that you know that...

      Not that we fucking Greeks deserve any excuse for our other stupid behaviors, but yes, you are right, what you wrote is true (by the way: Hitler, until he was defeated, payed some of the money back!!! His successors in the goverment of the German (west, east, or unified now) state... no!)

      --
      Antisthenes: "Wisdom begins by examining the words/names." - excuse my English, i am (slightly...) better with my Greek!
  11. New competition by viperidaenz · · Score: 5, Funny

    There should be an international coding competition between heads of state.

    1. Re:New competition by paul5086 · · Score: 3, Funny

      Meanwhile, in New Zealand... http://static2.stuff.co.nz/125...

    2. Re:New competition by NicBenjamin · · Score: 3, Insightful

      Would have to be Heads of Government. Lee's a Prime Minister, so he's not Head of State. Singapore's Head of State is Tony Tan.

      Under Singapore's Constitution President Tan has very few powers, but he still technically outranks the PM who has powers. It's similar to the system in Britain/Canada/etc. where the Queen's Head of State,* but the Prime Minister is the one who actually does everything interesting.

      And yes, this is a pet peeve of mine. I spent the week Netanyahu addressed Congress in constant nerd-rage because the entire US media kept calling him a "Head of State" when he isn't.

      *Altho many Canadians argue the Queen isn't their Head of State, her representative in Canada is (the Governor-General). The fact no Court's ruled on this definitively shows how important the title "Head of State" is in a Parliamentary system. Most legal scholars seem to think that the Queen is Head of State, but there is a minority that disagrees and their Constitution is not helpful on this question. But mostly nobody cares.

  12. Re:The PM writes good code by Anonymous Coward · · Score: 2, Funny

    You never heard of the Obfuscated_C_Code_Contest. Who knows what this "Sudoku Solver Code" actually does? It could be a Trojan horse to steal American freedoms.

  13. Re:Lead By Example?! by quenda · · Score: 3, Funny

    but our former prime-minister had a restaurant... our great Greek dinner with mousaka,

    Which one? You'd have hoped with that experience he might have had some idea how to balance the books. Did his restaurant go broke?

  14. Re:That's C code by fisted · · Score: 2, Informative

    void Succeed()

    That's actually more C++'ish, a C programmer would put it as

    void Succeed(void)

    Which means in C what the former means in C++.
    </nitpick>

    Apart from that, yeah. It's pretty much C. Almost C89, even, were it not for the C++ style comments and two instances of mixed declarations and code.

  15. Re:Lead By Example?! by antiperimetaparalogo · · Score: 4, Informative

    but our former prime-minister had a restaurant... our great Greek dinner with mousaka,

    Which one? You'd have hoped with that experience he might have had some idea how to balance the books. Did his restaurant go broke?

    It was mister Samaras, the one who just lost the elections - (he claims) his restaurant did just fine (he had it years ago, together with a business partner, while studing in USA - yes, one more Greek restaurant in the States!). To be fair he did a good job as a prime minister in the elimination of deficit, he not only balanced the books, but provided a (significant) surplus. Our new prime minister...well...!

    --
    Antisthenes: "Wisdom begins by examining the words/names." - excuse my English, i am (slightly...) better with my Greek!
  16. Not C++ Code Because its Understandable by Anonymous Coward · · Score: 2, Funny

    Its not C++ code because the code is understandable. For example:

    1. he does not use templates, restricting himself to solving only over the integer space. what about a sudoku puzzle of strings? basics, people, this is basic stuff.
    2. he is using raw loops. what about range based bi-directional iterators using lambdas? scott meyers is going to throw a tantrum.
    3. free functions without namespaces or a class even. more appropriate would have been korea::south::presidental_code::sudoku_solver.
    4. better yet, abstract it all away in a templated class, be sure to overload all the operators, implement copy-on-write and do the non-public stuff in a pimpl that relies some weird over-engineered templated-to-death library from boost. and make that shit virtual.
    5. and be sure to do all of the above multi-threaded, since you need to scale to multiple cores these days.

  17. that guy is for real by joss · · Score: 2

    He was Senior Wrangler while at Cambridge. Plus, his son is one of the most productive scala programmers in the world despite only doing it in his spare time. These guys ain't dumb.

    --
    http://rareformnewmedia.com/
  18. Re:That's C code by fisted · · Score: 2

    Also compiles under gcc and g++. Except for the file extension;)

    You cannot use "$compiler compiles it" to determine whether it's portable or correct C, just look at all the non-C garbage gcc happily accepts.
    Though in this case i'm not saying it wouldn't be correct; I just pointed out that C programmers usually wouldn't declare their function to have an unspecified number of arguments when what they really want is no arguments. It's not wrong; just unusual, C++ influenced style.

    the PM's code is legal and portable C

    Possibles &= ~(Possibles & -Possibles);
    Portable my ass. This at least requires two's complement. I'm also fairly sure that in addition to being nonportable, it's undefined behaviour unless there's a sequence point i'm missing (can verify that later)

    and therefore also legal C++.

    Don't be silly. Valid C isn't automatically valid C++, and if you have a program that happens to be something both a C and a C++ would accept, it doesn't need to have the same behaviour. Consider:

    int main(void)
    {
    int class = 42;
    }

    That's strictly conforming C, and invalid C++

    Further consider:

    int main(void)
    {
    for (size_t i = 0; i puts("poof");
    }

    That's valid C++, invalid C89, strictly conforming C99/C11. When treated as C, it will behave different from when treated as C++, unless your implementation has char and int being of the same width, which is rather unusual.
    Thanks for playing.

  19. Very C like. by gatkinso · · Score: 2

    Not a great example of modern C++.

    --
    I am very small, utmostly microscopic.
  20. I'm impressed by Mr+Z · · Score: 3, Insightful

    There's no shortage of people ragging on the code. "It's not C++ enough to be called C++," "there's not enough comments", "it uses C stdio.h", etc. Get over it.

    This looks like the sort of program I might dash out over an afternoon (maybe two) to satisfy some intellectual curiosity. Programming as play. This isn't production code, it's fun code, written to satisfy oneself.

    Is it perfect? WHO CARES! That's not important. That misses the point. If you doodle in your notepad and it brings you a smile, does anyone care it's not as good as the Mona Lisa? You sure as heck don't. And that's what this code is. A doodle. It just happens to be in simple, straightforward procedural C/C++ code.

    I personally think playing with programming is important. Sure, you'll write a lot of dreck. But, you'll also learn a lot. You learn real lessons when you do write dodgy code, and the dodgy code actually bites you. You also can try new things fearlessly. After all, you're programming a toy for oneself, and you're under no deadline pressure. There's no spec you have to fulfill. You can experiment and enjoy it.

    Programming as play still helps build your programming reflexes. If and when you do sit down to write professional grade software, all of that play will make the basic work of programming natural. Rather than focusing your energy on the basic details of programming, you can instead focus your energy designing maintainable code that meets the business requirements and documenting that design. Writing the code just flows naturally.

    So, yeah, I'm impressed. This Sudoku solver brought a smile to my face. It's incredibly cool that the prime minister shared a code doodle with us.

  21. Not very user friendly by aNonnyMouseCowered · · Score: 2

    No help file. WTF is this supposed to do? A bad example given our age of touch and click operating systems, even the most arcane GNU or BSD program is more comprehensible. Maybe it says a lot about the politics of his country, smart but not very user friendly.