一、原题
链接:Training on Simple Fun #352: Reagent Formula | Codewars
Now we will confect a reagent. There are eight materials to choose from, numbered 1,2,..., 8 respectively. We know the rules of confect: You are given a integer array |
二、解题
1、分析
【数学的与或非】
等价结果在右侧
material1 and material2 cannot be selected at the same time | 1和2同时不选;只选1;只选2; |
material3 and material4 cannot be selected at the same time | 3和4同时不选;只选3;只选4; |
material5 and material6 must be selected at the same time | 5和6同时选;5和6都不选 |
material7 or material8 must be selected(at least one, or both) | 7和8同时不选;只选7;只选8; |
formula[length]五重复值,可进一步化为:
1和2同时不选;只选1;只选2; | (a[1]!=a[2]|| (a[1]==0 && a[2]==0)) |
3和4同时不选;只选3;只选4; | (a[3]!=a[4] || (a[3]==0 && a[4]==0)) |
5和6同时选;5和6都不选 | (a[5]==a[6]) |
7和8同时不选;只选7;只选8; | (a[7]>0 || a[8]>0) |
2、思路
1)创建数组a[9]={0}
2)逐步读取formula[length]中的值存入item,将a[item]++;
3)按照分析的结果进行后续处理
if(a[7]>0 || a[8]>0){
if(a[5]==a[6]){//主要是无重复项
if(a[3]!=a[4] || (a[3]==0 && a[4]==0)){
if(a[1]!=a[2]|| (a[1]==0 && a[2]==0)){
return true;
} else return false;
}
else return false;
}
else return false;
}
else return false;
三、Myway
#include <stdbool.h>
#include <stddef.h>
#include<stdio.h>
bool is_valid(size_t length, const unsigned formula[length]) {
// <---- hajime!
int a[9]={0},item=-1;
for(size_t i=0;i<length;i++){//
item=formula[i];// 非 formula[length]
a[item]+=1;
}
if(a[7]>0 || a[8]>0){
if(a[5]==a[6]){//主要是无重复项
if(a[3]!=a[4] || (a[3]==0 && a[4]==0)){
if(a[1]!=a[2]|| (a[1]==0 && a[2]==0)){
return true;
} else return false;
}
else return false;
}
else return false;
}
else return false;
}
复制时需要观察变量情况,如第11行,我直接将formula[length]复制来用,未将length换为i,导致发生错误。
数学思维在处理问题上,很有帮助。