<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chris Chen on Medium]]></title>
        <description><![CDATA[Stories by Chris Chen on Medium]]></description>
        <link>https://medium.com/@chris-yn-chen?source=rss-321a4333be6d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*laeuBjXBsBPqZW4I8NetZg.png</url>
            <title>Stories by Chris Chen on Medium</title>
            <link>https://medium.com/@chris-yn-chen?source=rss-321a4333be6d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 23:02:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chris-yn-chen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Difference Array]]></title>
            <link>https://chris-yn-chen.medium.com/difference-array-a8f42f84f075?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8f42f84f075</guid>
            <category><![CDATA[difference-array]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[prefix-sum]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 12:39:37 GMT</pubDate>
            <atom:updated>2025-01-17T12:53:52.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_zGIHNGU_wTALDvT" /><figcaption>Photo by <a href="https://unsplash.com/@pastorthomasbwilson?utm_source=medium&amp;utm_medium=referral">Tom Wilson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Range update algorithm</p><p>Before we start to introduce the difference array. Please make sure you already know what is the prefix sum.</p><p>Ready? Let’s see one problem. If we want to do some range updates queries in an array A. How can we do that?</p><p>For example:</p><p>Let’s say we have an array A= [2,1,5,4,3]. And we have updates query= [[0, 2, 1], [2,4,-2]]. For each query[i] length is 3.<br>query[i][0] = range start (inclusive)<br>query[i][1] = range end (inclusive)<br>query[i][2] = increased value</p><p>The intuitive way that comes to mind is by using the brute force method to update all the range values. Brute force will look like:</p><pre>for(int[] e: query) {<br>  int start = e[0];<br>  int end = e[1];<br>  int increasedValue = e[2];<br>  for(int i = start; i &lt;= end; i++) {<br>    A[i] += increasedValue;<br>  }<br>}</pre><p>Finally get the result [3,2,4,2,1]. But this will take O(m * n) time complexity. (m is the size of query, n is the size of A) Which is okay, but do we have an efficient way to fix that?</p><p>So for this problem, we can utilize a difference array + prefix sum to help us implement with O(m + n) time complexity.</p><p>Before we solve the problem let’s define the difference array. Assume D[0] = A[0], for any of i &gt; 0, D[i] = A[i] - A[i - 1]. So for the original array A= [2,1,5,4,3], we can get the difference array D = [2,-1,4,-1,-1].</p><p>If we try to see the prefix sum of array D. We can obviously get <br>prefixSum(D) = A. Why? Because</p><pre>D[0] = A[0]<br>D[1] = A[1] - A[0]<br>D[2] = A[2] - A[1]<br>D[3] = A[3] - A[2]<br>D[4] = A[4] - A[3]<br><br>prefix sum array<br>P[0] = D[0] = A[0]<br>P[1] = D[0] + D[1] = A[0] + A[1] - A[0] = A[1]<br>P[2] = D[0] + D[1] + D[2] = A[1] + A[2] - A[1] = A[2]<br>P[3] = D[0] + D[1] + D[2] + D[3] = A[2] + A[3] - A[2] = A[3]<br>P[4] = D[0] + D[1] + D[2] + D[3] + D[4] = A[3] + A[4] - A[3] = A[4]</pre><p>If we need mathematical proof:</p><pre>P[i] = P[i - 1] + A[i] =&gt; A[i] = P[i] - P[i - 1]<br>D[i] = A[i] - A[i - 1] =&gt; A[i] = D[i] + A[i - 1]<br>So we can get:<br>P[i] - P[i - 1] = D[i] + A[i - 1] = A[i]</pre><p>This means prefixSum(D) = D(prefixSum) = A. After we get this result we can go back to the original problem.</p><p>A= [2,1,5,4,3], updates query= [[0, 2, 1], [2,4,-2]]<br>And our D = [2,-1,4,-1,-1] for each query we try to plus the start point and minus the end + 1 point.</p><p>query [0, 2, 1] =&gt; D = [3,-1,4,-2,-1] then continue with other query<br>query [2, 4, -2] =&gt; D = [3,-1,2,-2,-1]</p><p>After we get the result D we try to get its prefix sum P = [3,2,4,2,1]. And this result is the same as the brute force one. But actually, we only take O(m + n) time complexity 🎉.</p><p>In this case, we know the difference array is cool for some interval update cases. You can also find some LC problems related to that.</p><p>LC Reference:<br><a href="https://leetcode.com/problems/shifting-letters-ii/description/">https://leetcode.com/problems/shifting-letters-ii</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8f42f84f075" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode Matrix Questions]]></title>
            <link>https://chris-yn-chen.medium.com/leetcode-matrix-questions-7ce9af8efa2c?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ce9af8efa2c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[matrix]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[binary-search]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Sat, 24 Sep 2022 14:07:27 GMT</pubDate>
            <atom:updated>2022-09-24T14:07:27.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ONGJA6uqvitin4pU" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Matrix Search Question:</h3><p>Classic matrix search is these two questions:</p><ol><li><a href="https://leetcode.com/problems/search-a-2d-matrix/">https://leetcode.com/problems/search-a-2d-matrix/</a></li><li><a href="https://leetcode.com/problems/search-a-2d-matrix-ii/">https://leetcode.com/problems/search-a-2d-matrix-ii/</a></li></ol><h4>First case</h4><p>If the matrix is sorted like this:</p><pre>[1,2,3]<br>[4,5,6]<br>[7,8,9]<br>Target: 3</pre><p>Above case, the last element will be less than the next line&#39;s first element.<br>We can easily flatten the matrix to 1D, then use binary search solution.</p><pre>[1,2,3,4,5,6,7,8,9], Target: 3</pre><p>The solution will be like this:</p><pre>    public boolean searchMatrix(int[][] matrix, int target) {<br>        int m = matrix.length;<br>        int n = matrix[0].length;<br>        int l = 0;<br>        int r = m * n - 1;<br>        while(l &lt;= r) {<br>            int mid = l + r &gt;&gt; 1;<br>            <br>            int row = mid / n;<br>            int column = mid % n;<br>            <br>            if(matrix[row][column] == target) {<br>                return true;<br>            } else if(matrix[row][column] &gt; target) {<br>                r = mid - 1;<br>            } else {<br>                l = mid + 1;<br>            }<br>        }<br>        return false;<br>    }</pre><p>Total time complexity will be O(log(m * n)), space complexity will be O(1)</p><h4>Second case</h4><p>If the matrix is sorted like this:</p><pre>[1,4,7]<br>[2,5,8]<br>[3,6,9]<br>Target: 3</pre><p>Above case, the ith element is only ensured sorted by its row and column. We have an idea to start searching at the top right corner or left bottom corner. Why these two corners? Because we need compare.</p><p>Look at the below pic. We start from the top right corner 7 and we want to find 3. Because 7 &gt; 3so we know the bottom side elements are also larger than 3. So next step we should keep finding from the left. Alternatively, we finding from the bottom. We keep searching in the same way. Finally, we can find the element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*rTSOZuG4bgcXLZrjy63m8g.png" /></figure><p>The solution will be like this:</p><pre>    public boolean searchMatrix(int[][] matrix, int target) {<br>        int m = matrix.length;<br>        int n = matrix[0].length;<br>        <br>        int i = 0;<br>        int j = n - 1;<br>        while(i &lt; m &amp;&amp; j &gt;= 0) {<br>            if(matrix[i][j] == target) {<br>                return true;<br>            } else if(matrix[i][j] &gt; target) {<br>                j--;<br>            } else {<br>                i++;<br>            }<br>        }<br>        return false;<br>    }</pre><p>Total time complexity will be O(m +n), space complexity will be O(1)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ce9af8efa2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[國外Software Engineer 面試經驗分享]]></title>
            <link>https://chris-yn-chen.medium.com/%E5%9C%8B%E5%A4%96software-engineer-%E9%9D%A2%E8%A9%A6%E7%B6%93%E9%A9%97%E5%88%86%E4%BA%AB-86c5e6675180?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/86c5e6675180</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[tiktok-app]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[japan]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Fri, 12 Aug 2022 07:11:24 GMT</pubDate>
            <atom:updated>2022-08-21T15:02:51.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8pRdog1JgdLhYoP0" /><figcaption>Photo by <a href="https://unsplash.com/@jezar?utm_source=medium&amp;utm_medium=referral">Jezael Melgoza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>背景: 119 統計碩士，6年android開發經驗、2年flutter開發經驗</p><p>當初為什麼會想要到國外工作的動機 大概有以下幾點：</p><ul><li>人生有限 想體驗不同的生活</li><li>國外薪資以及薪資的天花板比台灣高</li><li>想讓家人小孩有不同的眼界 會不同的語言</li></ul><p>因為上述的一些原因，我開始面試一些國外的公司，在這之中有先取得新加坡Tiktok的offer，後來和家人、朋友們溝通發現，原來我們並不想移居新加坡。在經過這次的教訓，有了無數次的溝通後跟我老婆取得共識，考慮到語言、文化、安全、小孩的未來、離家鄉遠近…等等因素，我們選了日本當作我們的第一移居目標。</p><p>以下是我在2021 2022的面試結果：</p><p>Reject: Meta, Automattic, Amazon, Booyah</p><p>Offer Get: Tiktok , Woven Planet, Mercari</p><h3>Automattic</h3><p>會投這間公司是因為看到ptt soft job版上的分享，感覺是一間很有趣的公司，我比較有聽過的產品是WroldPress和Tumblr，公司是完全可以full remote爾且薪資算是global pay所以我想說嘗試看看。第一關面試是完全在slack 上text-only chat. 不過第一關完就收到感謝信了QQ</p><p>結果：Reject</p><h3>Meta</h3><p>Meta是請朋友幫忙投的，有聽說他們現在非常挑人，我都還沒面就直接收到了感謝函，希望以後還有機會再挑戰看看。</p><p>結果：Reject</p><h3>Amazon</h3><p>5關以上的面試</p><ul><li>OA + BQ(Hacker rank)</li><li>phone interview (1題DS + Algorithm + BQ)</li></ul><p>Amazon是面試台灣的Amazon Device, Ring這個team. 主要是做IOT相關的App. OA的部分中規中矩出了兩題medium左右的題目，個人覺得並不難但是他的BQ題目很多，所以建議如果有要準備關於Amazon的principle可能要看一下。Phone interview會針對你過去經驗問一些BQ相關的問題，另外還會有一題演算法面試，面試官出了一題Medium ~ Hard左右非常有意思的題目，雖然我最後有解出來但也是他給了提示才完成，最後知道自己能力不足也收到了感謝信。</p><p>結果：Reject</p><h3>Booyah</h3><p>這間公司是SEA旗下的一間子公司，同集團最有名的是蝦皮。因為朋友找了我想說剛好都準備了就試試看，4關+以上的面試：</p><ul><li>OA (1題LC medium左右的題目+一些android知識題)</li><li>Tech interview1 (主要是問Android相關的問題)</li><li>Tech interview2 (主要是問Android相關的問題，另外考了一題演算法 Tree的題目)</li><li>Manager interview3 (Android相關的問題，Sysem design)</li></ul><p>Booyah考的Android題目蠻刁鑽的，會針對你的回答往更更更深的地方問，所以如果有Android BSP或是framework相關的經驗可能會比較吃香。</p><p>結果：Reject</p><h3>Tiktok</h3><p>4關面試:</p><ul><li>1st Tech interview (2題DS + Algorithm )</li><li>2nd Tech interview (System design + 1題DS + Algorithm )</li><li>Manager interview (BQ + System design)</li><li>HR Behavior interview</li></ul><p>演算法的部分中規中矩大概是Leetcode medium的程度，System design主要也試考front-end的部分沒有涉及到backend的design，Manager interview中的system design倒是被問了個有趣的問題，如何implement 同user但有多重身份的登入。</p><p>這是新加坡的Fundenmental team 的Android缺，其實非常的吸引我，他的TC組合是base + bonus + shares，但我本人對share這種未來的東西不是看好且因為base低於我的預期，再加上家人沒有意願移居新加坡後放棄。</p><p>結果：Offer Get</p><h3>Woven Planet</h3><p>這是Toyota的子公司，主要負責自動駕駛、Smart City等等的開發，我面的職位是Smart City中的Super App team，這是一個新的team且App是用flutter寫的，剛好我有2年的flutter經驗可能有加分。一共有6關面試:</p><ul><li>Assignment</li><li>1st Tech interview (DS + Algorithm)</li><li>2nd Tech interview (System Design)</li><li>Behavior interview (BQ)</li><li>Cross function interview</li><li>Manager interview</li></ul><p>整個面試拖超~級~久的，第一關的tech面試 easy左右的題目 簡單到我不可置信，也沒有follow-up，整個面試大概15分鐘內就結束。Cross function interview是一個ex-Googler大叔，問了一些像是tree 的traversal, update 的TC, 怎麼balance tree 另外還有 Oauth等等的問題，因為大叔感覺是web背景的我被問這些回答得並不是很好。最後在等待結果前有在被要求加面一次感覺也是偏system design的interview，裡面就有問到怎麼設計一個service 要從FE/BE的角度都分析。</p><p>結果：Offer Get</p><h3>Mercari</h3><p>其實Mercari我以前就面過了，面試一共6關:</p><ul><li>OA(Hacker Rank)</li><li>Phone Screen</li><li>CS interview</li><li>Android Pair Programming interview</li><li>Manager interview</li><li>Director interview</li></ul><p>CS interview 我記得是考了一個linkedlist的問題，那個題目並沒有很難只是我把他往難的地方去想，最後給了一個reverse的解，後來他跟我再次澄清題目後我改用Set 去check object reference解了出來，一個大概只要5分鐘內解決的問題我想太複雜搞了30分鐘QQ。Android的面試官是兩位Tech Lead，他事先會給你有問題的code，最好可以先想好怎麼refactor來符合clean architecture的原則。Director interview我似乎有地方沒有答的很好，這部分最後有影響到我拿到offer的level。值得一提的是招募的TA是一個台灣人，非常好的一位大哥，Mercari也是full remote，所以你可以在日本任何一個角落工作不需要去公司。</p><p>結果：Offer Get</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86c5e6675180" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 858. Mirror Reflection]]></title>
            <link>https://chris-yn-chen.medium.com/leetcode-858-mirror-reflection-feddf8bab18d?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/feddf8bab18d</guid>
            <category><![CDATA[mirror]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 14:54:59 GMT</pubDate>
            <atom:updated>2022-08-11T08:42:51.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IwtjxkKiKIqoL5Z4" /><figcaption>Photo by <a href="https://unsplash.com/@josemreyes?utm_source=medium&amp;utm_medium=referral">José M. Reyes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Question:</strong></p><p>There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.</p><p>The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.</p><p>Given the two integers p and q, return the number of the receptor that the ray meets first.</p><p>The test cases are guaranteed so that the ray will meet a receptor eventually.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/0*ySiVJ1PE9PzXfMkF.png" /></figure><pre><strong>Input:</strong> p = 2, q = 1<br><strong>Output:</strong> 2<br><strong>Explanation:</strong> The ray meets receptor 2 the first time it gets reflected back to the left wall.</pre><p><strong>Example 2:</strong></p><pre><strong>Input:</strong> p = 3, q = 1<br><strong>Output:</strong> 1</pre><p>This is an interesting question. When first time I came to this question I thought “WTF, this couldn’t possibly occurs in an interview.” After I understand this question. This question need to uses a really tricky way to solve the problem - <strong>Mirror extension</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*W57szwRPnCpff8Xt88omeA.png" /><figcaption>mirror extension</figcaption></figure><p>We can imagine if the reflection can get through the mirror from the top. Assume after ntimes reflection it will meet the point 0 or 1 or 2. And in this case, it will use m squares. So we can get an equation m * p = n * q . So that meet point will be on the least common multiple(LCM) of p and q.</p><p>When n is odd which means the reflection will be on the right side. So it will only possible be meet 0 or 1 , alternatively, it will be 2</p><p>m is means the total square number. So when m is odd it meets on the top so will be 1 or 2 , alternatively, it will be 0</p><p>And how to get the lcm we need to know one of the important things is :</p><pre>lcm * gcd = p * q<br>//gcd = greratest common divisor</pre><p>So the whole code snipped will be something like:</p><pre>public int mirrorReflection(int p, int q) {<br>        int gcd = p;<br>        int tq = q;<br>        while(tq &gt; 0) {<br>            int temp = gcd % tq;<br>            gcd = tq;<br>            tq = temp;<br>        }<br>        //note1: lcm = mp = nq<br>        //note2: lcm * gcd = p * q</pre><pre>        int lcm = p * q / gcd;<br>        int m = lcm / p;<br>        int n = lcm / q;<br>        <br>        if(n % 2 == 0) {<br>            return 2;<br>        } else if(m % 2 == 0) {<br>            return 0;<br>        } else {<br>            return 1;<br>        }<br>}</pre><p>The problem is not to test your programming. But it’s a kind of test your math. Hopefully this article can help you to understand this question.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feddf8bab18d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apply FlatBuffer in Flutter]]></title>
            <link>https://chris-yn-chen.medium.com/apply-flatbuffer-in-flutter-8f9c25d0d97?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f9c25d0d97</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[flatbuffers]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 13:04:51 GMT</pubDate>
            <atom:updated>2022-07-27T13:28:46.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V38l4hUDTvJBYsy7" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As I already introduce the Flatbuffer <a href="https://chris-yn-chen.medium.com/apply-flatbuffer-in-android-3f74ba087ba3">here</a></p><p>This article will focus on how to implement it for Flutter.</p><h3>Step by Step</h3><p>Here are some step for how you apply Flatbuffer to your flutter app.</p><h3>1. need to install the <a href="https://cmake.org/">cmake</a></h3><pre>&gt; brew install cmake</pre><h3>2. setup the FlatBuffer</h3><p>Clone flatbuffer project via <a href="https://github.com/google/flatbuffers">github</a></p><p>Then we need to compile</p><pre>&gt; cmake -G &quot;Unix Makefiles&quot; -DCMAKE_BUILD_TYPE=Release</pre><p>under project and run <strong>make</strong></p><pre>&gt; make<br>[ 36%] Built target flatc[ 48%] Built target flatsampletext[ 70%] Built target flattests[ 75%] Built target flatsamplebinary[ 88%] Built target flatsamplebfbs[ 91%] Built target flathash[100%] Built target flatbuffers</pre><p>or do alternatively simply way (I suggest use this)</p><pre>&gt; brew install flatbuffers</pre><p>can add alias for flatc CLI (Optional)</p><pre>#flatbuffer CLIalias flatc=your_local_repo_path/flatbuffers/flatc</pre><p>Then can use <strong>flatc</strong></p><h3>3. Write a schema</h3><p>Can refer to <a href="https://google.github.io/flatbuffers/md__schemas.html">here</a>. This only write once can apply to all platform.</p><p>Let’s say we have a schema in JSON like below:</p><pre>{<br>  &quot;name&quot;: &quot;Charles&quot;,<br>  &quot;bloodVolume&quot;: 2,<br>  &quot;speed&quot;: 110.5,<br>  &quot;canFly&quot;: false,<br>  &quot;bag&quot;: {<br>    &quot;name&quot;: &quot;small bag&quot;,<br>    &quot;capacity&quot;: 100<br>  },<br>  &quot;weapons&quot;: [<br>    {<br>      &quot;name&quot;: &quot;axe&quot;,<br>      &quot;damage&quot;: 100<br>    },<br>    {<br>      &quot;name&quot;: &quot;gun&quot;,<br>      &quot;damage&quot;: 500<br>    }<br>  ],<br>  &quot;accessories&quot;: [<br>    &quot;T-shirt&quot;,<br>    &quot;pants&quot;<br>  ]<br>}</pre><p>So the <strong>Person.fbs</strong> will look like:</p><pre>namespace your.target.package;</pre><pre>table Person {<br>    name: string;<br>    bloodVolume: int;<br>    speed: double;<br>    canFly: bool;<br>    bag: Bag;<br>    weapons: [Weapon];<br>    accessories: [string];<br>}</pre><pre>table Weapon {<br>    name: string;<br>    damage: int;<br>}</pre><pre>table Bag {<br>    name: string;<br>    capacity: short;<br>}</pre><pre>root_type Person;</pre><p>Then we can generate dart classes for tables/structs</p><pre>//be careful your path<br>&gt; flatc -o lib --dart person.fbs</pre><p>Then everything is done.</p><h3>Testing</h3><p>If we want to test on this only in app. We can create personinjson.json in assets.</p><p>Then we can generate the json in binary file.</p><pre>//be careful your path<br>&gt; flatc --binary person.fbs ../assets/personinjson.json</pre><p>Then we can compare the JSON file and binary. The binary size is less than JSON file around 30% in general case.</p><h3>Conclusion</h3><p>As you can see the flatbuffer first parse + access time is a bit lower than json. And then it will always be better than json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_swIPuLcORBQO5n4V3TexA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtBZ3Zchcz7azqRt0ii9aQ.png" /><figcaption>First and Second run</figcaption></figure><p>The full example is <a href="https://github.com/chrisynchen/flatbuffer_flutter_example">here</a>. Enjoy it 😆</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f9c25d0d97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[持有工作簽證台灣 ✈️ 日本經驗分享]]></title>
            <link>https://chris-yn-chen.medium.com/%E6%8C%81%E6%9C%89%E5%B7%A5%E4%BD%9C%E7%B0%BD%E8%AD%89%E5%8F%B0%E7%81%A3-%EF%B8%8F-%E6%97%A5%E6%9C%AC%E7%B6%93%E9%A9%97%E5%88%86%E4%BA%AB-150255688024?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/150255688024</guid>
            <category><![CDATA[visa]]></category>
            <category><![CDATA[work]]></category>
            <category><![CDATA[taiwan]]></category>
            <category><![CDATA[japan]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 10:17:30 GMT</pubDate>
            <atom:updated>2023-09-06T15:02:11.101Z</atom:updated>
            <content:encoded><![CDATA[<p>這是小弟我持工作簽證從台灣 ✈️ 日本經驗分享 希望能幫助到有需要的朋友</p><h3>機場入境</h3><p>(Update: 2023年已經不需要PCR及疫苗証明嘍，以下當紀錄參考就好)<br>現在入境日本最好是打滿3劑疫苗(打滿3劑不需要隔離)，且需要72小時內的PCR證明，<a href="https://www.koryu.or.jp/tw/about/taipei/news/?itemid=2281&amp;dispmid=6255">PCR需要日本的格式</a>，最好是提早預約不然當天領的費用會高很多，入境日本的前置作業需要下載以下App：</p><ul><li>MYSOS App</li><li>COCOA App</li><li>Google Map</li></ul><p>裡面最重要的就是MYSOS App了，在飛機上你會拿到入境卡還有另外兩份文件需要填寫，如果你有MYSOS App其實你不需要那填那2份文件因為他只會看你的MYSOS App，<a href="https://www.ptt.cc/bbs/JapanStudy/M.1647321884.A.B13.html">ptt</a>有鄉民也列出了詳細的操作方式，但其實重點就是要把MYSOS弄成綠燈，這樣會大幅增加你在日本過關的速度。</p><p>跑圖跑完前面那大概10幾關大概會花1個多小時，整個過程很冗長且中間還會測一次PCR等結果，之後到海關會確認你護照上的VISA和COE之後發在留卡，這個就是你在日本的身分證，之後還需要去區役所辦理居住登記。</p><h3>居住登記</h3><p>區役所辦理居住登記需要帶以下文件：</p><ul><li>護照</li><li>在留卡</li><li>你當前住的地方的證明(如果是hotel可以跟他要)</li></ul><p>辦完區役所的居住登記後他會在你的在留卡背面填上你當前住的地址，之後就可以辦理日本的門號，門號蠻多種的可以先做一下功課看哪一種適合你，銀行卡則要等到你入職後才能開始辦。</p><h3>手機SIM選擇</h3><p>辦理手機門號需要的證件如下：</p><ul><li>在留卡</li><li>護照</li></ul><p>手機SIM的選擇百百種，主要還是看你的需求：</p><ul><li>每月大約用多少G流量</li><li>是不是需要頻繁通話</li><li>主要使用網路是不是line app或是其他社群軟體</li></ul><p>有些比較特別的像linemo就要在網路上辦，以我自己的case 因為不會講日文所以完全不需要手機通話只需要和家人用line保持聯繫所以linemo比較符合我的需求。</p><h3>銀行帳戶選擇</h3><p>銀行選擇Agent給我的選擇不多只有下面兩種，原因也是只有這兩家支援英語：</p><ul><li><a href="https://www.shinseibank.com/english/">Shinsei Bank</a></li><li><a href="https://www.smbctb.co.jp/en/index.html">SMBC Trust Bank (Prestia)</a></li></ul><p>到銀行完全不需要存錢就可以開戶，但要開戶需要以下的條件：</p><ul><li>要有個人日本手機號碼 (不能用公司的)</li><li>住民卡</li><li>護照</li><li>Certificate of employment (公司給的)</li><li>Certificate of residence (市or區役所給的)</li></ul><p>有些銀行對於外國人開戶相對不友善，所以建議可以先查看看。開戶完成後大約會需要1週的時間才會收到卡片。日本的ATM在便利商店不管是存錢或是領錢都蠻方便的。</p><h3>租屋攻略</h3><p>在日本租屋有蠻多細節需要注意的，可以列出自己的需求，日本租房的term是用房間數+Living room + Dining room + Kitchen，所以常常會看到像是1K、2DK、3LDK等等的字眼，根據自己的需求來決定你想找要什麼樣的房子，以下可以先列出自己的需求</p><ul><li>想要住哪一區</li><li>有幾位要住</li><li>要租1K? 1DK? 1LDK? 2LDK?</li><li>Apartment? マンション? 還是house?</li><li>你的budget上下限</li><li>想要租多大</li><li>希望的屋齡在多久內</li><li>可不可以接受榻榻米房間</li><li>走路去metro希望在幾分鐘內</li><li>到公司的總通勤時間希望在幾分鐘內</li></ul><p>想要住在哪一區這件事可以先從你的上班地點開始著手，看看你的上班地點是在哪條線上降低轉車率去找同一線的站點當作租房的考慮區域。另外還有一些需求像是離學校、超市近一些，或是希望住的樓層…等等，都可以跟Agent討論。</p><p>根據自身的經驗是不要太依賴Agent，因為他們通常根據你的條件給出的屋件都很少，再來你也不一定會滿意，所以比較推薦是自己去<a href="https://suumo.jp/">suumo</a>或是其他相關的網站上查詢看看，之後問Agent能不能請他幫忙問問屋主，因為即使你看上的屋件不是你的Agent公司負責，實際上Agent公司之間也會互相合作。</p><h3>申辦網路</h3><p>日本的網路source大部分來自NTT，在租屋入住之前最好先與Agent確認好使用的線路及如何使用，我本身是入住後才開始申辦所以多花了一些時間。我個人的經驗是用Softbank 光，他會先寄一個暫時可用的Wifi(個人猜應該是吃5g網路)，工事是看你住的地方有沒有需要，日本的Router不像台灣，接好線後需要設定連接你使用的廠商提供的帳密才可以上網，這點是比較麻煩的。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=150255688024" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[辦理日本工作簽證經驗分享]]></title>
            <link>https://chris-yn-chen.medium.com/%E8%BE%A6%E7%90%86%E6%97%A5%E6%9C%AC%E5%B7%A5%E4%BD%9C%E7%B0%BD%E8%AD%89%E7%B6%93%E9%A9%97%E5%88%86%E4%BA%AB-e2da5e36eef0?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2da5e36eef0</guid>
            <category><![CDATA[passport]]></category>
            <category><![CDATA[visa]]></category>
            <category><![CDATA[japan]]></category>
            <category><![CDATA[work]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 08:32:30 GMT</pubDate>
            <atom:updated>2022-03-03T08:42:02.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c9L9pLSfWXRO_wMu" /><figcaption>Photo by <a href="https://unsplash.com/@natallmighty?utm_source=medium&amp;utm_medium=referral">Natali Quijano</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>這篇文章是關於辦理日本工作簽證流程以及經驗分享，在開始說明流程之前我們先看看簽證的定義是什麼:</p><blockquote>簽證（英語：Visa，源自拉丁語：charta visa，意為必須看到的檔案）是一個國家或地區的行政機關在非本國或地區的公民所持的護照或其他旅行證件上的簽注、蓋印、附文（如另紙簽証），以示允許其出入本國國境（或者經過其國境前往第三國）的手續。一國政府會對另一國家的公民推出簽証優惠政策，有時是單方面的，以便於進行人員交流。</blockquote><h3>辦理Visa流程</h3><p>以我自己本身的經驗，剛好碰到Covid所以辦理Visa的時間比較長，以下我分享一下基本的流程:</p><ol><li>算高度人才簽證(HSP)積分 決定要辦哪一種Visa</li><li>辦理在留資格認定證明書 (COE)</li><li>辦理Certificate for Completion of Registration to the ERFS (受付済証)</li><li>帶齊文件去日本台灣交流協會辦理Visa</li></ol><h3><strong>在留資格認定證明書 (COE)</strong></h3><p>不管你是公司外派或是在拿到日本公司的Offer後，就會有人開始接洽你整個Relocation&amp;辦Visa的流程，在辦Visa之前最重要的就是要取得 — <strong>在留資格認定證明書Certificate of Eligibility (以下簡稱 COE)</strong></p><p>依照COE的不同可以分為兩種:</p><ul><li>標準工作簽證 (Engineer/Specialist in Humanities/International service’ status of residence)</li><li><a href="https://www.isa.go.jp/en/publications/materials/newimmiact_3_index.html">高度人才簽證</a> (Highly-Skilled Professional’ status of residence 以下簡稱HSP)</li></ul><p>以下針對兩種不同的COE稍做說明，因為我自己是辦HSP所以對這個流程會比較詳細一些。</p><h3>標準工作簽證:</h3><p>再留期間: 3個月/1年/3年/5年<br>申請時間: 將所有申請文件提交給移民局後，大約需要2到3個月的時間進行審查。因此，包括準備在內的整個程序週期約為3至4個月。</p><h3>高度人才簽證(HSP):</h3><p>高度人才簽證是日本政府從2012年5月7日開始針對吸引國外的高級專業人才來日本工作居留所設立的簽證。根據日本出入國在留管理廳準備的積分計算表，根據申請人的教育和專業背景、收入和學業成績等等給予積分，如果申請人能證明總積分獲得70分或以上，則給予此特殊居留身份。</p><p>再留期間: 5年<br>申請時間: 將所有申請文件提交給移民局後，大約需要 2 至 3 週的時間進行審查。因此，包括準備在內的整個程序週期約為1.5個月至2個月。</p><p>優勢:</p><ul><li>為了獲得永住許可，外國人必須在日本逗留 10 年以上。但是，對於拿到高度人才簽證的外國專業人士，總分70分的只需要3年，或者總分80分以上的只需要1年就可以申請永住許可。</li><li>優先處理簽證程序（COE申請、簽證狀態變更、續簽等）</li><li>在留期限為5年</li><li>在特定條件下可聘請家庭傭工/保姆</li><li>在一定條件下可以帶父母來日本</li><li>拿到HSP的人的配偶在某些條件下也可以全職工作</li></ul><p>注意事項: <br>與標準工作簽證不同，HSP簽證與公司綁定。因此如果一但離職，必須適當地申請更改在留資格，即使當前身份距離到期日還有一定的時間。例如:轉為由其他公司贊助的另一個 HSP…等等</p><p>積分估算表:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0MeJhgzsTkuLqCt1tz-Zjg.png" /><figcaption>Photo on <a href="https://www.isa.go.jp/common/uploads/pub-291_01.pdf">here</a></figcaption></figure><p>文件準備:</p><ul><li>Hearing sheet for working visa</li><li><a href="https://www.isa.go.jp/en/applications/guide/photo_info.html">3個月內的證件照</a></li><li>護照copy</li><li>簡單自介</li><li>畢業證書英文</li><li>HSP 積分計算表</li><li>工作證明</li><li>JLPT日文檢定證明</li></ul><p>上面看起來很多，但實際上主要就是根據你的HSP積分表勾了哪些項目 要提供相對應的證明給他，準備好文件給Agent後，對於申請者整個COE的流程就算跑完。之後申請下來後Agent會用DHL寄到你當初留的地址。</p><h3>Certificate for Completion of Registration to the ERFS (受付済証)</h3><p><a href="https://entry.hco.mhlw.go.jp/">受付済証</a>這是2022/3/1日本發布的入境政策，因為Covid疫情肆虐，對外開放留學＆工作簽證的話，政府需要追蹤外國人的健康狀態。這部分是由雇主或Agent幫忙申請的，我們只需要等待拿到受付済証。</p><h3>Visa申請</h3><p>Visa 申請需要的文件如下:</p><ul><li><a href="https://www.mofa.go.jp/mofaj/toko/visa/pdfs/application1_c2.pdf">簽證申請書</a>（須貼上６個月內拍攝之證件照）</li><li>護照正本及影本</li><li>身分證（第三國申請者為台灣居留證）正本及正反面影本</li><li>在留資格認定證明書(COE)之正本及正反面影本<br>（自發行日起算，若已超過３個月者，必需再提交擔保機關所製作之說明書）</li><li>受付済証影本</li></ul><p>準備好以上的東西就算完成了。以下還有一些Tips是我自己辦理的經驗大家可以參考一下。</p><ol><li>簽證申請書不能用擦擦筆寫</li><li>簽證申請後要隔一週才能拿，工本費 $830元</li><li>寫錯的可以用修正液或直接劃掉改</li><li>工作那欄要寫在台當前的工作 沒有就寫無</li><li>開始和結束日期要寫 天數也要寫 (天數例如是1825天 也就是高度人才簽限制5年)</li><li>班機不確定就寫未定</li></ol><p>要辦理簽證的當天建議是早上早點去(最好是9點開門就到)，主要是去日本留學或工作的人挺多的，承辦人要核對他所有的文件和資格，所以光處理一個人就很花時間。如果你有打算去日本工作，希望這篇文章對你有些幫助，留下個 👏 給我點支持鼓勵吧!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2da5e36eef0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monotonic Stack]]></title>
            <link>https://chris-yn-chen.medium.com/monotonic-stack-639ddf4a4e09?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/639ddf4a4e09</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[monotonic-stack]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 17:38:11 GMT</pubDate>
            <atom:updated>2022-02-14T06:22:56.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DBp34bHcf9Z1jwRm" /><figcaption>Photo by <a href="https://unsplash.com/@holly_buildalifeyoulove?utm_source=medium&amp;utm_medium=referral">Holly Stratton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is monotonic Stack</h3><p>Monotonic stack just like normal stack support push/pop/peek function. And for the element is increasing/decreasing in the stack. Before we push a new element onto the stack, we need to pop the top element off the stack until pushing the new element no longer breaks the monotonic condition.</p><h3>Why need Monotonic Stack?</h3><p>The purpose of a Monotonic stack is to solve problems like: If you want to find the next greater, previous greater, next less, previous less number in an array.</p><p>We can assume the result will be -1 if we cannot find the one. Give an Example: [3,2,7,4] <br>The previous greater element (PGE) for each element will be: <strong>[-1,3,-1,7]</strong><br>The next greater element (NGE) for each element will be: <strong>[7,7,-1,-1]</strong><br>The previous less element (PLE) for each element will be: <strong>[-1,-1,2,2]</strong><br>The next less element (NLE) for each element will be: <strong>[2,-1,4,-1]</strong></p><p>If we need to fix the above problem we can use stack to fix it. How can we solve the problem in O(n) time complexity? We need Monotonic Stack help.</p><p>There are two types of Monotonic stacks:<br>1) Increased Monotonic Stack<br>2) Decreased Monotonic Stack</p><h3>Examples:</h3><ul><li><a href="https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/">1475. Final Prices With a Special Discount in a Shop</a></li></ul><p>In this case, we need to find the next less element (NLE). It’s pretty easy to come out with a brute force solution. But it will need nested loops and takes O(n²) to find out the next less number for each of the prices[i].</p><p>We can use a simple data structure to help us to reduce the total time complexity. Let’s try increased Monotonic Stack.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80696eb47d9da8884eda3eb6bae3b7d2/href">https://medium.com/media/80696eb47d9da8884eda3eb6bae3b7d2/href</a></iframe><p>If we want to find the previous less element (PLE) we can simply modify the logic to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/876e996661e1566733123c931b3417c6/href">https://medium.com/media/876e996661e1566733123c931b3417c6/href</a></iframe><p>We only iterator the loop once and use stack data structure. So the total time complexity is O(n), Space complexity is O(n).</p><ul><li><a href="https://leetcode.com/problems/next-greater-element-i/">496. Next Greater Element I</a></li></ul><p>We need to use a decreased Monotonic Stack to help us to update the previous number. Below is next greater element (NGE) case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46a0e36a429c87cafc940f1915c4d51d/href">https://medium.com/media/46a0e36a429c87cafc940f1915c4d51d/href</a></iframe><ul><li><a href="https://leetcode.com/problems/sum-of-subarray-ranges/">2104. Sum of Subarray Ranges</a></li></ul><p>If you want to get the max/min for each subarray. For brute force solution is pretty easy to solve but it will take O(n²) time complexity. Monotonic Stack can also help us to find the subarray max/min. But we need some advanced knowledge to solve this issue. For example: [1,4,2,3]. <br>[ 1, 4, 2, 3]<br>[-1, 1, 1, 2]:PLE<br>[-1, 2,-1,-1]:NLE<br>So for element 2 we will know in the range of [1,(4,2,3)] it will be the minimum number. So total case would be 4</p><pre>total subarray for element 2 is minimum one:<br>42<br>423<br>2<br>23</pre><p>As above we can get the total case4 for specific i will be PLE index <br>(2 - 0) * (4 - 2) = 4<br>So we will know for the element nums[i] = (i — PLE[i]) * (NLE[i] — i) <br>Finally we can get the result like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcefac84a4e5b376a1db92b797db86ad/href">https://medium.com/media/dcefac84a4e5b376a1db92b797db86ad/href</a></iframe><p>That’s it. Monotonic Stack can help to reduce the total time complexity a lot! If you like it please give the article 👏.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=639ddf4a4e09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game of life in Kotlin]]></title>
            <link>https://chris-yn-chen.medium.com/game-of-life-in-kotlin-a85e678c85d3?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a85e678c85d3</guid>
            <category><![CDATA[games]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[cells]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Sun, 29 Nov 2020 02:33:39 GMT</pubDate>
            <atom:updated>2020-11-29T03:15:35.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eO2Zid1ceYoE2iRM" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The reason why I build this <a href="https://github.com/chrisynchen/GameOfLife">Game of Life example</a> is because an interview. That’s really interesting because the leetcode also has this problem (<a href="https://leetcode.com/problems/game-of-life/">289. Game of Life</a>). So I try to use a brute force solution to get the next state. Then follow the Android MVP pattern to build the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*pHDCnPbIi4IMxgiDG2H1RQ.gif" /><figcaption>Photo credit by <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">wiki</a></figcaption></figure><h3>Rule</h3><p>The rule of this game is:</p><ol><li><em>Any live cell with fewer than two live neighbours dies, as if by underpopulation.</em></li><li><em>Any live cell with two or three live neighbours lives on to the next generation.</em></li><li><em>Any live cell with more than three live neighbours dies, as if by overpopulation.</em></li><li><em>Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.</em></li></ol><h3>Algorithm</h3><p>The main transition will be this function:</p><pre>override fun getNextStatus(): Array&lt;IntArray&gt; {<br>    val newPixelArray = Array(cellArray.size) <strong>{ </strong>IntArray(cellArray[0].size) <strong>}<br>    </strong>for (i in newPixelArray.<em>indices</em>) {<br>        for (j in newPixelArray[0].<em>indices</em>) {<br>            val newValue = if (isLive(cellArray, i, j)) 1 else 0<br>            if (newPixelArray[i][j] == newValue) continue<br><br>            newPixelArray[i][j] = newValue<br>        }<br>    }<br><br>    for (i in cellArray.<em>indices</em>) {<br>        for (j in cellArray[0].<em>indices</em>) {<br>            cellArray[i][j] = newPixelArray[i][j]<br>        }<br>    }<br><br>    return newPixelArray<br>}</pre><p>So I copy an array then check each element neighbours finally assign back to the array<em> </em>cellArray</p><p>Follow rules, the alive function would be:</p><pre>private fun isLive(pixelArray: Array&lt;IntArray&gt;, i: Int, j: Int): Boolean {<br>    var neighborLiveCount = 0<br>    for (k in ref.<em>indices</em>) {<br>        if (i + ref[k][0] &lt; 0 || j + ref[k][1] &lt; 0<br>            || i + ref[k][0] &gt;= pixelArray.size<br>            || j + ref[k][1] &gt;= pixelArray[0].size<br>        ) continue<br><br>        neighborLiveCount += pixelArray[i + ref[k][0]][j + ref[k][1]]<br>    }<br><br>    return if (pixelArray[i][j] == 0) {<br>        neighborLiveCount == 3<br>    } else {<br>        neighborLiveCount in 2..3<br>    }<br>}</pre><p>For these logic we should define in ViewModel or Presenter (Depends on what kind of architecture pattern you using), then we can write some unit test to make sure our logic is run as our expected.</p><h3>Write a Test</h3><pre><em>/**<br> * leetcode example<br> * https://leetcode.com/problems/game-of-life/<br> * input [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]<br> * output [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]<br> */<br></em>@Test<br>fun getNextStatus_failed() {<br>    // Given<br>    presenter.setCellArrayElement(0, 1)<br>    presenter.setCellArrayElement(1, 2)<br>    presenter.setCellArrayElement(2, 0)<br>    presenter.setCellArrayElement(2, 1)<br>    presenter.setCellArrayElement(2, 2)<br><br>    // When<br>    presenter.getNextStatus()<br><br>    // Then<br>    <em>assertEquals</em>(0, presenter.cellArray[0][0])<br>    <em>assertEquals</em>(0, presenter.cellArray[0][1])<br>    <em>assertEquals</em>(0, presenter.cellArray[0][2])<br>    <em>assertEquals</em>(1, presenter.cellArray[1][0])<br>    <em>assertEquals</em>(0, presenter.cellArray[1][1])<br>    <em>assertEquals</em>(1, presenter.cellArray[1][2])<br>    <em>assertEquals</em>(0, presenter.cellArray[2][0])<br>    <em>assertEquals</em>(1, presenter.cellArray[2][1])<br>    <em>assertEquals</em>(1, presenter.cellArray[2][2])<br>    <em>assertEquals</em>(0, presenter.cellArray[3][0])<br>    <em>assertEquals</em>(1, presenter.cellArray[3][1])<br>    <em>assertEquals</em>(0, presenter.cellArray[3][2])<br>}</pre><p>Then we can use CountDownTimer , Rxjava2 …etc method to change the state by periodically. Consider it might be block UI, so I strongly recommended to put these logic into other worker thread to prevent large works doing in main thread.</p><h3>Draw the game</h3><p>After that, we need to think about how to draw this game. We can simply to use a custom view to draw the game. So first we should define the base cell size for the game then we can use drawRect accordingly. Here is a code snipped FYR.</p><pre>override fun onDraw(canvas: Canvas) {<br>    super.onDraw(canvas)<br>    drawCells(canvas)<br>}<br><br>private fun drawCells(canvas: Canvas) {<br>    cellArray.<em>let </em><strong>{<br>        </strong>for (i in <strong>it</strong>.<em>indices</em>) {<br>            for (j in <strong>it</strong>[0].<em>indices</em>) {<br>                rect.set(<br>                    i * cellSize, j * cellSize,<br>                    (i + 1) * cellSize, (j + 1) * cellSize<br>                )<br>                paint.<em>color </em>= if (<strong>it</strong>[i][j] == 1) {<br>                    liveColor<br>                } else {<br>                    deadColor<br>                }<br>                canvas.drawRect(rect, paint)<br>            }<br>        }<br>    <strong>}<br></strong>}</pre><p>That’s it. And we can use a touch event to draw everywhere you want to init. Finally the game will looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*_Cz-LHSeYLsJnPvaELz33Q.gif" /><figcaption>Game of Life demo</figcaption></figure><p>For that interview experience is really good. Because i never imagine that one day I could apply a game algorithm into the app. Here is my full demo code. Hope you like it. :)</p><p><a href="https://github.com/chrisynchen/GameOfLife">chrisynchen/GameOfLife</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85e678c85d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apply flatbuffer in Android]]></title>
            <link>https://chris-yn-chen.medium.com/apply-flatbuffer-in-android-3f74ba087ba3?source=rss-321a4333be6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f74ba087ba3</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <dc:creator><![CDATA[Chris Chen]]></dc:creator>
            <pubDate>Thu, 14 Nov 2019 10:36:41 GMT</pubDate>
            <atom:updated>2019-12-06T07:05:35.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*NZp7Ot3dfVdI78-xmRiHrA.jpeg" /><figcaption>Image source from <a href="https://kknews.cc/news/zgg5gxq.html">here</a></figcaption></figure><p>The performance/memory tuning is a huge topic in engineer world. In order to delight our user to make a good UX. We always need to think about how to improve our application no matter in memory management and performance. One of thing we can do is how to accelerate the network request call. There are some data format for communication between client and server: such as <strong>xml, JSON</strong> in http and <strong>gRPC</strong> in http/2. In this article I want to introduce alternative way — <a href="https://google.github.io/flatbuffers/index.html#flatbuffers_overview">FlatBuffer</a>.</p><h3>Why flatbuffer?</h3><p><a href="https://google.github.io/flatbuffers/index.html#flatbuffers_overview">FlatBuffer</a> is an efficient cross platform serialization library. It will flat our data in a binary buffer which size is less than the traditional JSON format. Here are some reasons why we should adopt flutter in our android project.</p><ul><li><strong>Access to serialized data without parsing/unpacking</strong></li><li><strong>Memory efficiency and speed</strong></li><li><strong>Flexible</strong></li><li><strong>Tiny code footprint</strong></li><li><strong>Strongly typed</strong></li><li><strong>Convenient to use</strong></li><li><strong>Cross platform code with no dependencie</strong></li></ul><h3>Step by Step</h3><p>Here are some step for how you apply flatbuffer to your app.</p><h4>1. need to install the <a href="https://cmake.org/"><strong>cmake</strong></a></h4><pre>&gt; brew install cmake</pre><h4>2. setup the flatbuffer</h4><p>Clone flatbuffer project via <a href="https://github.com/google/flatbuffers">github</a></p><p>Then we need to compile</p><pre>&gt; cmake -G &quot;Unix Makefiles&quot; -DCMAKE_BUILD_TYPE=Release</pre><p>under project and run <strong>make</strong></p><pre>&gt; make<br>[ 36%] Built target flatc</pre><pre>[ 48%] Built target flatsampletext</pre><pre>[ 70%] Built target flattests</pre><pre>[ 75%] Built target flatsamplebinary</pre><pre>[ 88%] Built target flatsamplebfbs</pre><pre>[ 91%] Built target flathash</pre><pre>[100%] Built target flatbuffers</pre><p>or do alternatively simply way</p><pre>&gt; brew install flatbuffers</pre><p>can add alias for flatc CLI (Optional)</p><pre>#flatbuffer CLI</pre><pre>alias flatc=your_local_repo_path/flatbuffers/flatc</pre><p>Then can use <strong>flatc</strong></p><h4>3. Copy google flatbuffer package to your project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*qkwtjbYTH3L5KnANkp2hzA.png" /></figure><h4>4. Write a schema</h4><p>Can refer to <a href="https://google.github.io/flatbuffers/md__schemas.html">here</a>. This only write once can apply to all platform.</p><p>Let’s say we have a schema in JSON like below:</p><pre>{<br>  &quot;name&quot;: &quot;Charles&quot;,<br>  &quot;bloodVolume&quot;: 2,<br>  &quot;speed&quot;: 110.5,<br>  &quot;canFly&quot;: false,<br>  &quot;bag&quot;: {<br>    &quot;name&quot;: &quot;small bag&quot;,<br>    &quot;capacity&quot;: 100<br>  },<br>  &quot;weapons&quot;: [<br>    {<br>      &quot;name&quot;: &quot;axe&quot;,<br>      &quot;damage&quot;: 100<br>    },<br>    {<br>      &quot;name&quot;: &quot;gun&quot;,<br>      &quot;damage&quot;: 500<br>    }<br>  ],<br>  &quot;accessories&quot;: [<br>    &quot;T-shirt&quot;,<br>    &quot;pants&quot;<br>  ]<br>}</pre><p>So the <strong>Person.fbs</strong> will look like:</p><pre>namespace your.target.package;<br><br>table Person {<br>    name: string;<br>    bloodVolume: int;<br>    speed: double;<br>    canFly: bool;<br>    bag: Bag;<br>    weapons: [Weapon];<br>    accessories: [string];<br>}<br><br>table Weapon {<br>    name: string;<br>    damage: int;<br>}<br><br>table Bag {<br>    name: string;<br>    capacity: short;<br>}<br><br>root_type Person;</pre><p>Then we can generate Java classes for tables/structs</p><pre>//be careful your path<br>&gt; flatc -o app/src/main/java/ --java Person.fbs</pre><p>Then everything done.</p><h3>Testing</h3><p>If we want to test on this only in app. We can create personinjson.json in res/raw.</p><p>Then we can generate the json in binary file.</p><pre>//be careful your path<br>&gt; flatc -b Person.fbs app/src/main/res/raw/personinjson.json</pre><p>Then we can compare the JSON file and binary. The binary size is less than JSON file around 30% in general case.</p><h3>Limitation</h3><p>If you interesting how flatbuffer works. It is uses offset to read the memory address of the value. You can check the source file which generate by <strong>Person.fbs</strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9Xf2cMMOX_kUGt84_OONA.png" /><figcaption>Generate by flatc</figcaption></figure><p>So there are some limitation for flatbuffer.</p><ul><li>Flatbuffer is unlike JSON. The attribute is case-insensitive</li><li>Flatbuffer is unlike JSON. It cannot extract structure like map (key, value pair)</li><li>Default values only support for int, bool, float, double rather than string</li><li>Not easy to debug since the response is in binary</li><li>Only suitable for infrequently changed API or you need complicate attribute version control.</li><li>Only show exception in runtime when access the wrong type of the value.</li></ul><h3>Conclusion</h3><pre>JSON: 319 Bytes<br>Flatbuffer: 200 Bytes</pre><pre>com.chris.flatbuffer_example D/MainActivity: json load time : 46 ms</pre><pre>com.chris.flatbuffer_example D/MainActivity: flatbuffer load time1: 2 ms</pre><p>Let’s see the final result. The Flatbuffer flie size is less than JSON file. As for deserialization, flatbuffer is more efficiency than Gson. For more detailed information can check <a href="https://google.github.io/flatbuffers/flatbuffers_benchmarks.html">benchmark</a>. Facebook also adopt this solution to improve the app performance. They wrote an article <a href="https://engineering.fb.com/android/improving-facebook-s-performance-on-android-with-flatbuffers/">here</a>. I also put an example in my <a href="https://github.com/chrisynchen/flatbuffer-example">github</a>. Hope you like it. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f74ba087ba3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>