我最近在做一个养猪场项目,有一个需求是当公猪与母猪配种时,要查询两头猪在四代以内是否有血缘关系,如果有则提示。我现在可以通过猪的特定标识在数据库表中找到它的父母,后面应该要如何去实现这个四代比对过程呢?这个需求我大概思路是用递归来做,请教高人们这个需要怎么做?递归是在sql里做判断还是在java代码端做判断?具体怎么做?最好有个代码示例
如果不考虑兄弟姐妹的话如下:
找到A的父母2人,祖父母4人(父母的父母),曾祖父母8人(父母的父母的父母)
同理找到B的父母、祖父母、曾祖父母
判断他们每一代是否有重复即可,流程上能够从父母辈开始判断有重复即结束,是否向上继续追溯祖父母,同理无重复再追溯曾祖父母
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
Pig p15 = new Pig(15,null,null);
Pig p14 = new Pig(14,null,null);
Pig p13 = new Pig(13,null,null);
Pig p12 = new Pig(12,null,null);
Pig p11 = new Pig(11,null,null);
Pig p10 = new Pig(10,null,null);
Pig p9 = new Pig(9,null,null);
Pig p8 = new Pig(8,null,null);
Pig p7 = new Pig(7,p14,p15);
Pig p6 = new Pig(6,p12,p13);
Pig p5 = new Pig(5,p10,p11);
Pig p4 = new Pig(4,p8,p9);
Pig p3 = new Pig(3,p6,p7);
Pig p2 = new Pig(2,p4,p5);
Pig p1 = new Pig(1,p2,p3);
Pig p16 = new Pig(1,p4,p5);
System.out.println(find(p1,p16,4));
}
// 俺是pigA,她是pigB,俺俩配种
public static boolean find(Pig pigA,Pig pigB,int generation){
// 俺的4代祖宗
List<Pig> aAncestry = new ArrayList<Pig>();
// 她的4代祖宗
List<Pig> bAncestry = new ArrayList<Pig>();
// 添加俺爸和俺爸的祖宗
if(pigA.father != null)
addAncerstry(aAncestry,pigA.father,generation);
// 添加俺妈和俺妈的祖宗
if(pigA.mother != null)
addAncerstry(aAncestry,pigA.mother,generation);
// 添加她爸和她爸的祖宗
if(pigB.father != null)
addAncerstry(bAncestry,pigB.father,generation);
// 添加她妈和她妈的祖宗
if(pigB.mother != null)
addAncerstry(bAncestry,pigB.mother,generation);
// 祖宗对比
for(Pig pigAancestry: aAncestry){
for(Pig pigBancestry: bAncestry){
// 同一个祖宗
if(pigAancestry.getSelfId() == pigBancestry.getSelfId()){
System.out.println("俺祖宗:"+pigAancestry.toString());
System.out.println("她祖宗:"+pigBancestry.toString());
return true;
}
}
}
return false;
}
public static void addAncerstry(List<Pig> ancestry,Pig pig,int generation){
if(generation == 1)
return;
ancestry.add(pig);
if(pig.father != null)
addAncerstry(ancestry,pig.father,generation-1);
if(pig.mother != null)
addAncerstry(ancestry,pig.mother,generation-1);
}
static class Pig{
// 猪的标识
private int selfId;
// 猪它爸
private Pig father;
// 猪它妈
private Pig mother;
public Pig(int selfId, Pig father, Pig mother) {
this.selfId = selfId;
this.father = father;
this.mother = mother;
}
@Override
public String toString() {
return "Pig{" +
"selfId=" + selfId +
", father=" + father +
", mother=" + mother +
'}';
}
public int getSelfId() {
return selfId;
}
public void setSelfId(int selfId) {
this.selfId = selfId;
}
public Pig getFather() {
return father;
}
public void setFather(Pig father) {
this.father = father;
}
public Pig getMother() {
return mother;
}
public void setMother(Pig mother) {
this.mother = mother;
}
}
}
从下往上,看,1的爸妈是2和3,2的爸妈是4和5
我现在可以通过猪的特定标识在数据库表中找到它的父母,后面应该要如何去实现这个四代比对过程呢?