用单个类构建“父/子”系统

时间:2019-04-16 20:37:44

标签: java recursion

我正在尝试使用类Bone创建一个类似“骨骼”的系统,并让“主要”骨骼的孩子由所有其他相连的骨骼组成。

public class Main {

    public static void main(String[] args) {
        Bone body = new Bone("primary", null);
        Bone leftArm1 = new Bone("left_arm_1", body);
        Bone leftArm2 = new Bone("left_arm_2", leftArm1);
        Bone rightArm1 = new Bone("right_arm_1", body);
        Bone rightArm2 = new Bone("right_arm_2", rightArm1);

        List<Bone> bones = new ArrayList<Bone>();
        for(Bone child : body.getChildren()) {
            System.out.println(child.getName());
        }
    }

}
public class Bone {
    private Bone parent = null;
    private String name = null;
    private List<Bone> children = new ArrayList<Bone>();
    public Bone(String name, Bone parent) {
        this.name = name;
        this.parent = parent;
        if(parent != null) {
            parent.addChild(this);
        }
    }
    public String getName() {
        return this.name;
    }
    public Bone getParent() {
        return this.parent;
    }
    public boolean hasParent() {
        if(this.parent != null) {
            return true;
        } else {
            return false;
        }
    }
    public List<Bone> getChildren() {
        return this.children;
    }
    public boolean hasChildren() {
        if(this.children.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }
    public void addChild(Bone child) {
        this.children.add(child);
    }
}

当前程序正在输出...

left_arm_1
right_arm_1

何时应该输出...

left_arm_1
left_arm_2
right_arm_1
right_arm_2

我如何使程序输出正确的字符串?

2 个答案:

答案 0 :(得分:1)

我会使用递归

model = Sequential()
embedding_layer = Embedding(dictionary_size, num_word_dimensions,
                            weights=[embedding_weights], mask_zero=True,
                            embeddings_regularizer=regularizers.l2(0.0001))
model.add(TimeDistributed(embedding_layer,
                          input_shape=(max_conversation_length, timesteps)))

model.add(TimeDistributed(Bidirectional(LSTM(m // 2, return_sequences=True,
                                             kernel_regularizer=regularizers.l2(0.0001)))))
model.add(TimeDistributed(Dropout(0.2)))
model.add(TimeDistributed(GlobalMaxPooling1D()))
model.add(Bidirectional(LSTM(h // 2, return_sequences = True,
                             kernel_regularizer=regularizers.l2(0.0001)),
                        merge_mode='concat'))
model.add(Dropout(0.2))
crf = CRF(num_tags, sparse_target=False, kernel_regularizer=regularizers.l2(0.0001))
model.add(crf)
model.compile(optimizer, loss = crf.loss_function, metrics=[crf.accuracy])

答案 1 :(得分:0)

由于body只有2个孩子,因此输出仅为left_arm_1 right_arm_1

如果要打印所有子项,则需要递归地对所有子项进行打印,依此类推。