4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 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()に渡して条件を満たす時だけ出力しています。

4
0
0

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
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?