Wednesday, May 27, 2015

C言語で「1時間以内に解けなければプログラマ失格となってしまう5つの問題が話題に」の5問目を解いてみた

Java8で「ソフトウェアエンジニアならば1時間以内に解けなければいけない5つの問題」の5問目を解いてみた」と「Perl6で「ソフトウェアエンジニアならば1時間以内に解けなければいけない5つの問題」の5問目を解いてみた」経由。

以下のような問題ですね。
1,2,…,9の数をこの順序で、”+”、”-“、またはななにもせず結果が100となるあらゆる組合せを出力するプログラムを記述せよ。例えば、1 + 2 + 34 – 5 + 67 – 8 + 9 = 100となる
とてもいい問題だと思うし、一方で上の回答例がeval的な手法を使っていたので、そういうズルをせずに解いたらどうなるだろう、ということでCで書いてみた。

正解が出るようになるまでの所要時間、約30分。なんとかプログラマ合格のようです。
#include <stdio.h>

#define MAX_POS 9
#define EXPECTED 100

static char buf[32];

static void doit(int pos, int sum, char *p, int sign)
{
    int i, n, s;

    *p++ = sign == 1 ? '+' : '-';
    for (i = pos, n = 0; i <= MAX_POS; ++i, n *= 10) {
        *p++ = '0' + i;
        n += i;
        s = sum + sign * n;
        if (i == MAX_POS) {
            if (s == EXPECTED) {
                *p = '\0';
                printf("%s = %d\n", buf + 1, s);
            }
        } else {
            doit(i + 1, s, p, 1);
            doit(i + 1, s, p, -1);
        }
    }
}   

int main(void)
{
    doit(1, 0, buf, 1);
    return 0;
}

