目的 c と条件に小さな問題があります。私が与えた 6 つの条件で、少なくとも 3 つが正しいと検証されなければならないことをどのように示すことができますか?
ご回答ありがとうございます。
目的 c と条件に小さな問題があります。私が与えた 6 つの条件で、少なくとも 3 つが正しいと検証されなければならないことをどのように示すことができますか?
ご回答ありがとうございます。
あなたはそれを次のように行うことができます:
int validated=0;
if(condition1){
validated++;
}
if(condition2){
validated++;
}
if(condition3){
validated++;
}
if(condition4){
validated++;
}
if(condition5){
validated++;
}
if(condition6){
validated++;
}
if(validated>=3){
//do your stuffs
}
int counter = 0;
if (condition1) counter++;
if (condition2) counter++;
if (condition3) counter++;
if (condition4) counter++;
if (condition5) counter++;
if (condition6) counter++;
if (counter >= 3) {
// something
}
あなたは正しい条件を数えることを試みることができます:
擬似コード:
int counter = 0;
if(A) counter++;
if(B) counter++;
if(C) counter++;
if(D) counter++;
if(E) counter++;
if(F) counter++;
if(counter >= 3){
//do stuff here
}
counter = 0;
すでに与えられた答えに加えて、ここに可変数の条件のためのより柔軟な解決策があります:
int conditions[6] = {condition1, condition2, condition3,
condition4, condition5, condition6};
int counter = 0;
for (int i = 0; i < sizeof(conditions)/sizeof(int); i++) {
counter += conditions[i]; // Assuming your conditions are 0 or 1.
}
if (counter >= 3) {
// do something
}
@interface Conditions
@property (nonatomic, strong) NSMutableArray *conditions;
- (void) addCondition: (Condition*) theCondition;
- (NSInteger) count;
- (NSInteger) satisfying: ( void (^block)(Condition*) );
@end
条件のリストをオブジェクトにラップします。3 つの条件が満たされているかどうかを知る必要がある場合:
if ([self.conditions satisfying: ^(Condition *c){ return [c isSatisfied]; })>3) {...};
これはやり過ぎです - おそらくばかげたやり過ぎです - これが使い捨てのプロジェクトである場合。ただし、長期的なメンテナンスが問題になる場合、これにより、条件が実装の詳細から切り離されます。条件の長いリストを避けます。条件を簡単に追加または変更できます。論理が複雑になった場合は、オブジェクト指向の優れたインターフェイスで対処できます。(Condition はおそらく、オブジェクトではなく Facade として動作するプロトコルです)。