Skip to content

Instantly share code, notes, and snippets.

@maraigue
Last active January 30, 2016 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraigue/ba7eda1b2d0b25b29e1e to your computer and use it in GitHub Desktop.
Save maraigue/ba7eda1b2d0b25b29e1e to your computer and use it in GitHub Desktop.
[C++] 「すべてのデータに対して何かを行って評価値を得て、評価値が最大のものを返す」ことをDRYに書くには
// ------------------------------------------------------------
// 【動機】
// 「すべてのデータに対して何かを行って評価値を得て、評価値が最大のものを
// 返したい」というシーンはよくある。(実験データの分析、AIの作成など)
// そのときよくあるコードとしては
//
// int input, best_input;
// int score, best_score = -1;
//
// for(std::size_t i = 0; i < input_list.size; ++i){
// input = input_list.get(i);
// score = calc_score(input);
// if(score > best_score){
// best_score = score;
// best_input = input;
// }
// }
// return input;
//
// というものがあるが、「input」「score」に対応する形で別途
// 「best_input」「best_score」も変数を定義しないとならないのが
// DRYじゃない、ということがしょっちゅう気になっていた。
//
// じゃあどうすればよいかと考えたとき、構造体を定義すればいいんじゃないか?
// と思って書いたのが以下のコード。
// ------------------------------------------------------------
#include <iostream>
int get_score(int input){
// 今回は、評価値は「一の位の値」としている
return input % 10;
}
int main(void){
struct Status{
int score;
int input;
};
const int size = 3;
int data[size] = {304, 107, 256};
Status status, best_status = {-1, 0};
for(int i = 0; i < size; ++i){
status.input = data[i];
status.score = get_score(data[i]);
if(status.score > best_status.score){
best_status = status;
}
}
std::cout << "Best input: " << best_status.input << " (Score: " << best_status.score << ")" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment