Skip to content

Instantly share code, notes, and snippets.

@Ivorforce
Created October 12, 2015 11:34
Show Gist options
  • Save Ivorforce/09a2de65caed872b6b46 to your computer and use it in GitHub Desktop.
Save Ivorforce/09a2de65caed872b6b46 to your computer and use it in GitHub Desktop.
/*
* Copyright 2015 Lukas Tenbrink
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ivorius.ivtoolkit.random;
import java.util.*;
public class WeightedShuffler
{
public static <T extends WeightedSelector.Item> void shuffle(Random rand, List<T> items, double totalWeight)
{
List<WeightedSelector.SimpleItem<T>> wrapped = new ArrayList<>();
for (T t : items)
wrapped.add(WeightedSelector.SimpleItem.of(rand.nextDouble() * t.getWeight(), t));
Collections.sort(wrapped, new Comparator<WeightedSelector.SimpleItem<T>>()
{
@Override
public int compare(WeightedSelector.SimpleItem<T> o1, WeightedSelector.SimpleItem<T> o2)
{
return o1.item.getWeight() > o2.item.getWeight()
? Double.compare(o1.getWeight(), o2.item.getWeight())
: Double.compare(o2.getWeight(), o1.item.getWeight());
}
});
items.clear();
for (WeightedSelector.SimpleItem<T> simpleItem : wrapped)
items.add(simpleItem.item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment