Randomness vs. Expectations: When “Random” Isn’t Random Enough

Randomness vs. Expectations: When “Random” Isn’t Random Enough

Willekeurig 📅 13 October 2024 👁 1333 views

Years ago, when I was developing an iOS app in Objective-C, a client gave me what seemed like a simple task: “Show random images.”

Easy, right? An array of images, a random generator, done. But after the first test, the client gave me feedback: “It shouldn’t be possible for the same image to appear three times in a row.”

My initial reaction was to explain that this is exactly what random means: anything can happen, even three times in a row. But what the client really wanted was a random experience that felt less repetitive and more varied for the user.

The First Approach

My first implementation looked something like this:


NSArray *images = @[@"img1.png", @"img2.png", @"img3.png", @"img4.png"];
int randomIndex = arc4random_uniform((uint32_t)[images count]);
NSString *imageName = images[randomIndex];
UIImage *image = [UIImage imageNamed:imageName];
self.imageView.image = image;
  

This worked fine: every call picked a random image. But it could still happen that img2.png appeared three times in a row.

The Client’s Request: Pseudo-Randomness

To prevent the same image from appearing too often, I added a small logic check. The app now remembers the last two images, and only allows a repeat after that.


static NSString *lastImage = nil;
static NSString *secondLastImage = nil;

- (void)showRandomImage {
    NSArray *images = @[@"img1.png", @"img2.png", @"img3.png", @"img4.png"];
    NSString *newImage;
    
    do {
        int randomIndex = arc4random_uniform((uint32_t)[images count]);
        newImage = images[randomIndex];
    } while ([newImage isEqualToString:lastImage] && 
             [lastImage isEqualToString:secondLastImage]);
    
    // Update history
    secondLastImage = lastImage;
    lastImage = newImage;
    
    // Show image
    self.imageView.image = [UIImage imageNamed:newImage];
}
  

This makes it impossible for an image to appear three times in a row, while still keeping the randomness intact.

Random vs. User Experience

What I learned from this: “random” means very different things to developers and to users.

  • For developers, randomness is statistically fair – each element has an equal chance.
  • For users, randomness often means varied, surprising, and not annoyingly repetitive.

This experience taught me that code shouldn’t only follow strict logic, but also support the experience of the end user.

Conclusion

Random isn’t always as random as it seems. Sometimes you need to cheat a little to create the feeling of randomness. And that’s what programming often comes down to: bridging the gap between pure logic and human expectations.

← Back to Blog