<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>probability Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/probability/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/probability/</link>
	<description></description>
	<lastBuildDate>Fri, 05 Jun 2020 06:15:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>probability Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/probability/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1467. Probability of a Two Boxes Having The Same Number of Distinct Balls</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 04 Jun 2020 05:18:59 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6867</guid>

					<description><![CDATA[<p>Given&#160;2n&#160;balls of&#160;k&#160;distinct colors. You will be given an integer array&#160;balls&#160;of size&#160;k&#160;where&#160;balls[i]&#160;is the number of balls of color&#160;i.&#160; All the balls will be&#160;shuffled uniformly at random,&#160;then&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/">花花酱 LeetCode 1467. Probability of a Two Boxes Having The Same Number of Distinct Balls</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1467. Probability of a Two Boxes Having The Same Number of Distinct Balls - 刷题找工作 EP332" width="500" height="375" src="https://www.youtube.com/embed/EZS6E6swOsY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given&nbsp;<code>2n</code>&nbsp;balls of&nbsp;<code>k</code>&nbsp;distinct colors. You will be given an integer array&nbsp;<code>balls</code>&nbsp;of size&nbsp;<code>k</code>&nbsp;where&nbsp;<code>balls[i]</code>&nbsp;is the number of balls of color&nbsp;<code>i</code>.&nbsp;</p>



<p>All the balls will be&nbsp;<strong>shuffled uniformly at random</strong>,&nbsp;then we will distribute the first&nbsp;<code>n</code>&nbsp;balls to the first box and the remaining&nbsp;<code>n</code>&nbsp;balls to the other box (Please read the explanation of the second example carefully).</p>



<p>Please note that the two boxes are considered different. For example, if we have two balls of colors&nbsp;<code>a</code>&nbsp;and&nbsp;<code>b</code>, and two boxes&nbsp;<code>[]</code>&nbsp;and&nbsp;<code>()</code>, then the distribution&nbsp;<code>[a] (b)</code>&nbsp;is considered different than the distribution&nbsp;<code>[b] (a)&nbsp;</code>(Please read the explanation of the first&nbsp;example carefully).</p>



<p>We want to&nbsp;<em>calculate the probability</em>&nbsp;that the two boxes have the same number of distinct balls.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [1,1]
<strong>Output:</strong> 1.00000
<strong>Explanation:</strong> Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [2,1,1]
<strong>Output:</strong> 0.66667
<strong>Explanation:</strong> We have the set of balls [1, 1, 2, 3]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equale probability (i.e. 1/12):
[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]
After that we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [1,2,1,2]
<strong>Output:</strong> 0.60000
<strong>Explanation:</strong> The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [3,2,1]
<strong>Output:</strong> 0.30000
<strong>Explanation:</strong> The set of balls is [1, 1, 1, 2, 2, 3]. It is hard to display all the 60 possible random shuffles of this set but it is easy to check that 18 of them will have the same number of distinct colors in each box.
Probability = 18 / 60 = 0.3
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [6,6,6,6,6,6]
<strong>Output:</strong> 0.90327
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= balls.length &lt;= 8</code></li><li><code>1 &lt;= balls[i] &lt;= 6</code></li><li><code>sum(balls)</code>&nbsp;is even.</li><li>Answers within&nbsp;<code>10^-5</code>&nbsp;of the actual value will be accepted as correct.</li></ul>



<h2><strong>Solution 0: Permutation</strong> (<strong>TLE</strong>)</h2>



<p>Enumerate all permutations of the balls, count valid ones and divide that by the total.</p>



<p>Time complexity: O((8*6)!) = O(48!) <br>After deduplication: O(48!/(6!)^8) ~ 1.7e38<br>Space complexity: O(8*6)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, TLE 4/21 passed
class Solution {
public:
  double getProbability(vector&lt;int&gt;&amp; balls) {
    const int k = balls.size();
    vector&lt;int&gt; bs;
    for (int i = 0; i &lt; k; ++i)
      for (int j = 0; j &lt; balls[i]; ++j)
        bs.push_back(i);
    const int n = bs.size();
    double total = 0.0;
    double valid = 0.0;
    // d : depth
    // used : bitmap of bs's usage
    // c1: bitmap of colors of box1
    // c2: bitmap of colors of box1
    function&lt;void(int, long, int, int)&gt; dfs = [&amp;](int d, long used, int c1, int c2) {    
      if (d == n) {          
        total += 1;
        valid += __builtin_popcount(c1) == __builtin_popcount(c2);                
        return;
      }
      for (int i = 0; i &lt; n; ++i) {
        if (used &amp; (1L &lt;&lt; i)) continue;
        // Deduplication.
        if (i &gt; 0 &amp;&amp; bs[i] == bs[i - 1] &amp;&amp; !(used &amp; (1L &lt;&lt; (i - 1)))) continue;        
        int tc1 = (d &lt; n / 2) ? (c1 | (1 &lt;&lt; bs[i])) : c1;
        int tc2 = (d &lt; n / 2) ? c2 : (c2 | (1 &lt;&lt; bs[i]));
        dfs(d + 1, used | (1L &lt;&lt; i), tc1, tc2);
      }
    };
    dfs(0, 0, 0, 0);    
    return valid / total;
  }
};</pre>
</div></div>



<h2><strong>Solution 1: Combination</strong></h2>



<p>For each color, put n_i balls into box1, the left t_i &#8211; n_i balls go to box2.<br>permutations = fact(n//2) / PROD(fact(n_i)) * fact(n//2) * PROD(fact(t_i &#8211; n_i))<br>E.g<br>balls = [1&#215;2, 2&#215;6, 3&#215;4]<br>One possible combination:<br>box1: 1 22 333<br>box2: 1 2222 3<br>permutations = 6! / (1! * 2! * 3!) * 6! / (1! * 4! * 1!) = 1800</p>



<p>Time complexity: O((t+1)^k) = O(7^8)<br>Space complexity: O(k + (t*k)) = O(8 + 48)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  double getProbability(vector&lt;int&gt;&amp; balls) {
    const int n = accumulate(begin(balls), end(balls), 0);
    const int k = balls.size();        
    double total = 0.0;
    double valid = 0.0;
    vector&lt;double&gt; fact(50, 1.0);
    for (int i = 1; i &lt; fact.size(); ++i)
      fact[i] = fact[i - 1] * i;
    // d: depth
    // b1, b2: # of balls in box1, box2
    // c1, c2: # of distinct colors in box1, box2
    // p1, p2: # permutations of duplicate balls in box1, box2
    function&lt;void(int, int, int, int, int, double, double)&gt; dfs = [&amp;]
      (int d, int b1, int b2, int c1, int c2, double p1, double p2) {
      if (b1 &gt; n / 2 || b2 &gt; n / 2) return;
      if (d == k) {
        const double count = fact[b1] / p1 * fact[b2] / p2;
        total += count;
        valid += count * (c1 == c2);
        return;
      }
      for (int s1 = 0; s1 &lt;= balls[d]; ++s1) {
        const int s2 = balls[d] - s1;
        dfs(d + 1,
            b1 + s1, 
            b2 + s2,
            c1 + (s1 &gt; 0), 
            c2 + (s2 &gt; 0), 
            p1 * fact[s1], 
            p2 * fact[s2]);
      }
    };
    dfs(0, 0, 0, 0, 0, 1.0, 1.0);
    return valid / total;
  }
};</pre>
</div></div>



<p>vector version</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  double getProbability(vector&lt;int&gt;&amp; balls) {
    const int k = balls.size();                    
    const int n = accumulate(begin(balls), end(balls), 0);
    vector&lt;double&gt; fact(49, 1.0);
    for (int i = 1; i &lt; fact.size(); ++i)
      fact[i] = fact[i - 1] * i;
    auto perms = [&amp;](const vector&lt;int&gt;&amp; bs, int n) -&gt; double {
      double p = fact[n];
      for (int b : bs) p /= fact[b];        
      return p;
    };
    vector&lt;int&gt; box1, box2;
    function&lt;double(int)&gt; dfs = [&amp;](int d) -&gt; double {
      const int n1 = accumulate(begin(box1), end(box1), 0);
      const int n2 = accumulate(begin(box2), end(box2), 0);
      if (n1 &gt; n / 2 || n2 &gt; n / 2) return 0;
      if (d == k)
        return (box1.size() == box2.size()) * perms(box1, n1) * perms(box2, n2);
      double total = 0;
      for (int s1 = 0; s1 &lt;= balls[d]; ++s1) {
        const int s2 = balls[d] - s1;
        if (s1) box1.push_back(s1);
        if (s2) box2.push_back(s2);
        total += dfs(d + 1);
        if (s1) box1.pop_back();
        if (s2) box2.pop_back();
      }
      return total;
    };
    return dfs(0) / perms(balls, n);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/">花花酱 LeetCode 1467. Probability of a Two Boxes Having The Same Number of Distinct Balls</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1377. Frog Position After T Seconds</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1377-frog-position-after-t-seconds/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1377-frog-position-after-t-seconds/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Mar 2020 19:49:39 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[probability]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6423</guid>

					<description><![CDATA[<p>Given an undirected tree&#160;consisting of&#160;n&#160;vertices numbered from 1 to&#160;n. A frog starts jumping&#160;from the&#160;vertex 1. In one second, the frog&#160;jumps from its&#160;current&#160;vertex to another&#160;unvisited&#160;vertex if&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1377-frog-position-after-t-seconds/">花花酱 LeetCode 1377. Frog Position After T Seconds</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1377. Frog Position After T Seconds - 刷题找工作 EP313" width="500" height="375" src="https://www.youtube.com/embed/B5nDIxkoEyo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an undirected tree&nbsp;consisting of&nbsp;<code>n</code>&nbsp;vertices numbered from 1 to&nbsp;<code>n</code>. A frog starts jumping&nbsp;from the&nbsp;<strong>vertex 1</strong>. In one second, the frog&nbsp;jumps from its&nbsp;current&nbsp;vertex to another&nbsp;<strong>unvisited</strong>&nbsp;vertex if they are directly connected. The frog can not jump back to a visited vertex.&nbsp;In case the frog can jump to several vertices it jumps randomly to one of them with the same probability, otherwise, when the frog can not jump to any unvisited vertex it jumps forever on the same vertex.&nbsp;</p>



<p>The edges of the undirected tree&nbsp;are given in the array&nbsp;<code>edges</code>, where&nbsp;<code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>]</code>&nbsp;means that exists an edge connecting directly the vertices&nbsp;<code>from<sub>i</sub></code>&nbsp;and&nbsp;<code>to<sub>i</sub></code>.</p>



<p><em>Return the probability that after&nbsp;<code>t</code>&nbsp;seconds the frog is on the vertex&nbsp;<code>target</code>.</em></p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/02/20/frog_2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
<strong>Output:</strong> 0.16666666666666666 
<strong>Explanation: </strong>The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after <strong>second 1</strong> and then jumping with 1/2 probability to vertex 4 after <strong>second 2</strong>. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. 
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/02/20/frog_3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
<strong>Output:</strong> 0.3333333333333333
<strong>Explanation: </strong>The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after <strong>second 1</strong>. 
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6
<strong>Output:</strong> 0.16666666666666666
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= n &lt;= 100</code></li><li><code>edges.length == n-1</code></li><li><code>edges[i].length == 2</code></li><li><code>1 &lt;= edges[i][0], edges[i][1] &lt;= n</code></li><li><code>1 &lt;= t&nbsp;&lt;= 50</code></li><li><code>1 &lt;= target&nbsp;&lt;= n</code></li><li>Answers within&nbsp;<code>10^-5</code>&nbsp;of the actual value will be accepted as correct.</li></ul>



<h2><strong>Solution: BFS</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/03/1373-ep313.png" alt="" class="wp-image-6463" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/03/1373-ep313.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/03/1373-ep313-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/03/1373-ep313-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>key: if a node has children, the fog jumps to to children so the probability at current node will become 0.</p>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  double frogPosition(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges, int t, int target) {
    vector&lt;double&gt; p(n + 1);
    p[1] = 1.0;
    vector&lt;vector&lt;int&gt;&gt; g(n + 1);
    for (const auto&amp; e : edges) {
      g[e[0]].push_back(e[1]);
      g[e[1]].push_back(e[0]);
    }
    vector&lt;int&gt; seen(n + 1);
    seen[1] = 1;
    queue&lt;int&gt; q{{1}};
    while (t--) {
      int size = q.size();      
      while (size--) {
        int cur = q.front(); q.pop();
        int children = 0;
        for (int nxt : g[cur])
          if (!seen[nxt]) ++children;
        for (int nxt : g[cur])
          if (!seen[nxt]++) {
            q.push(nxt);
            p[nxt] += p[cur] / children;
          }
        // key: fog jumps this node has children
        if (children &gt; 0) p[cur] = 0.0;
      }
    }
    return p[target];
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Solution:
  def frogPosition(self, n: int, edges: List[List[int]],
                   t: int, target: int) -&amp;gt; float:
    p = [0] + [1] + [0] * (n - 1)
    seen = [False] + [True] + [False] * (n - 1)    
    q = [1]
    g = [[] for _ in range(n + 1)]
    for i, j in edges:
      g[i].append(j)
      g[j].append(i)
    for _ in range(t):
      q2 = []
      for cur in q:
        children = sum([not seen[nxt] for nxt in g[cur]])
        for nxt in g[cur]:
          if seen[nxt]: continue
          seen[nxt] = True
          q2.append(nxt)
          p[nxt] = p[cur] / children
        if children &amp;gt; 0: p[cur] = 0
      q = q2
    return p[target]</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1377-frog-position-after-t-seconds/">花花酱 LeetCode 1377. Frog Position After T Seconds</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-1377-frog-position-after-t-seconds/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 470. Implement Rand10() Using Rand7()</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-470-implement-rand10-using-rand7/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-470-implement-rand10-using-rand7/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 16 Oct 2018 02:35:54 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[probability]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4192</guid>

					<description><![CDATA[<p>Problem Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-470-implement-rand10-using-rand7/">花花酱 LeetCode 470. Implement Rand10() Using Rand7()</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/Wyauxe92JJA?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Given a function <code>rand7</code> which generates a uniform random integer in the range 1 to 7, write a function <code>rand10</code> which generates a uniform random integer in the range 1 to 10.</p>
<p>Do NOT use system&#8217;s <code>Math.random()</code>.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">1</span>
<strong>Output: </strong><span id="example-output-1">[7]</span>
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">2</span>
<strong>Output: </strong><span id="example-output-2">[8,4]</span>
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">3</span>
<strong>Output: </strong><span id="example-output-3">[8,1,10]</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>rand7</code> is predefined.</li>
<li>Each testcase has one argument: <code>n</code>, the number of times that <code>rand10</code> is called.</li>
</ol>
<p><strong>Follow up:</strong></p>
<ol>
<li>What is the <a href="https://en.wikipedia.org/wiki/Expected_value" target="_blank" rel="noopener">expected value</a> for the number of calls to <code>rand7()</code> function?</li>
<li>Could you minimize the number of calls to <code>rand7()</code>?</li>
</ol>
<p><img class="alignnone size-large wp-image-4197" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/10/470-ep226-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/10/470-ep226-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/10/470-ep226-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/10/470-ep226-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-4196" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/10/470-ep226-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/10/470-ep226-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/10/470-ep226-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/10/470-ep226-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution:</strong></h1>
<p>Time complexity: O(1)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int rand10() {
    int index = INT_MAX;
    while (index &gt;= 40)
      index = 7 * (rand7() - 1) + (rand7() - 1);
    return index % 10 + 1;
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-470-implement-rand10-using-rand7/">花花酱 LeetCode 470. Implement Rand10() Using Rand7()</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-470-implement-rand10-using-rand7/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 808. Soup Servings</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-808-soup-servings/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-808-soup-servings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 02 Aug 2018 06:05:32 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3407</guid>

					<description><![CDATA[<p>Problem There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-808-soup-servings/">花花酱 LeetCode 808. Soup Servings</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1>Problem</h1>
<p>There are two types of soup: type A and type B. Initially we have <code>N</code> ml of each type of soup. There are four kinds of operations:</p>
<ol>
<li>Serve 100 ml of soup A and 0 ml of soup B</li>
<li>Serve 75 ml of soup A and 25 ml of soup B</li>
<li>Serve 50 ml of soup A and 50 ml of soup B</li>
<li>Serve 25 ml of soup A and 75 ml of soup B</li>
</ol>
<p>When we serve some soup, we give it to someone and we no longer have it.  Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can.  We stop once we no longer have some quantity of both types of soup.</p>
<p>Note that we do not have the operation where all 100 ml&#8217;s of soup B are used first.</p>
<p>Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.</p>
<pre class="crayon:false "><strong>Example:</strong>
<strong>Input:</strong> N = 50
<strong>Output:</strong> 0.625
<strong>Explanation:</strong> 
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.

</pre>
<p><strong>Notes:</strong></p>
<ul>
<li><code>0 &lt;= N &lt;= 10^9</code>.</li>
<li>Answers within <code>10^-6</code> of the true value will be accepted as correct.</li>
</ul>
<h1><strong>Solution 1: Recursion with Memorization</strong></h1>
<p>Time complexity: O(N^2) N ~ 5000 / 25 = 200</p>
<p>Space complexity: O(N^2)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  double soupServings(int N) {
    if (N &gt;= 5000) return 1.0;
    return prob(N, N);
  }
private:
  unordered_map&lt;int, unordered_map&lt;int, double&gt;&gt; m_;
  double prob(int A, int B) {
    static int ops[][2] = {{100, 0}, {75, 25}, {50, 50}, {25, 75}};
    if (A &lt;= 0 &amp;&amp; B &lt;= 0) return 0.5;
    if (A &lt;= 0) return 1.0;    
    if (B &lt;= 0) return 0.0;
    if (m_.count(A) &amp;&amp; m_[A].count(B)) return m_[A][B];    
    m_[A][B] = 0.0;
    for (int i = 0; i &lt; 4; ++i)
      m_[A][B] += 0.25 * prob(A - ops[i][0], B - ops[i][1]);
    return m_[A][B];
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-808-soup-servings/">花花酱 LeetCode 808. Soup Servings</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-808-soup-servings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 688. Knight Probability in Chessboard</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 02 Oct 2017 06:18:42 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[chess]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[knight]]></category>
		<category><![CDATA[probability]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=515</guid>

					<description><![CDATA[<p>https://leetcode.com/problems/knight-probability-in-chessboard/description/ Problem: On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly Kmoves. The rows and columns are 0 indexed, so&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/">花花酱 688. Knight Probability in Chessboard</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/MyJvMydR2G4?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><a href="https://leetcode.com/problems/knight-probability-in-chessboard/description/">https://leetcode.com/problems/knight-probability-in-chessboard/description/</a></p>
<p><strong>Problem:</strong></p>
<div class="question-description">
<p>On an <code>N</code>x<code>N</code> chessboard, a knight starts at the <code>r</code>-th row and <code>c</code>-th column and attempts to make exactly <code>K</code>moves. The rows and columns are 0 indexed, so the top-left square is <code>(0, 0)</code>, and the bottom-right square is <code>(N-1, N-1)</code>.</p>
<p>A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.</p>
<p><img src="https://leetcode.com/static/images/problemset/knight.png" />Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.</p>
<p>The knight continues moving until it has made exactly <code>K</code> moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">Input: 3, 2, 0, 0
Output: 0.0625
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on 
the board. The total probability the knight stays on the board is 0.0625.</pre><p><b>Note:</b></p>
<ul>
<li><code>N</code> will be between 1 and 25.</li>
<li><code>K</code> will be between 0 and 100.</li>
<li>The knight always initially starts on the board.</li>
</ul>
</div>
<div></div>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<div id="interviewed-div"><strong>Idea:</strong></div>
<div>Dynamic programming</div>
<div>Count the ways to reach (x, y) after k moves from start.</div>
<div></div>
<div></div>
<div><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79.png"><img class="alignnone size-full wp-image-522" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></div>
<div></div>
<div></div>
<div></div>
<div><strong>Time Complexity: </strong>O(k*n^2)</div>
<div></div>
<div><strong>Space Complexity: </strong>O(n^2)</div>
<div></div>
<div><strong>Solution:</strong></div>
<div>
<pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 6 ms
class Solution {
public:
    double knightProbability(int N, int K, int r, int c) {
        vector&lt;vector&lt;double&gt;&gt; dp0(N, vector&lt;double&gt;(N, 0.0));
        dp0[r][c] = 1.0;
        int dirs[8][2] = {{1, 2}, {-1, -2}, {1, -2}, {-1, 2},
                          {2, 1}, {-2, -1}, {2, -1}, {-2, 1}};
        for (int k = 0; k &lt; K; ++k) {            
            vector&lt;vector&lt;double&gt;&gt; dp1(N, vector&lt;double&gt;(N, 0.0));
            for (int i = 0; i &lt; N; ++i)
                for (int j = 0; j &lt; N; ++j) 
                    for (int m = 0; m &lt; 8; ++m) {
                        int x = j + dirs[m][0];
                        int y = i + dirs[m][1];
                        if (x &lt; 0 || y &lt; 0 || x &gt;= N || y &gt;= N) continue;
                        dp1[i][j] += dp0[y][x];
                    }
            std::swap(dp0, dp1);
        }
        
        double total = 0;
        for (int i = 0; i &lt; N; ++i)
            for (int j = 0; j &lt; N; ++j)
                total += dp0[i][j];
        
        return total / pow(8, K);
    }
};</pre>
</div>
<p>&nbsp;</p>
<p><strong>Related problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-62-unique-paths/">[解题报告] LeetCode 62. Unique Paths</a></li>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-63-unique-paths-ii/">[解题报告] LeetCode 63. Unique Paths II</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/">花花酱 688. Knight Probability in Chessboard</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