98 comments:

  1. Replies

    1. In your blog I was happy to see your article, better than last time, and have made great progress, I am very pleased. I am looking forward to your article will become better and better.
      hotmail login | red ball | 192.168.1.1

      Delete
  2. Packers and movers @ http://professionalmovers.in/
    Packers and Movers Chennai@ http://professionalmovers.in/packers-and-movers-in-chennai/
    Packers and Movers Bangalore@ http://professionalmovers.in/packers-and-movers-in-bangalore/

    ReplyDelete
  3. I value the article.Really thank you! Much obliged
    Diwali wishes

    ReplyDelete
  4. Really appreciate you sharing this blog post. Want more.
    Happydiwaliwishess.in

    ReplyDelete
  5. Great, thanks for sharing this blog article.Really looking forward to read more. Will read on...
    childrens Day wishes 2015

    childrens Day quotes

    ReplyDelete
  6. I gathered useful information on this point . Thank you posting relative information and its now becoming easier to complete this assignment
    mahjong games | agar io | games like minecraft|halloween | pacman| kizi | hulk | geometry dash pc | sniper games | games

    ReplyDelete
  7. It's a fact that your blog posts are so unique and interesting and I enjoys a lot while reading your posts because you explained your post very deeply in a very easy and clear language. Thanks for your support and Happy Blogging :D

    hostgator black friday 2015

    happy new year 2016
    new year 2016

    ReplyDelete
  8. I really liked your blog post.Thanks Again. Really Cool.
    Dilwale torrent

    ReplyDelete
  9. I truly appreciate this blog article.Thanks Again. Cool.
    Dilwale movie download

    ReplyDelete
  10. I really enjoy the blog.Much thanks again. Really Great.
    New year wishes

    ReplyDelete
  11. I think this is a real great blog article.Much thanks again. Great
    New year wishes 2016

    ReplyDelete
  12. I am so grateful for your post.Much thanks again. Really Great.
    New year quotes 2016

    ReplyDelete
  13. I truly appreciate this blog.Much thanks again. Keep writing.
    happy new year images

    ReplyDelete
  14. Im grateful for the blog.Really thank you! Much obliged.
    shahrukh dilwale movie torrent

    ReplyDelete
  15. Are You Celebrating Happy New Year 2016? If yes so please visit our website by clicking on these links and enjoy new stuffs which is updated by us like New Year wishes, Greetings, HD Images, New Year 2016 SMS and many more thing which make you more excited to celebrate this New Year 2016.

    Happy new year 2016
    Happy new year
    Happy new year sms 2016
    New Year 2016
    New Year Wishes 2016
    New Year Quotes 2016
    Happy new year wishes 2016
    Happy new year images 2016
    Happy new year messages 2016
    Happy new year Quotes 2016

    ReplyDelete
  16. Great article.... Thanx a lot...
    For Tech related topic...
    Visit my site....
    TechVine

    ReplyDelete
  17. I was noticing from many days that your blog is helping too many readers as your articles are easy to understand and helpful to us.
    I think you should explore the articles on your website, You should also cover different different categories for articles as you writes awesome. Thanks for sharing this great article with us.
    Happy New Year 2016

    ReplyDelete
  18. This is a good idea, I would like to refer to my content development. I have a few concerns can not explain, hopefully this article can help me. baixar facebook gratis , baixar facebook , facebook gratis , descargar whatsapp messenger , descargar mobogenie gratis , download mobogenie , whatsapp messenger free

    ReplyDelete
  19. I have read your article several times. It really made me feel important, I think people would not ignore it. Thanks for sharing it. facebook gratis , facebook gratis , baixar whatsapp gratis , whatsapp apk , whatsapp plus , mobogenie baixar , android market

    ReplyDelete
  20. You Can Download new Apps and Games Download HikeFor Pc Plants vs Zombies 2 Free Download Download HikeSkins IDM SERIAL KEY FOR 2016
    wasap app
    wasap app
    wasap app
    wasap app
    wasap app
    You Can Download new Apps and Games Download HikeFor Pc Plants vs Zombies 2 Free Download Download HikeSkins IDM SERIAL KEY FOR 2016
    wasap app
    wasap app
    wasap app
    wasap app
    wasap app

    ReplyDelete
  21. Get details about LG G5 cases and Galaxy S7 cases..


    Galaxy S7 cases

    ReplyDelete
  22. Have you ever met someone who liked the similar readings that you read? Its amazing to read inspirational quotes or love quotes for her to get better in life.

    ReplyDelete
  23. Get Customer Care numbers,address and more details. Visit my site.

    ReplyDelete
  24. Euro cup is not far away. Click Euro Cup 2016 live" to watch euro cup live

    ReplyDelete
  25. The war between humans, orcs and elves continues. Lead your race through a series of epic battles, using your crossbow to fend off foes and sending out units to destroy castles. Researching and upgrading wisely will be crucial to your success! There are 5 ages total and each one will bring you new units to train to fight in the war for you cause.
    earn to die 2 | game earn to die
    | unfair mario | slitherio
    Whatever you do, don’t neglect your home base because you cannot repair it and once it is destroyed, you lose! Age of War is the first game of the series and really sets the tone for the Age of War games . Also try out the Age of Defense series as it is pretty similar.
    In this game, you start at the cavern men’s age, then evolve! There is a total of 5 ages, each with its units and turrets. Take control of 16 different units and 15 different turrets to defend your base and destroy your enemy.
    tank trouble | age of war | age of war 6 | gold miner
    The goal of the game also differs depending on the level. In most levels the goal is to reach a finish line or to collect tokens. Many levels feature alternate or nonexistent goals for the player.

    ReplyDelete
  26. Your posts really great. Every one is in-detailed and clear understanding. You are awesome.
    happy fathers day
    father's day 2016

    ReplyDelete
  27. Want to know regular updates of Euro Cup 2016????
    Get Euro Cup live Streaming,Euro Cup 2016 Schedule,Euro Cup 2016 Fixture,Euro Cup 2016 Live Streaming,Euro Cup 2016 Live Stream,Euro Cup 2016 Live Score.
    Venue-France,From 10th june-10july. 24 teams,10 stadiums. Stay updated.

    ReplyDelete
  28. I must be thankful for sharing your ideas.Thank you for the good writeup.its a brellint job.please visit here for more detail:
    Packers And Movers Bangalore

    ReplyDelete
  29. Great article. I really appreciate the hard work you put in it. To know about Galaxy Note 7 Visit my blog.

    ReplyDelete
  30. Want to know about Veterans Day? Why is it celebrated,how did it all start and all other details, just have a look at my blog Veterans Day Poems

    ReplyDelete
  31. Visit us now to view & share beautiful collection of Best Images of
    rose day 2017

    ReplyDelete
  32. Visit us now to view & share beautiful collection of Best Images of
    chocolate day images

    ReplyDelete
  33. It is a great article. You will surely like this also because it is a great stufff
    Facebook Lite

    ReplyDelete
  34. All the best blogs that is very useful for keeping me share the ideas of the future as well this is really what I was looking for, and I am
    very happy to come here. Thank you very much
    animal jam codes | five nights at freddy's 4 | hotmail login

    ReplyDelete
  35. Thank you both for sharing Holy Mass with us each day FNAF Sister Location Juegos Friv Friv 2018 to make yourselves available Friv Twizl Jeux De Twizl Juegos De FNAF Sister Location when we were called out late at night and any other time and for your support and encouragement in every respect. Juegos Friv 2021 Juegos Twizl Juegos Yepi 2017 Juegos De Twizl

    ReplyDelete
  36. Danke, dafur dass Ihr jeden Tag mit uns die Hl. Messe gefeiert habt, fur all die Reparaturen im ganzen Haus Jeux De Friv Jogos Friv Jogos Friv fur Euere Bereitschaft Juegos Friv Juegos Friv Juegos De Friv immer zur Verfugung zu stehen Juegos Geometry Dash Juegos Twizl Twizy Twizl Danke, dass Sie Ihr Muhen um den Aufbau des Leibes Christi mit uns teilten.

    ReplyDelete
  37. A todos que partilham e trabalham sob estas mesmas convicções e princípios Friv Friv 360 Friv4school 2020 Senhor Deputado Cashman, agradeço-lhe a informação. Jeux De Friv 2018 Juegos De Roblox Juegos De Zoxy Mais uma vez, obrigada ao Parlamento por comungar da visão que informa a nova política dos consumidores Juegos Kizi 2017 Juegos Yepi 2017 Twizl 3 Zoxy 2 assente no mercado - a visão de um mercado de consumidores informados e capacitados que procuram e usufruem, com confiança,

    ReplyDelete
  38. Wir danken Ihnen Friv4school 2018 Gry Friv 2 Gry Friv 5 dass Sie diese Hoffnung mit uns teilen und diesen Schritt auf dem Pilgerweg des Vertrauens Gry Friv Juegos Friv 100 Juegos Friv 1000 mit uns gegangen sind. Juegos Friv 5 Juegos De Friv 2 Juegos Friv 250 Juegos Yepi wir danken Ihnen für das Interesse an unseren Produkten und hoffe

    ReplyDelete
  39. http://clickymaza.pk/
    http://apkinmobile.com/
    https://jobs360.pk/
    http://paknulled.com/
    http://dramasalert.com
    http://euhpro.pk/

    ReplyDelete
  40. This blog is so nice to me. I will continue to come here again and again. Visit my link as well. Good luck
    cara menggugurkan kandungan
    cara menggugurkan kandungan
    cara menggugurkan kandungan

    ReplyDelete
  41. دار السلام اهم شركة نقل عفش بالطائف وكذلك اهم شركة نقل عفش بمكة وجدة والمدينة المنورة تقوم الشركة بنقل العفش بحفر الباطن وتبوك وجازان وتقوم بنقل الاثاث بالقصيم
    شركة نقل عفش بالطائف
    شركة نقل عفش بالمدينة المنورة
    شركة نقل عفش بجازان وابها

    ReplyDelete