LoginSignup
0

More than 3 years have passed since last update.

日能研の問題をCで解いてみた(2018/11)

Last updated at Posted at 2018-11-15

日能研の広告の問題pythonで解いてみた記事があったので、同じことをC言語で実装してみました。

#include <stdio.h>
#include <math.h>

int trim(int d, int n) {
    int w, k=1, t=0;
    while(d > 0) {
        w = d % 10;
        if(w != n) {
            t += k * w;
            k *= 10;
        }
        d /= 10;
    }
    return t;
}

int ite(int *d) {
    int r;
    r = *d % 10;
    *d /= 10;
    return r;
}

void output(int val) {
    int i,w;
    w = val;
    for(i=6; i>1; i--) {
        if(w%i != 0)
            break;
        w /= 10;
    }
    if(i <= 1) {
        static int cnt = 1;
        printf("%d\n", val);
    }
}

void permutations(int cl, int k, int val) {
    int t_i, t_cl, t_w;
    if(k-2 <= 0) {
        output(val + cl);
        output(val + (10*(cl%10)) + (cl/10));
        return;
    }
    t_cl = cl;
    while((t_i=ite(&t_cl)) != 0) {
        t_w = t_i * pow(10, k-1);
        permutations(trim(cl,t_i), k-1, val+t_w);
    }
}

int main() {
    permutations(123456, 6, 0);
    return 0;
}

permutations()を再帰的に呼ぶことでpythonのitertools.permutations()と同様のことを行い、生成した値をoutput()に渡して条件を満たす時だけ出力しています。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0