Skip to content

Commit d7cbcb9

Browse files
ejeggneslihanturan
authored andcommitted
More random recent image selection (#1542)
time-based randomness is biased - if someone uploaded 100 images in hour, one week ago, and I select a random point in time, their last image is way more likely to come up than anything else. With this, there is still bias towards choosing one of the last N in any burst of uploads (where N is the number of recent changes fetched) but it's a bit better than before.
1 parent 73ffd11 commit d7cbcb9

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

app/src/main/java/fr/free/nrw/commons/media/RecentChangesImageUtils.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import org.w3c.dom.Element;
44
import org.w3c.dom.NodeList;
55

6+
import java.util.Random;
7+
68
import javax.annotation.Nullable;
79

810
public class RecentChangesImageUtils {
@@ -13,8 +15,23 @@ public class RecentChangesImageUtils {
1315
@Nullable
1416
public static String findImageInRecentChanges(NodeList childNodes) {
1517
String imageTitle;
16-
for (int i = 0; i < childNodes.getLength(); i++) {
17-
Element e = (Element)childNodes.item(i);
18+
Random r = new Random();
19+
int count = childNodes.getLength();
20+
// Build a range array
21+
int[] randomIndexes = new int[count];
22+
for (int i = 0; i < count; i++) {
23+
randomIndexes[i] = i;
24+
}
25+
// Then shuffle it
26+
for (int i = 0; i < count; i++) {
27+
int swapIndex = r.nextInt(count);
28+
int temp = randomIndexes[i];
29+
randomIndexes[i] = randomIndexes[swapIndex];
30+
randomIndexes[swapIndex] = temp;
31+
}
32+
for (int i = 0; i < count; i++) {
33+
int randomIndex = randomIndexes[i];
34+
Element e = (Element) childNodes.item(randomIndex);
1835
if (e.getAttribute("type").equals("log") && !e.getAttribute("old_revid").equals("0")) {
1936
// For log entries, we only want ones where old_revid is zero, indicating a new file
2037
continue;

0 commit comments

Comments
 (0)