[Solution]Problem 69: Generate Random Numbers According to Probability [TripleByte]
Logic, Problem Solving, Math
To learn more about the newsletter, check our detailed About Page + FAQs
To help me understand you better, please fill out this anonymous, 2-min survey. If you liked this post, make sure you hit the heart icon in this email.
Get a free Weekly Summary of the important updates in AI and Machine Learning here
Recommend this publication to Substack over here
Take the next step by subscribing here
How did you do yesterday?
The optimization for this is very different from traditional Leetcode problems. That’s why I love this problem. It requires you to think like a software engineer and consider the life cycle of your solution. I also love that this solution is not gimmicky. Any coder with problem-solving ability, coding skills, and some insight will be able to solve this. You don’t need to know some complex data-structure or memorize an esoteric algorithm for this. The solution is a pure demonstration of your competence in problem-solving.
Problem
This problem was asked by Triplebyte.
You are given n
numbers as well as n
probabilities that sum up to 1. Write a function to generate one of the numbers with its corresponding probability.
For example, given the numbers [1, 2, 3, 4]
and probabilities [0.1, 0.5, 0.2, 0.2]
, your function should return 1
10% of the time, 2
50% of the time, and 3 and 4 20% of the time.
You can generate random numbers between 0 and 1 uniformly.
Keep reading with a 7-day free trial
Subscribe to Technology Made Simple to keep reading this post and get 7 days of free access to the full post archives.