3131import net .createmod .catnip .data .Pair ;
3232import net .minecraft .world .item .ItemStack ;
3333
34+ import java .util .HashMap ;
35+
3436public class LogisticsManager {
3537
3638 private static Random r = new Random ();
@@ -40,8 +42,8 @@ public class LogisticsManager {
4042
4143 public static InventorySummary getSummaryOfNetwork (UUID freqId , boolean accurate ) {
4244 try {
43- Cache <UUID , InventorySummary > cacheToUse =
44- accurate ? LogisticsManager . ACCURATE_SUMMARIES : LogisticsManager .SUMMARIES ;
45+ Cache <UUID , InventorySummary > cacheToUse = accurate ? LogisticsManager . ACCURATE_SUMMARIES
46+ : LogisticsManager .SUMMARIES ;
4547 return cacheToUse .get (freqId , () -> createSummaryOfNetwork (freqId ));
4648 } catch (ExecutionException e ) {
4749 e .printStackTrace ();
@@ -106,7 +108,32 @@ public static Multimap<PackagerBlockEntity, PackagingRequest> findPackagersForRe
106108 Multimap <PackagerBlockEntity , PackagingRequest > requests = HashMultimap .create ();
107109
108110 // Packages need to track their index and successors for successful defrag
109- Iterable <LogisticallyLinkedBehaviour > availableLinks = LogisticallyLinkedBehaviour .getAllPresent (freqId , true );
111+ Iterable <LogisticallyLinkedBehaviour > allAvailableLinks = LogisticallyLinkedBehaviour .getAllPresent (freqId ,
112+ true );
113+
114+ // Group links by InventoryIdentifier and randomly select one from each group
115+ Map <InventoryIdentifier , List <LogisticallyLinkedBehaviour >> linksByInventory = new HashMap <>();
116+ List <LogisticallyLinkedBehaviour > availableLinks = new ArrayList <>();
117+
118+ // Group links by their inventory identifier
119+ for (LogisticallyLinkedBehaviour link : allAvailableLinks ) {
120+ InventoryIdentifier inventoryId = getInventoryIdentifierFromLink (link );
121+ if (inventoryId != null ) {
122+ linksByInventory .computeIfAbsent (inventoryId , k -> new ArrayList <>()).add (link );
123+ } else {
124+ // Links without inventory identifier are added directly
125+ availableLinks .add (link );
126+ }
127+ }
128+
129+ // Randomly select one link from each inventory group
130+ for (List <LogisticallyLinkedBehaviour > linkGroup : linksByInventory .values ()) {
131+ if (!linkGroup .isEmpty ()) {
132+ LogisticallyLinkedBehaviour selectedLink = linkGroup .get (r .nextInt (linkGroup .size ()));
133+ availableLinks .add (selectedLink );
134+ }
135+ }
136+
110137 List <LogisticallyLinkedBehaviour > usedLinks = new ArrayList <>();
111138 MutableBoolean finalLinkTracker = new MutableBoolean (false );
112139
0 commit comments