<?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 Calvin Lee on Medium]]></title>
        <description><![CDATA[Stories by Calvin Lee on Medium]]></description>
        <link>https://medium.com/@calvinlee417?source=rss-71571126fd7b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NcFwKYRTqcBehjPq</url>
            <title>Stories by Calvin Lee on Medium</title>
            <link>https://medium.com/@calvinlee417?source=rss-71571126fd7b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:53:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@calvinlee417/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[392. Is Subsequence]]></title>
            <link>https://medium.com/@calvinlee417/392-is-subsequence-73a77082f3?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/73a77082f3</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Wed, 21 Jun 2023 10:06:12 GMT</pubDate>
            <atom:updated>2023-06-21T10:06:12.648Z</atom:updated>
            <content:encoded><![CDATA[<pre>目錄：<br> 🌑 Question<br> 🌑 Solution<br> 🌑 Key Points<br> 🌑 References<br>    - AsahiOcean</pre><blockquote>Question</blockquote><p>Given two strings s and t, return true<em> if </em>s<em> is a </em><strong><em>subsequence</em></strong><em> of </em>t<em>, or </em>false<em> otherwise</em>.</p><p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., &quot;ace&quot; is a subsequence of &quot;abcde&quot; while &quot;aec&quot; is not).</p><pre>class Solution {<br>    func isSubsequence(_ s: String, _ t: String) -&gt; Bool {<br>        var arr = Array(s)<br><br>    }<br>}<br><br>// input1: s = &quot;abc&quot;, t = &quot;ahbgdc&quot;<br>// input2: s = &quot;axc&quot;, t = &quot;ahbgdc&quot;  </pre><blockquote>Solution</blockquote><pre>class Solution {<br>    func isSubsequence(_ s: String, _ t: String) -&gt; Bool {<br>        var ars = Array(s)<br>        for c in t where c == ars.first { ars.removeFirst() }<br>        return ars.isEmpty<br>    }<br>}</pre><blockquote>Key Point</blockquote><pre>class Solution {<br>    func isSubsequence(_ s: String, _ t: String) -&gt; Bool {<br>        var ars = Array(s)<br>        for char in t where char == ars.first { ars.removeFirst() }<br>        /* 其實跑一下就都知道在做什麼了～<br>        char = [a] == ars.first = [a] 條件成立，所以ars拿掉第一個值 ars = [b,c]<br>        char = [h] == ars.first = [b] 條件不成立，for-in繼續跑<br>        char = [b] == ars.first = [b] 條件成立，所以ars拿掉第一個值 ars = [c]<br>        char = [g] == ars.first = [c] 條件不成立，for-in繼續跑<br>        char = [d] == ars.first = [c] 條件不成立，for-in繼續跑<br>        char = [c] == ars.first = [b] 條件成立，所以ars拿掉第一個值 ars = []<br>        for-in跑完了然後ars也空了～這時候isEmpty會是true<br>        */<br>        return ars.isEmpty<br>    }<br>}<br><br>// input1: s = &quot;abc&quot;, t = &quot;ahbgdc&quot;</pre><blockquote>Reference</blockquote><p><a href="https://leetcode.com/problems/is-subsequence/solutions/2172474/accepted-solution-for-swift/?envType=study-plan-v2&amp;envId=top-interview-150">✅ [Accepted] Solution for Swift - Is Subsequence - LeetCode</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvOmukR-MKlJ2eyK_Ka2hg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73a77082f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[125. Valid Palindrome]]></title>
            <link>https://medium.com/@calvinlee417/125-valid-palindrome-8f7521586072?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7521586072</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Wed, 21 Jun 2023 06:36:05 GMT</pubDate>
            <atom:updated>2023-06-21T06:36:05.572Z</atom:updated>
            <content:encoded><![CDATA[<pre>目錄：<br> 🌑 Question<br> 🌑 Solutions<br> 🌑 Key Points<br>    - 小小想法<br> 🌑 References<br>    - AsahiOcean<br>    - inquen</pre><blockquote><em>Question</em></blockquote><p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p><p>Given a string s, return true<em> if it is a </em><strong><em>palindrome</em></strong><em>, or </em>false<em> otherwise</em>.</p><pre>class Solution {<br>    func isPalindrome(_ s: String) -&gt; Bool {<br>        <br>    }<br>}<br><br>//case1 =&gt; s = &quot;A man, a plan, a canal: Panama&quot;<br>//case2 =&gt; s = &quot;race a car&quot;<br>//case3 =&gt; s = &quot; &quot;</pre><blockquote><em>Solutions</em></blockquote><p><a href="https://leetcode.com/AsahiOcean/">AsahiOcean</a>提供的解法:</p><pre>class Solution {<br>    func isPalindrome(_ s: String) -&gt; Bool {<br>        let chars = [Character](s.lowercased().filter { $0.isLetter || $0.isNumber })<br>        var idxL = 0, idxR = (chars.count - 1)<br>        while idxL &lt; idxR {<br>            if chars[idxL] != chars[idxR] { return false }<br>            idxL += 1<br>            idxR -= 1<br>        }<br>        return true<br>    }<br>}</pre><p><a href="https://leetcode.com/inquen/">inquen</a>提供的解法:</p><pre>class Solution {<br> func isPalindrome(_ s: String) -&gt; Bool {<br>      var reversed = &quot;&quot;<br><br>      for item in s.lowercased().reversed() where item.isLetter || item.isNumber {<br>          reversed.append(item)<br>      }<br><br>      return reversed == String(reversed.reversed())<br>  }<br>}</pre><blockquote><em>Key Points</em></blockquote><p>小小想法</p><pre>class Solution {<br>    func isPalindrome(_ s: String) -&gt; Bool {<br><br>        // 這邊做了個陣列其中使用filter去刷掉非Letter或Number的值(還用了$0)，<br>        // 然後再透過lowercased去小寫全部的值。<br>        let chars = [Character](s.lowercased().filter { $0.isLetter || $0.isNumber })<br>        <br>        // 設兩個變數，去從左邊idxL跟右邊idxR去確認值是否相同。<br>        var idxL = 0, idxR = (chars.count - 1)<br>        while idxL &lt; idxR {<br>            if chars[idxL] != chars[idxR] { return false }<br>            idxL += 1<br>            idxR -= 1<br>        }<br>        return true<br>    }<br>}<br><br><br>// MARK: ----------------------------------------------<br><br>class Solution {<br> func isPalindrome(_ s: String) -&gt; Bool {<br>      var reversed = &quot;&quot;<br>      // 這邊是使用for-in去一個一個跑s[]中的非Letter&amp;Number值，<br>      // 不過這邊的.reversed()，個人認為是不必要的，因為後續return的時候本來就會轉。<br>      for item in s.lowercased().reversed() where item.isLetter || item.isNumber {<br>          reversed.append(item)<br>      }<br>      return reversed == String(reversed.reversed())<br>  }<br><br><br>  // 其實也不需要多設一個變數，直接把排除後的丟回s也可以<br>  // let s = s.lowercased().filter { $0.isLetter || $0.isNumber }<br>  // return s == String(s.reversed()) </pre><p>References:</p><ul><li><a href="https://leetcode.com/problems/valid-palindrome/solutions/412797/swift-5-solution/">Swift 5 Solution - Valid Palindrome - LeetCode</a></li><li><a href="https://leetcode.com/problems/valid-palindrome/solutions/1793564/solution-swift-valid-palindrome-test-cases/">✅ [Solution] Swift: Valid Palindrome (+ test cases) - Valid Palindrome - LeetCode</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XQbzERLfscPhmch_oTIZg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7521586072" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[121. Best Time to Buy and Sell Stock]]></title>
            <link>https://medium.com/@calvinlee417/121-best-time-to-buy-and-sell-stock-853ab537efd4?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/853ab537efd4</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 09:51:53 GMT</pubDate>
            <atom:updated>2023-06-20T05:19:47.385Z</atom:updated>
            <content:encoded><![CDATA[<pre>目錄：<br> 🌑 Question<br> 🌑 Solution<br> 🌑 Key Points<br>    1. guard &amp; if <br>    2. isEmpty<br>    3. indices<br>    4. dropFirst<br>    5. 運算過程<br> 🌑 References<br>    - AsahiOcean</pre><blockquote>Question</blockquote><p>You are given an array prices where prices[i] is the price of a given stock on the ith day.</p><p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p><p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return 0.</p><pre>class Solution {<br>    func maxProfit(_ p: [Int]) -&gt; Int {<br> <br>    }<br>}<br><br>//input1 =&gt; prices = [7,1,5,3,6,4]<br>//input2 =&gt; Prices = [7,6,4,3,1]</pre><blockquote>Solution</blockquote><p><a href="https://leetcode.com/AsahiOcean/">AsahiOcean</a>提供的解法:</p><pre>class Solution {<br>    func maxProfit(_ p: [Int]) -&gt; Int {<br>        guard !p.isEmpty else { return 0 }<br>        var bday = 0, prof = 0<br>        for i in p.indices.dropFirst() {<br>            bday = max(0, bday + p[i] - p[i-1])<br>            prof = max(prof, bday)<br>        }<br>        return prof<br>    }<br>}</pre><blockquote>Key Points</blockquote><p>Guard</p><pre>// Guard &amp; if 放在一起說明會比較清楚～<br><br>/* if else長下面這樣～<br>if 條件1 {<br>  執行1...<br>  } else if 條件2 {<br>  執行2...<br>  } else if 條件 {<br>  執行3...<br>  } else { <br>  執行4...<br>  }<br>*/<br><br>var calvinIQ = 180<br><br>if calvinIQ &lt; 85 {<br>  print(&quot;Calvin IQ 低於85&quot;)<br>} else if calvinIQ &gt; 160 {<br>  print(&quot;Calvin的IQ是\(calvinIQ)，天才來著嗎！？&quot;)<br>} else {<br>  print(&quot;麻煩Calvin努力點行嗎...&quot;)<br>}<br><br>// print：Calvin的IQ是 180 天才來著嗎！？<br><br>// ----------------------------------------------------<br>// guard的話長這樣～<br>var calvinEQ = 60<br>func EQTest(EQ: Int ) {<br>    // 當EQ &gt; 85 這事情&quot;不&quot;成立的話就執行else後面的程序碼，然後return出去～<br>    guard EQ &gt; 85 else {<br>        print(&quot;Calvin的EQ是\(calvinEQ)，可以不要這麼牡羊座嗎！？&quot;)<br>        return<br>    }<br>    // 但這邊如果 EQ &gt; 85 成立的話，會執行這邊~<br>    print(&quot;Calvin好棒棒&quot;)<br>}<br><br>EQTest(EQ: calvinEQ)<br>// print：Calvin的EQ是60，可以不要這麼牡羊座嗎！？<br><br>/*<br>當然還可在搭配一些Control transfer statements使用～<br>如：continue, break, fallthrough, return, throw...<br>*/<br></pre><p>isEmpty</p><pre>// isEmpty 就是確認是否有東西～<br><br>let horseName = &quot;Silver&quot;<br>if horseName.isEmpty {<br>    print(&quot;My horse has no name.&quot;)<br>} else {<br>    print(&quot;Hi ho, \(horseName)!&quot;)<br>}<br>// Prints &quot;Hi ho, Silver!&quot;)</pre><p>indices</p><pre><br>let greeting = &quot;Hello World!&quot;<br><br>// startIndex<br>greeting[greeting.startIndex]  // print: g<br><br>// endIndex<br>greeting[greeting.endIndex]    // print: error<br><br>// index(before:) <br>greeting[greeting.index(before:greeting.endIndex)] // print: !<br><br>// index(after:)<br>greeting[greeting.index(after:greeting.startIndex)] // print: e<br><br>// index( _:, offsetBy:)<br>let A = greeting.index(greeting.startIndex:, offsetBy: 6)]<br>greeting[A] // print: W<br><br>// indices<br>for i in greeting.indices {<br>    print(&quot;\(greeting[i]) &quot;, terminator:&quot;&quot;) // print: H e l l o   W o r l d ! <br><br>// terminator參數傳入空字串，取代原本預設換行的\n</pre><p>dropfirst</p><pre>var array = [1,2,3,4,5,6,7,8,9,10]<br>print (array.dropLast(3))    // print: [1, 2, 3, 4, 5, 6, 7]<br>print (array.dropFirst(2))   // print: [3, 4, 5, 6, 7, 8, 9, 10]<br></pre><p>運算過程</p><pre>class Solution {<br>    func maxProfit(_ p: [Int]) -&gt; Int {<br>        // 確認price陣列是否有值<br>        guard !price.isEmpty else { return 0 }<br>        var buyday = 0, profit = 0<br>        for i in p.indices.dropFirst() {<br>            buyday = max(0, buyday + p[i] - p[i-1])<br>            profit = max(profit, buyday)<br>/*          input =&gt; prices = [7,1,5,3,6,4]<br>            因為p陣列已經dropFrist()了，所以i在跑的時候要不會跑到i0<br>            <br>            i1 = 1, buyday = 0, profit = 0<br>            buyday = max(0, 0+1-7)  -&gt; buyday = 0<br>            profit = max(0, 0)      -&gt; profit = 0<br>            <br>            i2 = 5, buyday = 0, profit = 0<br>            buyday = max(0, 0+5-1)  -&gt; buyday = 4<br>            profit = max(0, 4)      -&gt; profit = 4<br>            <br>            i3 = 3, buyday = 4, profit = 4<br>            buyday = max(0, 4+3-5)  -&gt; buyday = 2<br>            profit = max(4, 2)      -&gt; profit = 4<br>            <br>            i4 = 6, buyday = 2, profit = 4<br>            buyday = max(0, 2+6-3)  -&gt; buyday = 5<br>            profit = max(4, 5)      -&gt; profit = 5<br>            <br>            i5 = 4, buyday = 5, profit = 5<br>            buyday = max(0, 5+4-6)  -&gt; buyday = 3<br>            profit = max(5, 3)      -&gt; profit = 5          */<br>}<br>        return profit  // return profit -&gt; 5<br>    }<br>}</pre><p>References</p><p><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/1370459/accepted-solution-for-swift/?envType=study-plan-v2&amp;envId=top-interview-150">✅ [Accepted] Solution for Swift - Best Time to Buy and Sell Stock - LeetCode</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*siWMVj7EOJ5GE1x_oFFE_w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=853ab537efd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[169. Majority Element]]></title>
            <link>https://medium.com/@calvinlee417/169-majority-element-a4ba42177b8f?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4ba42177b8f</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 15:21:37 GMT</pubDate>
            <atom:updated>2023-06-19T02:23:37.743Z</atom:updated>
            <content:encoded><![CDATA[<pre>目錄：<br> 🌑 Question<br> 🌑 Solutions<br> 🌑 Key points<br>    1. 三元條件運算(Ternary Conditional Operator)<br>    2. 高階函數 forEach<br>    3. isMutiple補充說明<br>    4. 運算過程<br>    5. 總結<br> 🌑 References<br>    - AsahiOcean<br>    - forEach<br>    - isMultiple</pre><blockquote><em>Question:</em></blockquote><p>Given an array nums of size n, return <em>the majority element</em>.</p><p>The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.</p><pre>class Solution {<br>     func majorityElement(_ nums: [Int]) -&gt; Int {<br>    }<br>}<br><br>//input1 =&gt; nums = [3,2,3]<br>//input2 =&gt; nums = [2,2,1,1,1,2,2]</pre><blockquote><em>Solutions</em></blockquote><p><a href="https://leetcode.com/AsahiOcean/">AsahiOcean</a>提供的解法:</p><pre>class Solution {<br>    func majorityElement(_ nums: [Int]) -&gt; Int {<br>        var candidate = 0, vote = 0<br>        nums.forEach { n in<br>            if vote == 0 { candidate = n }<br>            vote += n == candidate ? 1 : -1<br>        }<br>        return candidate<br>    }<br>}</pre><blockquote><em>Key Points</em></blockquote><p>1. 三元條件運算(Ternary Conditional Operator)</p><pre>// 三元條件運算就是 =&gt; 運算式...問題 ? 答案1 : 答案2<br>// 如果問題是true的話就回&quot;答案1&quot;，如果問題是fales的話&quot;答案2&quot;<br><br>let calvinHeight = 173<br>let wearShoes = true<br><br>// Calvin穿鞋高度 = Calvin高 + (wearShoes是否為 true, 如果是true就+2，反之+0<br>let calvinWearShoes = calvinHeight + (wearShoes ? 2:0)<br>// print(calvinWearShoes) =&gt; 175<br><br>// ----------------------------------------------------------------<br>// 知道三元條件運算後，再來看看下面這段在幹嘛！？<br><br>vote += n == candidate ? 1 : -1<br><br>/*<br>上述這段的話就是 vote += 1 or -1 取決於 n == candidate 是否成立<br>if n == candidate<br>vote + 1 <br><br>if n != candidate<br>vote -1<br>*/</pre><p>2. 高階函數 forEach</p><pre>/*<br>了解三元條件運算後，可以來看看forEach(可參閱references)了，<br>以我簡單的腦袋瓜子來說就是for-in loop。<br>*/<br><br>let numbers = [2, 5, 3, 9, 15, 12, 8, 17, 20, 11]<br><br>for number in numbers {<br>    if number % 2 == 0 {<br>        print(&quot;\(number) is even&quot;)<br>    } else {<br>        print(&quot;\(number) is odd&quot;)<br>    }<br>}<br><br>// 如果把它寫成forEach的話就會是取代for-in，但他還是有個參數(number)可以帶入~<br>numbers.forEach { (number) in {<br>    if number % 2 == 0 {<br>        print(&quot;\(number) is even&quot;)<br>    } else {<br>        print(&quot;\(number) is odd&quot;)<br>    }<br>}<br><br><br>//當然參數還可以再搭配$0的應用，就變成下面這樣<br>numbers.forEach {<br>    if $0 % 2 == 0 {<br>        print(&quot;\($0) is even&quot;)<br>    } else {<br>        print(&quot;\($0) is odd&quot;)<br>    }<br>}</pre><p>3. isMutiple補充說明</p><pre>// 額外補充: isMultiple 可以取代上面 %2 == 0 那一大塊～<br>// 所以原本的<br>for number in numbers {<br>    if number % 2 == 0 {<br>        print(&quot;\(number) is even&quot;)<br>    } else {<br>        print(&quot;\(number) is odd&quot;)<br>    }<br>}<br>// 改用isMultiple可以轉成這樣<br>for number in numbers {<br>    number.isMultiple(of: 2) ? print(&quot;\(number) is even&quot;) : print(&quot;\(number) is odd&quot;)<br>}<br><br><br>// ----------------------------------------------------------------<br>// 如果是用forEach的話～<br>numbers.forEach { (number) in {<br>    if number % 2 == 0 {<br>        print(&quot;\(number) is even&quot;)<br>    } else {<br>        print(&quot;\(number) is odd&quot;)<br>    }<br>}<br><br>// 改用isMultiple可以變成這樣<br>numbers.forEach { (number) in<br>    number.isMultiple(of: 2) ? print(&quot;\(number) is even&quot;) : print(&quot;\(number) is odd&quot;)<br>}<br><br><br>// ----------------------------------------------------------------<br>// 如果同時使用forEach 跟 $0 的話<br>numbers.forEach {<br>    if $0 % 2 == 0 {<br>        print(&quot;\($0) is even&quot;)<br>    } else {<br>        print(&quot;\($0) is odd&quot;)<br>    }<br>}<br>// 可以變成單純一行完結，實在有夠看沒有ＸＤＤＤ<br>numbers.forEach { $0.isMultiple(of: 2) ? print(&quot;\($0) is even&quot;) : print(&quot;\($0) is odd&quot;)<br>}</pre><p>4. 運算過程</p><pre>nums = [2,2,1,1,1,2,2]<br><br>class Solution {<br>    // 原解如下<br>    func majorityElementA(_ nums: [Int]) -&gt; Int {<br>        var candidate = 0, vote = 0<br>        nums.forEach { n in<br>            if vote == 0 { candidate = n }<br>            vote += n == candidate ? 1 : -1<br>        }<br>        return candidate<br>    }<br>    <br>    // 如果把for-in帶回去看的話～<br>    func majorityElementB(_ nums: [Int]) -&gt; Int {<br>        var candidate = 0, vote = 0<br>        for i in nums{<br>            print(&quot;運算前vote: &quot;,vote)<br>            if vote == 0 { candidate = i }<br>            vote +=      i == candidate ? 1 : -1<br>            print(&quot;運算之後vote: &quot;,vote)<br>        }<br>        return candidate<br>    }<br>}<br><br><br>let answer = Solution()<br>answer.majorityElementB(nums)<br>/* 跑起來會得到<br>-- i0 -&gt; 2 --<br>前面前vote:  0<br>後面之後vote:  1<br><br>-- i1 -&gt; 2 --<br>前面前vote:  1<br>後面之後vote:  2<br><br>-- i2 -&gt; 1--<br>前面前vote:  2<br>後面之後vote:  1<br><br>上面在跑蝦咪呢～如下解釋：<br><br>i0=2 的時候呢，Vote = 0 ，所以candidate = i =&gt; 2<br>vote 就要判斷要+1還是-1， 此時i == candidata -&gt; 是成立的所以 vote+1 -&gt; vote == 1<br><br>i1=2 的時候呢，Vote = 1，candidate不用動<br>vote 要判斷+1還是-1， 此時i == candidata -&gt; 是成立的所以 vote+1 -&gt; vote == 2<br><br>i2=1 的時候呢，Vote = 2，candidate不用動<br>vote 要判斷+1還是-1， 此時 i == 1 而 candidata == 2 -&gt; 所以這時後條件不成立，<br>當條件不成立 vote 要加個-1 -&gt; vote += -1 -&gt; 2-1 = 1， vote == 1<br><br>*/<br></pre><p>5. 總結以上資訊，可以變成下面這個詭異的東西。</p><pre>class Solution {<br>     func majorityElement(_ nums: [Int]) -&gt; Int {<br>        var candidate = 0, vote = 0<br>        nums.forEach {<br>            if vote == 0 { candidate = $0 }<br>            vote += $0 == candidate ? 1 : -1<br>        }<br>        return candidate<br>    }<br>}</pre><blockquote><em>References:</em></blockquote><ul><li><a href="https://leetcode.com/problems/majority-element/solutions/1242079/solution-swift-majority-element-test-cases/?envType=study-plan-v2&amp;envId=top-interview-150">✅ [Solution] Swift: Majority Element (+ test cases) - Majority Element - LeetCode</a></li><li><a href="https://www.appcoda.com.tw/higher-order-function/">Swift 教學：認識 Higher Order Functions 高階函數（Reduce 和 FlatMap）</a></li><li><a href="https://developer.apple.com/documentation/swift/int/ismultiple(of:)">isMultiple(of:) | Apple Developer Documentation</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1K3xSHN1oe3-JRNeIgTLQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4ba42177b8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[26. Remove Duplicates from Sorted Array]]></title>
            <link>https://medium.com/@calvinlee417/26-remove-duplicates-from-sorted-array-ecaa12b87f16?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecaa12b87f16</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 07:55:01 GMT</pubDate>
            <atom:updated>2023-06-18T07:55:01.248Z</atom:updated>
            <content:encoded><![CDATA[<pre>目錄：<br> 🌑 Question<br> 🌑 Solutions<br> 🌑 Key points<br> 🌑 References<br>    - user1177rA<br>    - Advanced Operators<br>    - 溢位運算子</pre><blockquote>Question:</blockquote><p>Given an integer array nums sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em>nums.</p><p>Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:</p><ul><li>Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.</li><li>Return k.</li></ul><pre>class Solution {<br>    func removeDuplicates(_ nums: inout [Int]) -&gt; Int {<br><br>    }<br>}</pre><blockquote>Solutions</blockquote><p><a href="https://leetcode.com/user1177rA/">user1177rA</a>提供兩個解法:</p><pre>func removeDuplicates(_ nums: inout [Int]) -&gt; Int {<br>    /// nums.count will be used 3 times during function, pre-calculate<br>    /// in stack frame for fewer CPU instructions.<br>    let length = nums.count<br>    guard length &gt; 1 else { return length }<br>    <br>    /// The number of unique values we are keeping<br>    var keep = 1<br>    /// Minimal iterative instructions.<br>    /// Overflow addition operator avoids instructions that unecessarily<br>    /// check for Integer overflow.<br>    for i in 1..&lt;length {<br>        if nums[i &amp;- 1] != nums[i] {<br>          nums[keep] = nums[i]<br>          keep &amp;+= 1<br>        }<br>    }<br>    /// Eliminate all of nums that are not unique.<br> /// (20% faster than nums = Array(nums[0..&lt;keep]).<br>    nums.removeLast(length &amp;- keep)<br>    return keep<br>}</pre><pre>func removeDuplicates(_ nums: inout [Int]) -&gt; Int {<br>    guard !nums.isEmpty else { return 0 }<br>    nums = Array(Set(nums)).sorted()<br>    return nums.count<br>}</pre><blockquote>Key Points</blockquote><pre>func removeDuplicates(_ nums: inout [Int]) -&gt; Int {<br>    // 這邊主要是為如果陣列內不只一個數字就會跑，但如果陣列只有一個值那就return 1<br>    let length = nums.count<br>    guard length &gt; 1 else { return length }<br><br>    <br>    var keep= 1<br>    for i in 1..&lt;length {<br>        if nums[i &amp;- 1] != nums[i] {<br>/* <br>nums = [0,0,1,1,1,2,2,3,3,4]<br>這邊 nums[keep] = nums[i] 要做的事情是如果數字不相同的話就把它丟到nums裏面]，<br>如果印出來的話會長下面這樣，因為最後nums會再透過removeLast移除多的，<br>這樣nums會變成題目需求的無重複值陣列  <br>  [0, 1, 1, 1, 1, 2, 2, 3, 3, 4]<br>  [0, 1, 2, 1, 1, 2, 2, 3, 3, 4]<br>  [0, 1, 2, 3, 1, 2, 2, 3, 3, 4]<br>  [0, 1, 2, 3, 4, 2, 2, 3, 3, 4]<br>    */<br>          nums[keep] = nums[i]<br>          keep &amp;+= 1<br>        }<br>    }<br>// 此處就是在移除後面已重複的值<br>    nums.removeLast(length &amp;- keep)<br>    return keep<br>}<br><br>// 但此方法適用於nums陣列已排序，如果nums = [1,2,3,4,0,0,1,2,3,1]<br>// 就會return錯誤的值。<br><br><br>// &amp;-與&amp;+ 請參閱advanced operators or 溢位運算子<br></pre><pre>func removeDuplicates(_ nums: inout [Int]) -&gt; Int {<br><br>  // 確保nums不是null<br>    guard !nums.isEmpty else { return 0 }<br>/*<br>  nums = [1,2,3,4,0,0,1,2,3,1]<br>  Set(nums) = [1,2,3,4,0] =&gt; Set 維護一組不重複的資料，但資料不依序儲存。<br>  nums.sorted = [0,1,2,3,4] =&gt; sorted來排序。<br>  Array(Set(nums)) =&gt; 讓他重set型別轉回array型別。<br>*/<br>    nums = Array(Set(nums)).sorted()<br>    return nums.count<br>}</pre><blockquote>References:</blockquote><ul><li><a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/solutions/1047203/swift-99-88-performance-with-documentation/?envType=study-plan-v2&amp;envId=top-interview-150">Swift 99.88% Performance with Documentation - Remove Duplicates from Sorted Array - LeetCode</a></li><li><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/advancedoperators/#Overflow-Operators">Documentation</a></li><li><a href="https://tommy60703.gitbooks.io/swift-language-traditional-chinese/content/chapter2/23_Advanced_Operators.html#overflow_operators">《The Sw­ift Pr­ogramm­ing La­nguage­》正體中文版</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*149yyosx0eWdfKVcEOJaGw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecaa12b87f16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[27. Remove Element]]></title>
            <link>https://medium.com/@calvinlee417/27-remove-element-top-interview-150-2bb0ba4c6a86?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bb0ba4c6a86</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 04:36:56 GMT</pubDate>
            <atom:updated>2023-06-18T05:51:24.951Z</atom:updated>
            <content:encoded><![CDATA[<pre>目錄：<br> 🌑 Question<br> 🌑 Solution<br> 🌑 Key points<br>    1. filter<br> 🌑 References<br>    - Swift 教學：認識 Higher Order Functions 高階函數<br>    - closure 參數的省略，神奇的 $0，$1 &amp; $2</pre><p>Question:</p><p>Given an integer array nums and an integer val, remove all occurrences of val in nums <a href="https://en.wikipedia.org/wiki/In-place_algorithm"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em>nums<em> which are not equal to </em>val.</p><p>Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:</p><ul><li>Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.</li><li>Return k.</li></ul><pre>class Solution {<br>    func removeElement(_ nums: inout [Int], _ val: Int) -&gt; Int {<br>  <br>    }<br>}</pre><p><a href="https://leetcode.com/AsahiOcean/">AsahiOcean</a>提供的解法:</p><pre>class Solution {<br>    func removeElement(_ nums: inout [Int], _ val: Int) -&gt; Int {<br>           nums = nums.filter { $0 != val }<br>        return nums.count<br>    }<br>}</pre><blockquote><strong>The Sw­ift Pr­ogramm­ing La­nguage­ -</strong>filter() 宣告如下：</blockquote><pre>func filter(includeElement: (T) -&gt; Bool) -&gt; Array&lt;T&gt;</pre><ul><li>includeElement 表示傳入的 function 或 closure，用來判斷陣列個元素是否符合條件。</li><li>filter() 回傳結果為陣列。</li></ul><p>以上為定義，實際操作的話如下</p><pre>import UIKit<br><br>// 先來一個無序陣列<br>let numbers = [2, 5, 3, 9, 15, 12, 8, 17, 20, 11]<br><br>// ----------------------------------------------------------------<br>// 正常來說要超過如果要抓超過10以上的數字，方式如下<br>var over10A = [Int]()<br><br>for number in numbers {<br>    if number &gt; 10 {<br>        over10A.append(number)<br>    }<br>}<br>print(&quot;over10A: &quot;, over10A) // over10A:  [15, 12, 17, 20, 11]<br><br><br>// ----------------------------------------------------------------<br>//使用filter的話～ 因bool number &gt; 10 為true 就把 number appends到over10B<br>let over10B = numbers.filter { (number) -&gt; Bool in<br>    if number &gt; 10 {<br>        return true<br>    } else {<br>        return false<br>    }<br>}<br>print(&quot;over10B: &quot;, over10B) // over10B:  [15, 12, 17, 20, 11]<br><br><br><br>// ----------------------------------------------------------------<br>// 配合$0 搭配 bool使用會更加簡短如下<br>let over10C = numbers.filter { $0 &gt; 10 }<br><br>print(&quot;over10C: &quot;, over10C)// over10C:  [15, 12, 17, 20, 11]<br><br><br>// ----------------------------------------------------------------<br>/*<br><br>$0 說明一下下～ 以over10C為例子<br>.filter { $0 &gt; 10 } 是在做下面的事情，但直接省略掉_參數<br><br>for _ in numbers {<br>  if _ &gt; 10 {<br>    over10C.append(_)<br>    }<br>}<br><br>*/ </pre><p>Reference:</p><ul><li><a href="https://tommy60703.gitbooks.io/swift-language-traditional-chinese/content/chapter2/06_Functions.html">《The Sw­ift Pr­ogramm­ing La­nguage­》正體中文版</a></li><li><a href="https://leetcode.com/problems/remove-element/description/?envType=study-plan-v2&amp;envId=top-interview-150">Remove Element - LeetCode</a></li><li><a href="https://www.appcoda.com.tw/higher-order-function/">Swift 教學：認識 Higher Order Functions 高階函數（Reduce 和 FlatMap）</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/closure-%E5%8F%83%E6%95%B8%E7%9A%84%E7%9C%81%E7%95%A5-%E7%A5%9E%E5%A5%87%E7%9A%84-0-1-2-shorthand-argument-names-ade1b883e7da">closure 參數的省略，神奇的 $0，$1 &amp; $2 (Shorthand Argument Names)</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPvjs5KpxWvir0Cfgwy7Pw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bb0ba4c6a86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top Interview 150 — Merge Sorted Array(88)]]></title>
            <link>https://medium.com/@calvinlee417/top-interview-150-merge-sorted-array-88-db3181eaadfe?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/db3181eaadfe</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 09:18:18 GMT</pubDate>
            <atom:updated>2023-06-18T05:51:14.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>88. Merge Sorted Array</h3><pre>目錄：<br> 🌑 Question<br> 🌑 Solutions<br> 🌑 Key points<br>    1. 半閉區間運算子<br>    2. inout<br>    3. prefix<br>    4. Named parameter<br> 🌑 References</pre><blockquote>Question:</blockquote><p>You are given two integer arrays nums1 and nums2, sorted in <strong>non-decreasing order</strong>, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.</p><p><strong>Merge</strong> nums1 and nums2 into a single array sorted in <strong>non-decreasing order</strong>.</p><p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em>nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.</p><blockquote>Solutions</blockquote><p><a href="https://leetcode.com/UpvoteThisPls/">UpvoteThisPls</a>提供的解法:</p><pre>class Solution {<br>    func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {<br>        nums1 = (nums1[..&lt;m]+nums2).sorted()<br>    }<br>}</pre><p>另一位<a href="https://leetcode.com/YO1901/">YO1901</a>提供用prefix的建議～</p><pre>class Solution {<br>    func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {<br>        nums1 = (nums1.prefix(m)+nums2).sorted()<br>    }<br>}</pre><blockquote>Key Points</blockquote><p>半閉區間運算子（<em>a..&lt;b</em>）定義一個從<em>a</em>到<em>b</em>但不包括<em>b</em>的區間。 之所以稱為半閉區間，是因為該區間包含第一個值而不包括最後的值。就像閉區間運算子一樣，<em>a</em>的值必不大於<em>b</em>。如果<em>a</em>跟<em>b</em>相等，那結果的區間就會是空。</p><pre>let names = [&quot;Anna&quot;, &quot;Alex&quot;, &quot;Brian&quot;, &quot;Jack&quot;]<br>let count = names.count<br>for i in 0..&lt;count {<br>    println(&quot;第 \(i + 1) 個人叫 \(names[i])&quot;)<br>}<br>// 第 1 個人叫 Anna<br>// 第 2 個人叫 Alex<br>// 第 3 個人叫 Brian<br>// 第 4 個人叫 Jack</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>輸入輸出參數（In-Out Parameters）變數參數，僅僅能在函式體內被更改。如果想要一個函式可以修改參數的值，並且想要在這些修改在函式呼叫結束後仍然存在，那麼就應該把這個參數定義為輸入輸出參數（In-Out Parameters）。</p><pre>func TwoInts(inout a: Int, inout b: Int) {<br>    let temporaryA = a<br>    a = b<br>    b = temporaryA<br>}</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>prefix</strong>: Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.</p><pre>let numbers = [1, 2, 3, 4, 5]<br>print(numbers.prefix(2))<br>// Prints &quot;[1, 2]&quot;<br>print(numbers.prefix(10))<br>// Prints &quot;[1, 2, 3, 4, 5]&quot;</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>預設情況下函式使用其參數名稱（parameter name）作為引數標籤(argument label)。在參數名稱之前可以另外給一個自行定義的引數標籤，或者以_符號來表示不保留引數標籤。</p><pre>func greet(_ person: String, on day: String) -&gt; String<br>{<br>    return &quot;Hello \(person), today is \(day).&quot;<br>}<br>greet(&quot;John&quot;, on: &quot;Wednesday&quot;)<br>//Prints &quot;Hello John, today is Wednesday.&quot;</pre><p>Reference:</p><ul><li><a href="https://tommy60703.gitbooks.io/swift-language-traditional-chinese/content/chapter2/02_Basic_Operators.html">《The Sw­ift Pr­ogramm­ing La­nguage­》正體中文版</a></li><li><a href="https://developer.apple.com/documentation/swift/array/prefix(_:)">prefix(_:) | Apple Developer Documentation</a></li><li><a href="https://tommy60703.gitbooks.io/swift-language-traditional-chinese/content/chapter2/06_Functions.html">《The Sw­ift Pr­ogramm­ing La­nguage­》正體中文版</a></li><li><a href="https://leetcode.com/problems/merge-sorted-array/description/?envType=study-plan-v2&amp;envId=top-interview-150">Merge Sorted Array - LeetCode</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAqNw1AB_BgPWFu72q6RFQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db3181eaadfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#5 心理測驗或問卷 App | 龍與地下城九大陣營測驗]]></title>
            <link>https://medium.com/@calvinlee417/5-%E5%BF%83%E7%90%86%E6%B8%AC%E9%A9%97%E6%88%96%E5%95%8F%E5%8D%B7-app-%E9%BE%8D%E8%88%87%E5%9C%B0%E4%B8%8B%E5%9F%8E%E4%B9%9D%E5%A4%A7%E9%99%A3%E7%87%9F%E6%B8%AC%E9%A9%97-1deaa4867d47?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1deaa4867d47</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 04:44:50 GMT</pubDate>
            <atom:updated>2023-06-02T04:54:52.051Z</atom:updated>
            <content:encoded><![CDATA[<p>正所謂”沒吃過豬肉，也見過豬跑”，雖然現在沒看過豬走路的應該更多人了。大家可能沒玩過龍與地下城的桌遊，但還在沒有電腦的年代時這款桌遊可是美國瘋迷。它甚至是影響到所有後來的RPG類型遊戲(角色扮演遊戲)，之前也有買過類似的桌遊，但可能是大家已經習慣電腦了～玩不起來QQ<br>最近也出了電影版，據說評價也不錯，也因為電影的關係想到來做個陣營的測驗。 (資訊來源是簡體，我懶得轉繁體請見諒 XDDD)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XUW7lA7nzcDdi1CGR_SeOQ.jpeg" /></figure><pre>目錄：<br> 🌑 <a href="#386b">Demo &amp; Structure</a><br> 🌑 Key points<br>    1. <a href="#7257">Questions and Choices</a><br>    2. <a href="#016f">Button Action</a><br>    3. <a href="#8085">Display View</a><br>    4. <a href="#f1a7">Compute Points</a><br>    5. <a href="#d7dc">Next Button</a><br>    6. <a href="#85eb">Protocol</a><br> 🌑 <a href="#9724">GitHub</a><br> 🌑 <a href="#1c5d">Reference</a></pre><blockquote>Demo &amp; Structure</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*nwhvzZt7R9_JNFOOHW2bqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*TuDvUig62d16_4YOLM5ozw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*fKJI1LSB0qvVt956nPmIwA.png" /></figure><ol><li>頁面一(圖片1 &amp; 2)：<br>A. 標題<br>B. 進度條(共36題依長度去分36等分)<br>C. 題目(依目前進度去抓question index)<br>D. 四個選項(依目前進度去抓choice index)<br>E. 下一題(顯示下一個question&amp;choices，最後一題時去計算陣營)</li><li>頁面二(圖片3)：<br>A. 9大陣營圖片<br>B. 測試完後你的陣營<br>C. 陣營解析<br>D. 再測試一次(用協定去執行)</li></ol><blockquote>Key Points</blockquote><p>1. Questions and Choices</p><pre>//建立一個新的swift file來存放問題、選項、陣營，及對應分數的資料<br>import Foundation<br><br>struct Question <br>{<br>    let questionContent: String<br>    var choices: [Choice]<br>}<br><br>/*    這邊設了三個常數: <br>      content是要選項的資訊; <br>      type是每個選項有自己對應到的陣營; <br>      選項中的陣營對應的分數也不同 */<br>struct Choice <br>{<br>    let content: String<br>    let type: Type<br>    let score: Int<br>}<br><br>/*    陣營的方式是用列舉(enumerate)去列出6種，<br>      會這樣主要是之後再用switch去判斷及抓分數時使用 */<br>enum Type <br>{<br>    case Good, GEN, Evil, Law, LCN, Chaos<br>}<br><br>// 陣列資訊範例如下<br>var questions = [<br>    Question(questionContent: &quot;Question X：&quot;,<br>             choices: [Choice(content: &quot;First Choice.&quot;, type: .Good, score:2),<br>                       Choice(content: &quot;Second Choice.&quot;, type: .Law, score:1),<br>                       Choice(content: &quot;Third Choice.&quot;, type: .Chaos, score:1),<br>                       Choice(content: &quot;Fourth Choice.&quot;, type: .Evil, score:2)]),</pre><pre><a href="#7257">Questions and Choices</a>｜<a href="#d77a">文章目錄</a></pre><p>2. Button Action</p><pre>    // 定義選項被選後便色變圖案，以及選項被選擇後才會顯示出&quot;next&quot;按鈕<br>    @IBAction func firstButtonAction(_ sender: AnyObject) <br>    {<br>        firstChoiceButton.isSelected = true;<br>        secondChoiceButton.isSelected = false;<br>        thirdChoiceButton.isSelected = false;<br>        fourthChoiceButton.isSelected = false;<br>        nextButton.isHidden = false<br>    }</pre><pre><a href="#d77a">文章目錄</a></pre><p>3. Display View</p><pre>    // 顯示question以及屬於它的choices。<br>    func displayQuestion() <br>  {<br>        // 顯示相對應的問題及選項<br>        questionsLabel.text = questions[currentQuestionIndex].questionContent<br>        firstChoiceButton.setTitle(questions[currentQuestionIndex].choices[0].content, for: .normal)<br>        secondChoiceButton.setTitle(questions[currentQuestionIndex].choices[1].content, for: .normal)<br>        thirdChoiceButton.setTitle(questions[currentQuestionIndex].choices[2].content, for: .normal)<br>        fourthChoiceButton.setTitle(questions[currentQuestionIndex].choices[3].content, for: .normal)<br>        <br>        // 每次點選&quot;next&quot;按鈕後，都把四個選項取消選取。<br>        firstChoiceButton.isSelected = false;<br>        secondChoiceButton.isSelected = false;<br>        thirdChoiceButton.isSelected = false;<br>        fourthChoiceButton.isSelected = false;<br>    }</pre><pre><a href="#d77a">文章目錄</a></pre><p>4. Compute Points</p><pre>    // 選擇選項後，回傳選項的資訊<br>    func buttonChose() -&gt; Int<br>    {<br>        var chose:Int = 0<br>        if firstChoiceButton.isSelected == true {<br>            chose = 0<br>        } else if secondChoiceButton.isSelected == true {<br>            chose = 1<br>        } else if thirdChoiceButton.isSelected == true {<br>            chose = 2<br>        } else if fourthChoiceButton.isSelected == true {<br>            chose = 3<br>        }<br>        return chose<br>    }<br>    <br>    <br>    // 設變數給計算陣營功能&quot;computeAlignmentType&quot;使用<br>    var law_Score = 0<br>    var chaos_Score = 0<br>    var lcn_Score = 0<br>    var good_Score = 0<br>    var evil_Score = 0<br>    var gen_Score = 0<br>    <br><br>    //<br>    func computeAlignmentType() -&gt; String<br>    {<br>        let defineType = questions[currentQuestionIndex - 1].choices[buttonChose()].type<br>  <br>        // 用switch在qustions[_].choices[_]裡面的type挑<br>        switch defineType<br>            {<br>            case .Law:<br>                law_Score += questions[currentQuestionIndex - 1].choices[buttonChose()].score<br>                print(&quot;Law&quot;, law_Score) //這邊print只是想看有沒有跑對而已<br>            case .Chaos:<br>                chaos_Score += questions[currentQuestionIndex - 1].choices[buttonChose()].score<br>                print(&quot;Chaos&quot;, chaos_Score)<br>            case .LCN:<br>                lcn_Score += questions[currentQuestionIndex - 1].choices[buttonChose()].score<br>                print(&quot;LCN&quot;, lcn_Score)<br>            case .Good:<br>                good_Score += questions[currentQuestionIndex - 1].choices[buttonChose()].score<br>                print(&quot;Good&quot;, good_Score)<br>            case .Evil:<br>                evil_Score += questions[currentQuestionIndex - 1].choices[buttonChose()].score<br>                print(&quot;Evil&quot;, evil_Score)<br>            case .GEN:<br>                gen_Score += questions[currentQuestionIndex - 1].choices[buttonChose()].score<br>                print(&quot;GEN&quot;, gen_Score)<br>        }<br>        <br>        // 設定變數來丟兩種性向？性格？偏好？<br>        var typeString = &quot;&quot;<br>        <br>        // 第一種，為避免分數相同多做了幾個判別<br>        let firstAlignment = [&quot;守序&quot;, &quot;中立&quot;, &quot;混乱&quot;]<br>        if  law_Score &gt; chaos_Score &amp;&amp; law_Score &gt; lcn_Score {<br>            typeString += &quot;守序&quot;<br>        } else if chaos_Score &gt; law_Score &amp;&amp; chaos_Score &gt; lcn_Score {<br>            typeString += &quot;混乱&quot;<br>        } else if lcn_Score &gt; law_Score &amp;&amp; lcn_Score &gt; chaos_Score {<br>            typeString += &quot;中立&quot;<br>        } else if law_Score == lcn_Score &amp;&amp; chaos_Score &lt; lcn_Score {<br>            typeString += &quot;守序&quot;<br>        } else if law_Score == chaos_Score {<br>            typeString += &quot;中立&quot;<br>        } else if chaos_Score == lcn_Score &amp;&amp; law_Score &lt; lcn_Score {<br>            typeString += &quot;混乱&quot;<br>        }<br>        <br>        // 第二種，為避免分數相同多做了幾個判別<br>        let secondAlignment = [&quot;善良&quot;, &quot;中立&quot;, &quot;邪恶&quot;]<br>        if  good_Score &gt; evil_Score &amp;&amp; good_Score &gt; gen_Score {<br>            typeString += &quot;善良&quot;<br>        } else if evil_Score &gt; good_Score &amp;&amp; evil_Score &gt; gen_Score {<br>            typeString += &quot;邪恶&quot;<br>        } else if gen_Score &gt; good_Score &amp;&amp; gen_Score &gt; evil_Score {<br>            typeString += &quot;中立&quot;<br>        } else if good_Score == gen_Score &amp;&amp; evil_Score &lt; gen_Score {<br>            typeString += &quot;善良&quot;<br>        } else if good_Score == evil_Score {<br>            typeString += &quot;中立&quot;<br>        } else if evil_Score == gen_Score &amp;&amp; good_Score &lt; gen_Score {<br>            typeString += &quot;邪恶&quot;<br>        }<br>        <br>        // 最後computeAlignmentType此function回傳一個string，丟回去給alignmentTypeText再做陣營判別及抓資訊。<br>        return typeString<br>    }<br>    <br>}</pre><pre><a href="#f1a7">Compute Points</a>｜<a href="#d77a">文章目錄</a></pre><p>5. Next Button</p><pre>@IBAction func nextButton(_ sender: UIButton)<br>    {<br>        var alignmentTypeText = &quot;&quot;<br>        var index = 0<br>        currentQuestionIndex += 1<br>        //進度條<br>        progressBar.progress = Float(currentQuestionIndex) / Float(questions.count) // 更新進度條<br>        if currentQuestionIndex == questions.count<br>        {<br>            // 將每次答題後計算的陣營取向取最大值丟回alignmentTypeText，再去看要抓哪個index<br>            alignmentTypeText = computeAlignmentType()<br><br>            // 求出 AlignmentTypeText 屬於的 struct 在陣列中的 index<br>            switch alignmentTypeText<br>            {<br>                case &quot;守序善良&quot;: index = 0<br>                case &quot;中立善良&quot;: index = 1<br>                case &quot;混乱善良&quot;: index = 2<br>                case &quot;守序中立&quot;: index = 3<br>                case &quot;中立中立&quot;: index = 4<br>                case &quot;混乱中立&quot;: index = 5<br>                case &quot;守序邪恶&quot;: index = 6<br>                case &quot;中立邪恶&quot;: index = 7<br>                case &quot;混乱邪恶&quot;: index = 8<br>                default: break<br>            }<br>                // 把alignment[index] 和 index 分別傳給 resultVC 的屬性<br>                if let resultVC = storyboard?.instantiateViewController(identifier: &quot;ResultVC&quot;) as? ResultViewController<br>                    {<br>                    resultVC.delegate = self //restart功能用<br>                    resultVC.alignmentInfo = alignments[index]<br>                    resultVC.alignmentIndex = index<br>                    resultVC.modalPresentationStyle = .overCurrentContext<br>                    present(resultVC, animated: true)<br>                    }<br>        } else if currentQuestionIndex &lt; questions.count<br>            {<br>            displayQuestion() // 顯示下一頁後的題目<br>            nextButton.isHidden = true // 隱藏下一頁的按鈕<br>            }<br>        <br>    }</pre><pre><a href="#d7dc">Next Button</a>｜<a href="#d77a">文章目錄</a></pre><p>6. Protocol</p><pre>  //因為protocol是無法建立資料，僅宣告沒實作，故這邊宣了個 function到ViewController使用<br><br>protocol ResultViewControllerProtocol <br>{<br>    func dialogueDismissed()<br>}</pre><pre>class ViewController: UIViewController, ResultViewControllerProtocol<br>{<br>    var currentQuestionIndex = 0<br><br>    // <br>    func dialogueDismissed() {<br>        currentQuestionIndex = 0 // 指標回到第1題<br>        progressBar.progress = 0 // 進度條歸零<br>        displayQuestion() // 顯示問題<br>    }</pre><p>Protocol的部分推薦幾位前輩們寫的資訊～</p><p><a href="https://www.appcoda.com.tw/swift-protocol/">https://www.appcoda.com.tw/swift-protocol/</a></p><ul><li><a href="https://medium.com/one-two-swift/classes-%E5%92%8C-structure-oop-%E5%92%8C-pop-de4a4b4ffe4b">Swift基礎 — Class 和 Structure OOP 和 POP</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E7%B0%A1%E6%98%93%E8%AA%AA%E6%98%8Eswift-4-protocol-919b7f9cbaee">『簡易說明Swift 4』Protocol</a></li></ul><pre><a href="#85eb">Protocol</a>｜<a href="#d77a">文章目錄</a></pre><blockquote>GitHub:</blockquote><p><a href="https://github.com/Hsuan-Yu/DnD_Alignment_test">GitHub - Hsuan-Yu/DnD_Alignment_test</a></p><blockquote>Reference:</blockquote><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84%E8%A9%A6%E7%85%89-%E5%8B%87%E8%80%85%E7%9A%84-100-%E9%81%93-swift-ios-app-%E8%AC%8E%E9%A1%8C/16-%E5%BF%83%E7%90%86%E6%B8%AC%E9%A9%97%E6%88%96%E5%95%8F%E5%8D%B7-app-d8910d1345e">#16 心理測驗或問卷 App</a></li><li><a href="http://easydamus.com/alignmenttest.html">Alignment Test</a></li><li><a href="https://unnamed42.github.io/2016-06-30-%E5%AE%98%E6%96%B9%E7%89%88DnD%E9%98%B5%E8%90%A5%E6%B5%8B%E8%AF%95.html">官方版DnD阵营测试</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/21-%E8%A3%BD%E4%BD%9C-mbti-%E5%8D%81%E5%85%AD%E5%9E%8B%E4%BA%BA%E6%A0%BC%E6%B8%AC%E8%A9%A6-app-ee8d5e269e9f">#21 製作 MBTI 十六型人格測試 App</a></li></ul><pre><a href="#d77a">文章目錄</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1deaa4867d47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[文章指南彙整目錄]]></title>
            <link>https://medium.com/@calvinlee417/%E7%9B%AE%E9%8C%84-2c8088df3f3d?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c8088df3f3d</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Wed, 17 May 2023 05:21:41 GMT</pubDate>
            <atom:updated>2023-06-21T10:07:35.811Z</atom:updated>
            <content:encoded><![CDATA[<p>小小前言：<br>一位被蘋果砸到的科學家Isaac Newon說過：<br>If I have seen further it is by standing on the shoulders of giants.</p><figure><img alt="奧維爾號(The Orville)" src="https://cdn-images-1.medium.com/max/1024/1*jWoGJqXi87p4nzTa13hVtQ.png" /><figcaption>奧維爾號 (The Orville)</figcaption></figure><p>對我來說模仿是最有效的學習方式，就像是站在巨人肩膀上一樣，在什麼都不懂的狀況下先知道怎麼使用後再去理解其原理，我覺得是很快的一種學習方式。在學會使用後去理解它會有種 『哦～～～～～對對對！ 難怪！！』 的豁然開朗。推薦給想嘗試學習的各位～模仿是學習必經的過程，母湯的是抄襲。所以各位學起來～</p><pre>目錄：<br> 🌑 <a href="#520f">Swift、iOS 學習目錄</a><br> 🌑 <a href="#e9b1">LeetCode練習</a><br> 🌑 <a href="#ff52">其其它它有的無的欸東西</a></pre><blockquote><strong><em>Swift、iOS 學習目錄：</em><br></strong><em>學習作品集～</em></blockquote><p>#5 <a href="https://medium.com/@calvinlee417/5-%E5%BF%83%E7%90%86%E6%B8%AC%E9%A9%97%E6%88%96%E5%95%8F%E5%8D%B7-app-%E9%BE%8D%E8%88%87%E5%9C%B0%E4%B8%8B%E5%9F%8E%E4%B9%9D%E5%A4%A7%E9%99%A3%E7%87%9F%E6%B8%AC%E9%A9%97-1deaa4867d47">心理測驗或問卷 App | 龍與地下城九大陣營測驗</a><br>#4 <a href="https://medium.com/@calvinlee417/4-youtube-api-part-1-e8ec123d743e">Youtube API | ALHLEAN-X</a><br>#3 <a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/3-%E8%AA%BF%E8%89%B2%E5%A4%A7%E5%B8%AB-rick-and-morty-1403f0e5cb1b">調色大師 | Rick and Morty</a><br>#2 <a href="https://medium.com/@calvinlee417/2-collection-view-74dc9ae0818e">Collection View | Monster</a><br>#1 <a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/1-auto-layout-figma-%E8%A8%AD%E8%A8%88%E5%9C%96%E7%B7%B4%E7%BF%92-aeef82928236?source=your_stories_page-------------------------------------">Auto Layout | Figma 設計圖練習</a></p><pre><a href="#520f">段落：Swift、iOS 學習目錄</a>｜<a href="#7554">回目錄</a></pre><blockquote><em>LeetCode練習</em></blockquote><p>Top Interview 150:<br>#26 <a href="https://medium.com/@calvinlee417/26-remove-duplicates-from-sorted-array-ecaa12b87f16">Remove Duplicates from Array</a><br>#27 <a href="https://medium.com/@calvinlee417/27-remove-element-top-interview-150-2bb0ba4c6a86">Remove Element</a><br>#88 <a href="https://medium.com/@calvinlee417/top-interview-150-merge-sorted-array-88-db3181eaadfe">Merge Sorted Array</a><br>#121 <a href="https://medium.com/@calvinlee417/121-best-time-to-buy-and-sell-stock-853ab537efd4">Best Time to Buy and Sell Stock</a><br>#125 <a href="https://medium.com/@calvinlee417/125-valid-palindrome-8f7521586072">Vaild Palindrome</a><br>#169 <a href="https://medium.com/@calvinlee417/169-majority-element-a4ba42177b8f">Majority Element</a><br>#392 <a href="https://medium.com/@calvinlee417/392-is-subsequence-73a77082f3">Is Subsequence</a></p><pre><a href="#e9b1">LeetCode練習</a>｜<a href="#7554">回目錄</a></pre><blockquote>其其它它<br>有的無的欸東西</blockquote><p>🌑 <a href="https://medium.com/@calvinlee417/medium-%E7%9B%AE%E9%8C%84-%E6%AE%B5%E8%90%BD-40c8667a6de2#325f">Medium 目錄&amp;段落</a><br>🌑 自我介紹</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2LJ1jUfo6-LfDRWLnzBjA.jpeg" /></figure><pre><a href="#ff52">段落：其其它他有的無的欸東西</a>｜<a href="#7554">回目錄</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c8088df3f3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Medium 目錄&段落]]></title>
            <link>https://medium.com/@calvinlee417/medium-%E7%9B%AE%E9%8C%84-%E6%AE%B5%E8%90%BD-40c8667a6de2?source=rss-71571126fd7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/40c8667a6de2</guid>
            <dc:creator><![CDATA[Calvin Lee]]></dc:creator>
            <pubDate>Wed, 17 May 2023 04:59:37 GMT</pubDate>
            <atom:updated>2023-05-17T08:36:48.264Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>學習目標：</em></strong></blockquote><p>學會Medium的目錄、段落及文章跳轉</p><ol><li>Steps<br>🌑 第一步：找尋文字的位置<br>🌑 第二步：設置目錄區塊</li></ol><blockquote><strong>Steps：</strong></blockquote><p>🌑 第一步：找尋文字的位置</p><ol><li>先在網頁中按下鍵盤的『fn + F12』</li><li>找尋文字的位置可以看到段落的name是7790，文章頂點的name是325f</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*jrPLHUWWfnHMgAm7--VzCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*5j_j4c0DzjkJzoXH4xhbVw.png" /></figure><p>🌑 第二步：設置目錄區塊</p><ol><li>先打好『段落頂點｜文章目錄』後再按下快捷鍵<br>Mac：⌘ + option + 6</li><li>匡選『段落頂點』後點迴紋針輸入#7790 <em>(注意:須在前面加入#)</em></li><li>Story尚未發布前的話開啟新分頁跳轉，發布後就會在同頁執行</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-sFFvWoOszQBoslMKW8cQ.png" /></figure><pre><a href="#7790">段落頂點</a>｜<a href="#325f">文章目錄</a></pre><blockquote><em>Reference：</em></blockquote><p><a href="https://medium.com/deerlight/medium-d3a707f3c2ce">🌰 Medium Tips｜內文導引</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40c8667a6de2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>