Problem 470

Abstract / Summary

Generate a random number from 1 to 10 using a given function that produces numbers from 1 to 7.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0470.py

class Solution:
    def rand10(self):
        sum = 0
        for i in range(10):
            sum += rand7() - 1

        return 1 + sum % 10
7 lines | 149 bytes | submitted August 14, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 46% (200k+ submissions).

Typical patterns to solve this problem:
  • Math
  • Probability And Statistics
  • Randomized
  • Rejection Sampling
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method named rand10 that produces a pseudo-random integer uniformly distributed in the range 1 to 10. It leverages an existing helper function rand7, which returns an integer uniformly distributed between 1 and 7. By aggregating multiple calls to rand7 and applying arithmetic transformations, the method maps the broader range of possible sums onto the desired 1-10 interval.

Detailed Walkthrough

The method begins by establishing an accumulator variable that will hold the cumulative result of several rand7 invocations.

sum = 0

A for loop iterates exactly ten times. During each iteration, rand7 is called, its result is shifted down by one to produce a zero-based value, and this value is added to the accumulator.

for i in range(10):
    sum += rand7() - 1

After the loop completes, the accumulator contains a value ranging from 0 (up to ten calls each returning 1) to 60 (up to ten calls each returning 7). The final step reduces this range to the target interval by applying the modulo operator with divisor 10, then offsetting the result by 1 to convert the zero-based remainder into the required 1-10 range.

return 1 + sum % 10

The combination of these three code fragments constitutes the core logic of the method.

Edge Cases Handled

Because each rand7 call yields a value in the closed interval [1, 7], subtracting 1 guarantees a non-negative contribution (0 to 6) to the accumulator. Consequently, the sum can never be negative, and the modulo operation always receives a non-negative dividend. The modulo operation inherently wraps any sum, whether it is at the lower bound (0) or the upper bound (60), into a remainder between 0 and 9. Adding 1 then maps this remainder to the full inclusive range 1 to 10, ensuring that even extreme accumulator values are correctly transformed without overflow or underflow concerns.

Performance Optimizations

The implementation fixes the number of rand7 calls to ten, eliminating the need for a conditional loop that repeats until a certain condition is met. This deterministic iteration count simplifies control flow and enables the Python interpreter to optimize loop execution. The use of a single accumulator variable avoids the overhead of creating intermediate data structures. Arithmetic operations-subtraction, addition, and modulo-are executed in constant time and are highly optimized at the interpreter level. By performing the modulo reduction only once after all contributions have been summed, the method minimizes the number of expensive division operations, further enhancing runtime efficiency.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having a magic box that gives you a number between one and seven every time you press a button. That is what rand7 does. This code wants to make a new game where you get a number between one and ten instead. To do this, it presses the button on the first magic box ten times in a row. It adds all those little numbers together to create a big pile of numbers. Then, it uses a special trick with division to chop that big pile down until it fits perfectly into the size of ten. This makes sure that every number from one to ten has a fair chance of being picked.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 3 | μ = 4.11 | σ = 2.31

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
36 links | 21 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

20 solutions   August 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality