我已经确定了如下所示的真值表
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/