Simple Fun #352: Reagent Formula——C语言提高题

一、原题

链接: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 formula. Array contains only digits 1-8 that represents material 1-8. Your task is to determine if the formula is valid. Returns true if it's valid, false otherwise.

二、解题

1、分析

【数学的与或非】

        等价结果在右侧

material1 and material2 cannot be selected at the same time

1和2同时不选;只选1;只选2;
material3 and material4 cannot be selected at the same time3和4同时不选;只选3;只选4;
material5 and material6 must be selected at the same time5和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,导致发生错误。

        数学思维在处理问题上,很有帮助。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱读书的小胖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值