Sat*_*pes 1 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
Run Code Online (Sandbox Code Playgroud)
我想知道实现这一目标所需的最小检查次数是多少.
我的想法是使用卡诺图,如下所示:
00| 01| 11| 10
-----------------
0 | A | A | B | A |
-----------------
1 | C | C | A | C |
-----------------
Run Code Online (Sandbox Code Playgroud)
其中A对应于什么,B调用function1,C调用function2
根据我所看到的,你有2个A和2个组合共有3个用于A 1用于B和2个组合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();
}
Run Code Online (Sandbox Code Playgroud)
现在我也看到它上面或者这个更好:
if ((prev_state == new && input1 == disable) || (prev_state == new && input2 == Off)) {
function2();
}
else if (input1 == enable && input2 == On) {
function1();
}
Run Code Online (Sandbox Code Playgroud)
感谢那些提出查找表的人,这个表是O(1)但占用了内存空间.我现在意识到我宁愿有一个不使用额外内存的解决方案.您是否同意使用卡诺图是获得最小比较量的有效方法?
我想知道你需要达到的最小检查次数是多少......
零.使用查找表
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]();
Run Code Online (Sandbox Code Playgroud)
OP后来评论寻找一种解决方案......不会使用额外的内存.
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();
}
Run Code Online (Sandbox Code Playgroud)