作者Frozenmouse (*冰之鼠*)
看板Programming
標題Re: [問題] 1-9位數不重複印出來 (C++ template)
時間Wed Dec 14 11:43:40 2016
※ 引述《mikemagic88 (Mikemagic88)》之銘言:
: 使用者輸入1 印1-9
: 使用者輸入2 印1-98 (11, 22, 33等重複的不印)
: 使用者輸入3 印1-987 (121, 988, 667等有重複的不印)
#include <iostream>
using namespace std;
#ifndef INPUT
#define INPUT 3
#endif
template<int Length, int Flags = 0, int LastDigit = 9, int Number = 0>
struct SolutionFinder {
static void exec() {
SolutionFinder<Length, Flags, LastDigit - 1, Number>::exec();
if (!Number || !(Flags & (1 << LastDigit))) {
SolutionFinder<
Length - 1,
Flags | (1 << LastDigit),
9,
Number * 10 + LastDigit
>::exec();
}
}
};
template<int Length, int Flags, int Number>
struct SolutionFinder<Length, Flags, -1, Number> {
static void exec() { }
};
template<int Flags, int LastDigit, int Number>
struct SolutionFinder<0, Flags, LastDigit, Number> {
static void exec() {
if (Number) cout << Number << endl;
}
};
int main() {
SolutionFinder<INPUT>::exec();
return 0;
}
使用範例:
$ g++ -O3 -DINPUT=3 -o test3 test.cpp
$ ./test3
中規中矩(?)的版本
不過編到 INPUT >= 6 記憶體就不夠用了,求救援 XD
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.171.99.34
※ 文章網址: https://www.ptt.cc/bbs/Programming/M.1481687024.A.5BE.html
※ 編輯: Frozenmouse (1.171.99.34), 12/14/2016 11:47:58
→ Neisseria: 剛試了一下,INPUT = 6 時,程式編不完 125.227.36.84 12/14 16:44
→ Neisseria: 不知道是不是記憶體不足,後來 kill 掉 125.227.36.84 12/14 16:44
→ Neisseria: 就放棄了。總之,還是蠻有趣的 XD 125.227.36.84 12/14 16:46
推 CindyLinz: "求救援" => 募資買記憶體! :D 112.121.78.5 12/15 00:31