基于Java的卡诺图化简

1.先给出核心匹配段，对ArrayList数组中的内容判断是否可化简

//传入两个字符串对其进行是否仅有一个变量不同的字符串
//如果有返回这两个字符串化简的新字符串
//例 ABCd+ABCD=ABC
public class pipei {
public String match(String mstr, String nstr) {
String s = "";//存放成功匹配后化简的字符串
int rem = 0;//记录差异字符的位置
int sum = 0;//记录差异字符的个数，仅有差异为1才继续进行
String[] m = mstr.split("");
String[] n = nstr.split("");
for (int i = 0; i < nstr.length(); i++) {
if (!m[i].equals(n[i])) {
sum = sum + 1;
rem = i;
}
}
//将成功匹配的新字符串产生作为返回值传出
if (sum == 1) {
for (int i = 0; i < nstr.length(); i++) {
if (i != rem) {
s = s + m[i];
}
}
}

rem = 0;
sum = 0;
return s;
}
}

2.主函数应用


import java.util.ArrayList;//应用ArrayList动态数组方便元素的提取删除
import java.util.Random;//随机数产生卡诺图方便程序测试

public class Main {

public static void main(String[] args) {
// TODO 自动生成的方法存根
ArrayList list = new ArrayList();
pipei s1 = new pipei();
int[][] numbers = new int[4][4];
Random random = new Random();
String result = "";
int num;
for (int i = 0; i < 4; i++) {//随机产生4*4的01矩阵
for (int j = 0; j < 4; j++) {
num = random.nextInt(10);
if (num > 4) {
numbers[i][j] = 1;
} else {
numbers[i][j] = 0;
}

}
}
//根据得到的01矩阵和下标将数组中为1的元素得到对应的项
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
String s = "";
if (numbers[i][j] == 1) {
if (i == 0) {
s = s + "AB";
} else if (i == 1) {
s = s + "1B";
} else if (i == 2) {
s = s + "A2";
} else if (i == 3) {
s = s + "12";
}
if (j == 0) {
s = s + "CD";
} else if (j == 1) {
s = s + "3D";
} else if (j == 2) {
s = s + "C4";
} else if (j == 3) {
s = s + "34";
}
System.out.println(s);
}
}
}
int remperi = 0;
String remi = "", remp = "";//记录要删除的两个项
for (int j = 0; j < 4; j++) {
for (int i = 0; i < list.size(); i++) {
if (i >= list.size()) {
break;
}
for (int p = i + 1; p < list.size(); p++) {
if (p >= list.size()) {
break;
}
if (list.size() <= 2) {
break;
}
//匹配到两个合适的字符串将其删除，合并的字符串填入ArrayList
if (!s1.match(list.get(i).toString(), list.get(p).toString()).equals("")) {
remi = list.get(i).toString();
remp = list.get(p).toString();
if (i != 0) {
i--;
}
break;
} else {

remi = "";
remp = "";
}
}
if (!remi.equals("")) {
list.remove(remp);//对字符串进行删除（下标操作困难）
list.remove(remi);
}
}
}
//根据最终化简的ArrayList得出最简最小项
for (int i = 0; i < list.size(); i++) {
result = result + list.get(i);
if (i != list.size() - 1) {
result = result + "+";
}
}
System.out.println(result);
}

}


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客