evenfurther / pathfinding

Pathfinding library for rust

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Negative cost values lead to wrong results in dijkstra and A*

simonstix opened this issue · comments

I know this was stupid on my part, but during advent of code I tried using Dijkstra to optimize a path. So instead of minimizing cost, I wanted to optimize a score. I tried it by using a negative cost, which returned invalid results. It was easily fixed by using max_score_per_step - current_score as a cost, then calculating the final score with final_score = step_count * max_score_per_step - total_cost.
As I said, it's my fault for trying to misuse the algorithms.

That said, I think there should either be a warning in the documentation that all costs must be positive or even a check/panic in case costs are negative. That way the algorithms never return wrong paths.
Another possibility would be to use the minimum value for cost, instead of zero. For example by creating a trait MinValue that returns 0 for unsigned values and the smallest negative number for signed values. But that would break compatibility with custom types, so I can see how it could be problematic.

I just realized there's already a min value trait in num_traits: https://docs.rs/num-traits/latest/num_traits/bounds/trait.LowerBounded.html

I'm also trying to use this crate for AOC22 day 16, maybe some of the code could be added to the examples.

just got it, here: https://github.com/marco-silva0000/aoc22/blob/main/16/src/main.rs

Does this code terminate? I let it run for one whole minute and it has not finished yet. I'm not sure it is the best example to illustrate those algorithms.

But I'll keep the suggestion to add more examples in mind, I myself have plenty of code where I use pathfinding, including in 8 of the first 21 days of AOC22 so far.

1m 1s on a mac m1 pro. the python version ran for 4 days without terminating nor finding the best result though xD

yeah I'm sure my version is bad I'm just learning rust now so mostly struggling with the types than anything else.
that version goes trough all the searched paths squared, it's trying to find 2 non intercepting paths that when added produce the biggest score. also used the BFS for distance calculation.