2 回答

TA貢獻1936條經(jīng)驗 獲得超7個贊
這不是問題的唯一可能的編碼,因為每個問題都有其自己的特征。對于多背包問題,我會選擇IntegerChromosome代替BitChromosomes。
private static final ISeq<Integer> ITEMS = IntStream.rangeClosed(1, 10)
.boxed()
.collect(ISeq.toISeq());
public Codec<ISeq<List<Integer>>, IntegerGene> codec(final int knapsackCount) {
return Codec.of(
Genotype.of(IntegerChromosome.of(
0, knapsackCount, ITEMS.length())
),
gt -> {
final ISeq<List<Integer>> knapsacks = IntStream.range(0, knapsackCount)
.mapToObj(i -> new ArrayList<Integer>())
.collect(ISeq.toISeq());
for (int i = 0; i < ITEMS.length(); ++i) {
final IntegerGene gene = gt.get(0, i);
if (gene.intValue() < knapsackCount) {
knapsacks.get(gene.intValue()).add(ITEMS.get(i));
}
}
return knapsacks;
}
);
}
上面給出的編解碼器選擇一個IntegerChromoses長度為背包物品數(shù)量的 。它的基因范圍將比背包的數(shù)量還要大。物品i將被放入背包,其染色體索引為IntegerChromosome.get(0, i).intValue()。如果索引超出有效范圍,則跳過該項目。這種編碼將保證項目的明確劃分。

TA貢獻2012條經(jīng)驗 獲得超12個贊
如果您想要一組不同的基因,則必須定義兩組不同的基因。
private static final ISeq<Integer> SET1 = IntStream.rangeClosed(1, 10)
.boxed()
.collect(ISeq.toISeq());
private static final ISeq<Integer> SET2 = IntStream.rangeClosed(11, 20)
.boxed()
.collect(ISeq.toISeq());
public Codec<ISeq<ISeq<Integer>>, BitGene> codec() {
return Codec.of(
Genotype.of(
BitChromosome.of(SET1.length()),
BitChromosome.of(SET2.length())
),
gt -> ISeq.of(
gt.getChromosome(0).as(BitChromosome.class).ones()
.mapToObj(SET1)
.collect(ISeq.toISeq()),
gt.getChromosome(1).as(BitChromosome.class).ones()
.mapToObj(SET2)
.collect(ISeq.toISeq())
)
);
}
通過這兩個整數(shù)集,您將保證獨特性。
添加回答
舉報