implement fitness function with penalty

This commit is contained in:
2026-01-31 10:45:24 +01:00
parent cacc2911f1
commit 7df33a810b

View File

@@ -1,6 +1,7 @@
package main
import "core:fmt"
import "core:math"
import "core:os"
import "core:strconv"
import "core:strings"
@@ -27,6 +28,28 @@ read_data :: proc(file: string) -> (res: [NUMBER_OF_ITEMS]Item, ok := true) {
return
}
Chromosome :: [NUMBER_OF_ITEMS]bool
distance :: proc(x, y: int) -> int {
return math.abs(x - y)
}
penalize :: proc(d: int) -> int {
return math.min(-3 * d, 0)
}
// side-effect: reads global `items`
fitness :: proc(chrom: Chromosome) -> int {
tot_profit, tot_weight := 0, 0
for bit, idx in chrom {
if !bit {continue}
tot_profit += items[idx].profit
tot_weight += items[idx].weight
}
return tot_profit + penalize(distance(tot_weight, CAPACITY))
}
main :: proc() {
items, ok := read_data(DATA_FILE)
if !ok {