朝日新聞2005年5月6日パズル横丁解答

プログラムの実行結果は以下の通り。最後の出力23が求める答えになる。

max:21,a:1,b:4,c:9,d:2,e:8,f:3,g:5,h:7,i:6
max:23,a:1,b:9,c:3,d:7,e:2,f:8,g:6,h:4,i:5
cnt:96

図示すると以下の通り。

プログラムのソースは以下の通り。

#include "puzutl.h"

YesNo used[10];

int main( int argc, cstring argv[])
{
  int           cnt = 0;
  int           x = 0;
  for( int a=1; a< 10; a++) {
    used[a] = YES;
    for( int b=1; b< 10; b++) {
      if( used[b]) continue;
      used[b] = YES;
      for( int c=1; c< 10; c++) {
        if( used[c]) continue;
        used[c] = YES;
        for( int d=1; d< 10; d++) {
          if( used[d]) continue;
          used[d] = YES;
          for( int e=1; e< 10; e++) {
            if( used[e]) continue;
            used[e] = YES;
            for( int f=1; f< 10; f++) {
              if( used[f]) continue;
              used[f] = YES;
              for( int g=1; g< 10; g++) {
                if( used[g]) continue;
                used[g] = YES;
                for( int h=1; h< 10; h++) {
                  if( used[h]) continue;
                  used[h] = YES;
                  for( int i=1; i< 10; i++) {
                    if( used[i]) continue;
                    used[i] = YES;
                    if( ( a-b==f || b-a==f) &&
                        ( b-c==g || c-b==g) &&
                        ( c-d==h || d-c==h) &&
                        ( d-e==i || e-d==i)) {
                      cnt++;
                      int y = f+g+h+i;
                      if( y > x ) {
                        x = y;
                        ps( "max:%d,a:%d,b:%d,c:%d,d:%d,e:%d,f:%d,g:%d,h:%d,i:%d\n", y, a, b, c, d, e, f, g, h, i);
                      }
                    }
                    used[i] = NO;
                  }
                  used[h] = NO;
                }
                used[g] = NO;
              }
              used[f] = NO;
            }
            used[e] = NO;
          }
          used[d] = NO;
        }
        used[c] = NO;
      }
      used[b] = NO;
    }
    used[a] = NO;
  }
  ps( "cnt:%d\n", cnt);
  return    0;
}