c - 真值表的最优实现

标签 c algorithm truthtable karnaugh-map

我已经确定了如下所示的真值表

prev_state| input1         | input2 |next_state| Action
(def/new) |(Disable/Enable)|(Off/On)|          |
def       | D              | Off    | def      | Nothing
def       | D              | On     | def      | Nothing
def       | E              | Off    | def      | Nothing
def       | E              | On     | new      | call function1
new       | D              | Off    | def      | call function2
new       | D              | On     | def      | call function2
new       | E              | Off    | def      | call function2
new       | E              | On     | new      | Nothing

我想知道实现此目标所需的最少检查次数是多少。

我想使用 Karnaugh map比如下面这个:

    00| 01| 11| 10 
  -----------------
0 | A | A | B | A |  
  -----------------
1 | C | C | A | C |  
  -----------------

其中A对应空,B调用function1,C调用function2

据我所知,你有 2 个 A 的 2 个组合和一个 A 总共 3 个组合 1个 和 2 个 C 的 2 个组合

那是不是说比较的最少次数是3+1+2=6? 但是因为 A 什么都不做,所以最小的实现需要 只有 B 和 C 的 3 种组合?

测试实现

if (prev_state == new && input1 == disable) {
    function2();
}
else if (prev_state == new && input2 == Off) {
    function2();
}
else if (input1 == enable && input2 == On) {
    function1();
}

现在我看到了上面那个更好还是这个更好:

if ((prev_state == new && input1 == disable) || (prev_state == new && input2 == Off)) {
    function2();
}
else if (input1 == enable && input2 == On) {
    function1();
}

感谢那些提出查找表的人,它是 O(1) 但占用内存空间。 我现在意识到我更愿意有一个不使用额外内存的解决方案。您是否同意使用卡诺图是得出最小比较量的有效方法?

最佳答案

I was wondering what is the minimum number of checks that you need to achieve ...

零。使用查找表

void f_Nothing(void) {
  ; // do nothing
}

void f_function1(void) {
  ;  // something interesting
}

void f_function2(void) {
  ;  // something interesting
}

int main(void) {

  typedef void (*fun_type)(void);

  fun_type f[2][2][2] = { //
      {{f_Nothing, f_Nothing}, {f_Nothing, f_function1}}, 
      {{f_function2, f_function2}, {f_function2, f_Nothing}}};
  bool prev_state, input1, input2;
  //...
  f[prev_state][input1][input2]();

OP 后来评论了looking for a solution that ... doesn't use further extra memory .

if ( (input1 == E && input2 == ON) && (prev_state == def)) function1();
if (!(input1 == E && input2 == ON) && (prev_state == new)) function2();

// or

if (input1 == E && input2 == ON) {
  if (prev_state == def) function1();
} else {
  if (prev_state == new) function2();
}

关于c - 真值表的最优实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54096741/

相关文章:

c - PostgreSQL:从 C 函数评估 SQL 表达式

javascript - 如何在 javascript 中合并两棵树?

c++ - C++中的开源随机数生成算法?

haskell - Haskell 中匿名函数的真值表

javascript - 生成数组中变量的可能真值

c - c中的指针递增

c - 如何检查是否在宏中从 C 设置了环境变量

python - PyEval_InitThreads 什么时候被调用?

java - treeMap中entrySet的时间复杂度是多少

c++ - 我的代码中有错误 - bool 真值表