Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Seems n² but could be n.log(n) #2

Open
Ten0 opened this issue Apr 17, 2024 · 0 comments
Open

Seems n² but could be n.log(n) #2

Ten0 opened this issue Apr 17, 2024 · 0 comments

Comments

@Ten0
Copy link

Ten0 commented Apr 17, 2024

Unless I'm mistaken the implementation of first fit is n² because it checks every bin for every item,

for item in items.into_iter() {
// Find the first bin that the item fits in
match bins
.iter_mut()
.filter(|bin| item.size() <= bin.remaining_capacity)
.next()
{
Some(bin) => bin.add(item),
None => bins.push(Bin::with_item(bin_size, item)),
}
// TODO: Should be move bins that are full to a new vector to avoid having to iterate them?
}

And this could be improved to n.log(n) (complexity could be improved but for small sizes this probably isn't better) by storing the current size of each bin in a BTreeSet<(usize, usize)> where tuple is (size_of_the_bin, index_of_the_bin).
Using the BTreeSet::range function enables you to look up the best fit in O(log(n)) in the map.

@Ten0 Ten0 changed the title Seems n² Seems n² but could be n.log(n) Apr 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant