Skip to content

Commit 2e0a0ba

Browse files
Corrected tests
1 parent 2c4141e commit 2e0a0ba

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

think-machine-random/src/main/java/com/softwaremagico/tm/random/RandomSelector.java

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ private void assignMandatory() throws InvalidXmlElementException {
163163

164164
private TreeMap<Integer, Element> assignElementsWeight() throws InvalidXmlElementException {
165165
final TreeMap<Integer, Element> weightedElements = new TreeMap<>();
166-
int count = 0;
166+
int count = 1;
167167
for (final Element element : getAllElements()) {
168168
try {
169169
validateElement(element);
@@ -178,9 +178,6 @@ private TreeMap<Integer, Element> assignElementsWeight() throws InvalidXmlElemen
178178
count += weight;
179179
}
180180
}
181-
if (!weightedElements.isEmpty()) {
182-
weightedElements.put(count, null);
183-
}
184181
return weightedElements;
185182
}
186183

@@ -355,7 +352,7 @@ protected Element selectElementByWeight() throws InvalidRandomElementSelectedExc
355352
throw new InvalidRandomElementSelectedException("No elements to select");
356353
}
357354
final int value = RANDOM.nextInt(totalWeight) + 1;
358-
Element selectedElement = weightedElements.values().iterator().next();
355+
Element selectedElement;
359356
final SortedMap<Integer, Element> view = weightedElements.headMap(value, true);
360357
try {
361358
selectedElement = view.get(view.lastKey());
@@ -400,22 +397,20 @@ protected void updateWeight(Element element, int newWeight) {
400397
weightedElements.put(newWeight, element);
401398
}
402399

403-
public SortedMap<Integer, Element> getWeightedElements() {
400+
public TreeMap<Integer, Element> getWeightedElements() {
404401
return weightedElements;
405402
}
406403

407404
public Integer getAssignedWeight(Element element) {
408405
if (element == null) {
409406
return null;
410407
}
411-
Integer elementWeight = null;
412-
for (final Map.Entry<Integer, Element> entry : weightedElements.entrySet()) {
413-
if (Objects.equals(entry.getValue(), element)) {
414-
elementWeight = entry.getKey();
415-
continue;
408+
int previousWeight = 0;
409+
for (final Entry<Integer, Element> entry : weightedElements.entrySet()) {
410+
if (entry.getValue().equals(element)) {
411+
return entry.getKey() - previousWeight;
416412
}
417-
if (elementWeight != null)
418-
return entry.getKey() - elementWeight;
413+
previousWeight = entry.getKey();
419414
}
420415
return null;
421416
}

0 commit comments

Comments
 (0)