<?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 De_ on Medium]]></title>
        <description><![CDATA[Stories by De_ on Medium]]></description>
        <link>https://medium.com/@debbiecamera0704?source=rss-1d35a82d3fba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NEmcSAXUHyLwEnOiokRYrg.jpeg</url>
            <title>Stories by De_ on Medium</title>
            <link>https://medium.com/@debbiecamera0704?source=rss-1d35a82d3fba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:01:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@debbiecamera0704/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[CS50 Week5 Data Structure]]></title>
            <link>https://debbiecamera0704.medium.com/cs50-week5-data-structure-8bc8af49757a?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bc8af49757a</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[cs50]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[trees]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Mon, 02 May 2022 10:17:02 GMT</pubDate>
            <atom:updated>2022-05-02T10:17:02.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5BeQAn0S8OWcJ9DU7lMRg.jpeg" /><figcaption>CS50 Week5 Data Structure</figcaption></figure><p>Remember array is elements stored back to back? The size of an array is often predefined. If you want to resize it afterwards, chances are there might be some garbage values stored next to it and you can’t just plop in a new value. Then what is the solution?</p><p>Let’s say the original array is of size 3 and you want to add a new value. What you can do is get a new chunk of memory with size of 4 and then copy the original array, finally put the new value in.</p><p>The time complexity is O(n) since you need to execute n times copy and pasting into an array. As the original array gets bigger and bigger, the time to execute those steps would be much longer.</p><h3>Linked List</h3><p>Linked list is dynamic, easy to grow and shrink the size of it without having to touch and move all the original data from one location to another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQMQWb5s6GCLTIPDn80VQw.jpeg" /><figcaption>linked list</figcaption></figure><p>Each element in a linked list stores two things, one is the value it holds, the second one is the pointer to the next element. The last element does not store any pointer, so the value of it is null, which means the absence of an address</p><p>We can think of linked list as a list of numbers that are linked togerther.</p><p>The links are implemented by way of addresses or pointers. The linked list is just a collection of nodes, each rectangle in the above image represents a node.</p><p>With linked list, we save the time doing the copy pasting of values that an array uses to resize. But the tradeoff is that we need extra space to store pointers.</p><p>Let’s create the structure of a linked list:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73f92d186303ac9da0e4f41b9e98f23d/href">https://medium.com/media/73f92d186303ac9da0e4f41b9e98f23d/href</a></iframe><p>How to create a linked list with codes?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/260cbeb814c8194d3103a1d30be0c44b/href">https://medium.com/media/260cbeb814c8194d3103a1d30be0c44b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPT2jUNTGc9mYTd0ZNLS0g.jpeg" /><figcaption>Every node pointing to another</figcaption></figure><blockquote>How much time does it take to search in a linked list?</blockquote><p>Searching in a linked list takes O(n) steps since you always need to start from the first node and then follow up to the second one, unlike arrays where you can jump to any locations easily.</p><blockquote>How much time does it take to insert into a linked list?</blockquote><p>If we sacrifice order, it would take us constant time to insert into a linked list since you only need to change the pointer from an old address to a new one.</p><p>Now let’s look at resizing in both arrays and linked list</p><p>using realloc() to resize an array</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea6ce7c1bc5c105da3c4beb06320b4c6/href">https://medium.com/media/ea6ce7c1bc5c105da3c4beb06320b4c6/href</a></iframe><p>realloc(address *p, size int) hands in back the memory address by you already asked by using malloc() and also resize it to suit your needs. It also copies the value in the old memory address and paste to the new one.</p><blockquote>How about inserting a new node in the middle of a linked list?</blockquote><p>First, we need to update the new node’s next field. This way, we won’t orphan nodes in the original linked list. (In this example, 2,4 and 5 won’t get orphaned.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSoJnr58jii4s8VuiikyCw.jpeg" /><figcaption>Insert a new node in the middle</figcaption></figure><pre>node-&gt;next = list;</pre><p>Next, update the list to point at the new node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-aqaa12z1a6LQRmlzH-rQ.jpeg" /><figcaption>update the pointer</figcaption></figure><pre>list = n;</pre><h3>Tree</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQ6ejNCihpTS_hKbk7cgmA.jpeg" /><figcaption>Tree</figcaption></figure><p>Tree is a recursive data structure. Every node is a tree itself. This data structure implements dynamism by using nodes. Also, it preserved an important order for binary search by making sure that right child is always more, left child is always less. Its downside is taking more space to store pointers.</p><p>define a node in tree:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/876349faceae53ba4c77ad1e261c25f9/href">https://medium.com/media/876349faceae53ba4c77ad1e261c25f9/href</a></iframe><p>Searching in a tree is a recursive process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f453d099f989afa6d6466e9da62e5c7b/href">https://medium.com/media/f453d099f989afa6d6466e9da62e5c7b/href</a></iframe><blockquote>How much time does it take to insert an element into a tree?</blockquote><p>O(log(n)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQ6ejNCihpTS_hKbk7cgmA.jpeg" /><figcaption>Insert into a tree</figcaption></figure><p>Say we want to insert 8 in the above tree. We start from the root, and go to the right sub tree, the right sub tree and then find a place to insert. It turns out that the height of the tree is the maximum time we spend looking for a right place to insert. In this case, it’s log8, which is 3.</p><p>The height of a binary search tree is log(n).</p><p>Let’s look at a more perverse example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SaCsrGysTFN507wP5sZdgA.jpeg" /><figcaption>tree with only right children</figcaption></figure><p>If we have a tree with 1 be the root and 2, 3 be the following elements, we will end up being like this, kind of like a linked list. In this case, it takes O(n) time to search. How can we solve this problem?</p><p>The answer is pretty simple, just make 2 the new root and a balanced tree shows up. It might take some time to ensure you creating a balanced tree in your program. But as your data gets larger, the time you spent on creating a balanced tree would indeed benefit you more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2v85nALmShAOi4SIPEW7g.jpeg" /><figcaption>balanced tree</figcaption></figure><h3>Hash table</h3><p>Hash table is an array of linked list. Say we record everyone’s name by storing these names in alphabetical order. Now every letter has its own linked list, just like a chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9XiBo7NXfrYAt_FLrC2Qw.jpeg" /><figcaption>Hash table</figcaption></figure><p>How do we search in a hash table?</p><p>First, we need a hash function that helps us find the right linked list to start our search.</p><p><strong>input ⇒ hash function ⇒ output</strong></p><p>For example, if we want to find Bill, by giving Bill as an input to the hash function and gets 2 as the output, we know Bill could only exist in the second linked list. This saves us a ton of time looking up from the first linked list to the last one.</p><p>As you can see from the above picture, some of the names takes longer times to be found, like names starting with H would take 3 steps. As names starting with H gets bigger, it would be not so time effieicent to search for them.</p><p>To solve this issue, you can look at more letters when storing. For example, instead of only having the H bucket, you can store Ha, Haa or so separately, avoiding collision.</p><p>Although this solution could save you time searching, it also takes up huge memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-76iT4jZiWsV9ORZWYgPw.jpeg" /><figcaption>Inserting more buckets</figcaption></figure><p>A hash table helps you to bucketize your inputs and get access to data more quickly.</p><p>How much time does it take to search in a hash table?</p><p>O(n), take a deck of cards for instance, if we sort them according to suits in advance, the time it takes to find a card in them gets shortened from 52 steps to 13 steps. When it comes to theory, it is still O(n) just like searching in a linked list. But in the real world, it is indeed faster than searching in a linked list.</p><h3>Trie</h3><p>A trie is a tree, each of whose nodes is an array. And each of the arrays is an array of pointers to other nodes.</p><p>In this picture, each node is a 26-sized array. We store each letter in one node and it would point to the next letter in another node. By following the next pointer, we are able to know if a name exist. No matter how many names are stored, it takes constant time to search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtANwG5jdKA7evERKYRi7Q.jpeg" /><figcaption>Trie</figcaption></figure><p>It can attain the ultimate goal of time complexity, which is O(1). But it takes too much memory. In the above example, we only store three names, but it takes more than 100 pointers to store some null pointers.</p><h3>Abstract data structure</h3><p>A mental structure you can imagine, implementing some real world problems, that’s implemented with some other data structures.</p><h4>queue</h4><p>It has a famous property called FIFO, first in, first out.</p><ul><li>enqueue: get into a queue</li><li>dequeue: get out of a queue</li></ul><p>The idea of queue in code can be implemented using either array or linked list, these lower level implementation details.</p><h4>stack</h4><p>It has a property called LIFO, last in, first out.</p><ul><li>push: add element into a stack</li><li>pop: remove element from a stack</li></ul><h4>dictionary</h4><p>A dictionary allows you to associate keys with values.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bc8af49757a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 Week4 Memory]]></title>
            <link>https://debbiecamera0704.medium.com/cs50-week4-memory-b5cf4b837c3f?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5cf4b837c3f</guid>
            <category><![CDATA[cs50]]></category>
            <category><![CDATA[computer-memories]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Tue, 12 Apr 2022 03:23:33 GMT</pubDate>
            <atom:updated>2022-04-12T03:28:58.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TL_YBOCFtkIvwQUxVL7dMQ.png" /><figcaption>CS50 Week4 Memory</figcaption></figure><h3>hexadecimal</h3><p>hex means 16</p><p>hexadecimal: 0,1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F</p><blockquote>Why do scientists like to use hexadecimal?</blockquote><p>16 can represent 4 binary digits, which is 1111 in binary base. (2 * 2 * 2 * 2 = 16). With just two hexadecimal digits, we can express any number from 0 to 255. To do the same in binary, we need 8 digits. As number getting larger and larger, we need more digits to represent values.</p><p>People often use prefix like 0* to indicate the usage of hexadecimal, otherwise it might get mixed up with decimal.</p><p>e.g. 0*48 (a hexadecimal number 48)</p><p>RGB is a system that uses hexadecimal to represent different colors.</p><p>e.g. 000000 = black, FFFFFF = white</p><p>Memory, today’s topic, is also an example that uses hexadecimal.</p><p>Memory address starts from 0, all the way up to FF like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwwAYDjd7qbkIBhY5dIOXA.png" /><figcaption>Hexadecimal memory address</figcaption></figure><h3>Pointer</h3><p>A variable that contains the address of other value. Its type is int * and takes up 8 bytes in most of the time.</p><p>&amp;: <strong>address operator</strong>, <strong>gets the address. </strong>When you put an ampersand before a variable, C gives you the address that the variable is stored in.</p><p>*: <strong>dereference operator</strong>, <strong>goes to the address. </strong>When you put an star sign before a variable, C goes to the address and return the value stored inside.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68d37b183dcb4554f862fc7c3d5c13a8/href">https://medium.com/media/68d37b183dcb4554f862fc7c3d5c13a8/href</a></iframe><blockquote>What does the memory look like?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSGQOr295zYET-PdiL-Edg.png" /><figcaption>pointer in the memory</figcaption></figure><p>The pointer p is also a variable stored in somewhere in the memory. But we don’t need to care about where p is stored. All we need to know is that the value of p is the address of n, in this case, 50. <strong>P is just a pointer that points to the address of int n.</strong></p><h4>String in memory</h4><p>string s = “HI!” What does this line of code look like in the memory?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*iMsn36erTeMy0SaexHwuvA.png" /><figcaption>string in the memory</figcaption></figure><p>We know <strong>string is an array of chars that are stored back to back in the memory</strong>, that is, they are stored one byte apart. That’s why you see the memory address is in order.</p><blockquote>What about s?</blockquote><p>The value of s is <strong>the address of the first character in the string</strong>. In the above example, it would be 0x123.</p><blockquote>How does the computer know the end of the string?</blockquote><p>When hitting the value of \0, the null character, we know we are at the end of a string. <strong>Variable s is just a pointer pointing to the address of the first character.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4deb43f1f1924ff0204c8d92c7bd3b77/href">https://medium.com/media/4deb43f1f1924ff0204c8d92c7bd3b77/href</a></iframe><p>The data type string does not exist in C. More precisely, it exists in C as char star. &lt;cs50.h&gt; just make a custom data type called string.</p><p>This line of code:</p><p>char *s = &quot;HI!&quot;;</p><p>equals these lines of code in &lt;cs50.h&gt;</p><pre>typedef char *string;<br>string s = &quot;HI!&quot;</pre><h4>Pointer arithmetic</h4><p>Remember we can use s[1] to get the second element in string s? It is actually a syntactic sugar. We know a pointer in C is an address, which is a numeric value. By incrementing the pointer by 1, the program gives us access to each of the succeeding elements in the array just like what below shows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd63aed3432061be8cb22ba9e10c9d0c/href">https://medium.com/media/fd63aed3432061be8cb22ba9e10c9d0c/href</a></iframe><h4>String comparison</h4><p>Suppose we want to compare two strings. With the program below, even when we type in two identical strings, the result still turns out to be different. Why?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03cec97325cbe1321c8a00a6b2e187a8/href">https://medium.com/media/03cec97325cbe1321c8a00a6b2e187a8/href</a></iframe><p>That’s because s and t represent the address of the first character in the string, not the character itself.</p><h4><strong>String copy</strong></h4><p>Now let’s look at another example. We want to create t which copies the value of s, and then change the element in t without modifying s. However, it turns out that both s and t got changed afterwards.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40c9bb85eb8f94f22f36c64f9514249e/href">https://medium.com/media/40c9bb85eb8f94f22f36c64f9514249e/href</a></iframe><p>That’s because in copy.c, s and t both refer to the same address. When t[0] got changed, s[0] also got changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*EC5PoJUjjavR_QNNsYgtuQ.png" /><figcaption>copy.c</figcaption></figure><blockquote>How to copy string values rather than memory addresses?</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/466e7cefd09202311d9f1e6759d226d6/href">https://medium.com/media/466e7cefd09202311d9f1e6759d226d6/href</a></iframe><h3>Malloc() and free()</h3><blockquote>function malloc(int num): memory allocation</blockquote><p><em>syntax:</em> char *t = malloc(4);(allocate 4 bytes to t’s memory)</p><p>The malloc function <strong>returns the first address of the chuck of memory</strong> that it has allocated for you. But sometimes it may return a nul pointer when there’s no memory available. Thus, better check for the return value when using this function.</p><p>NULL, is not the same as nul, it’s a nul pointer, an empty address.</p><p>nul, or \0, is a null character.</p><blockquote>function strcpy(destination, source)</blockquote><p>strcpy function helps you to copy strings.</p><blockquote>functionfree(pointer)</blockquote><p>Contrary to malloc(), free function returns the memory allocated by malloc(), calloc(), and realloc() back to the computer, this way you won’t run out of memory. It’s better to always give the memory back after you are done with the program. Just give the memory address you want to release as the input, the function will free the memory.</p><h3>valgrind</h3><p>Another useful debug tool for detecting potential memory problems</p><p>It helps detect any memory related problems. When you do not use free() to release memory, when you touch any memory that you should not(segmentation fault), and when memory leaks, valgrind reports the problem to you.</p><p>How to use valgrind? Write a problematic program first</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d6d909de41ee182477bafdd03a31604/href">https://medium.com/media/5d6d909de41ee182477bafdd03a31604/href</a></iframe><p>call valgrind to detect problems: valgrind ./memory.c</p><p>Errors:</p><p>Invalid write of size 1</p><p>⇒ A write refers to changing a value. In the above example, we only ask for three bytes, and are not supposed to change the value in the fourth byte.</p><p>Invalid read of size 1</p><p>⇒ A read refers to reading, using or printing a value. In the above example, we print out the whole string, which includes a memory address that we should not have touched.</p><p>LEAK SUMMARY: ==705== definitely lost: 3 bytes in 1 blocks</p><p>⇒ We do not free the memory got from malloc() at the end of the program.</p><h3>Memory layout</h3><p>Say we write a function called swap, it should swap the values of two variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1a36a55f187da9a5acb7f1fa806d758/href">https://medium.com/media/c1a36a55f187da9a5acb7f1fa806d758/href</a></iframe><p>Why the above program does not swap values of x and y successfully?</p><p><strong>It turns out that computer treats different portions in computer’s memory in different ways.</strong> Everything are stored in a standard location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*53lzULx8YHX6V1mLeE00_Q.png" /><figcaption>memory usage in C</figcaption></figure><p><strong>Machine code</strong>: The 0s and 1s that compose your program</p><p><strong>global variables</strong>: Constants that are put outside your functions</p><p><strong>heap</strong>: a chunk of memory that malloc() uses to get some extra space. And you need to use free() at the end to release memory</p><p><strong>stack</strong>: When calling functions, like main(), strlen(), strcmp(), you are using spaces called stack space to store some local variables and parameters. Don’t need to use free() function at the end because when functions are executed, they are popped and removed from the space.</p><p>As you can see from the picture, stack and heap spaces point at one another. We typically have enough memory, so these two spaces won’t collide.</p><p>In the above program, we call function swap. It does swap values, but the values are just the copies of x and y. The real x and y in the main function remain unchanged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuFmgrR8o3Oz7VcM_Tp_Vw.png" /><figcaption>how stack works</figcaption></figure><p>How to fix the problem?</p><p>Pass pointers instead so this time we are not just copying x and y’s values and passing them to swap(), but actually going to the addresses of them and making changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c78f0e839a47313e3fa3247b3765a427/href">https://medium.com/media/c78f0e839a47313e3fa3247b3765a427/href</a></iframe><p><strong>stack overflow</strong>: Calling too many functions till the memory overflows the heap memory</p><p><strong>heap overflow</strong>: A form of buffer overflow. It happens when a chunk of memory is allocated to heap, and data is written into the memory without any bound checking, leading to internal structures being overwritten.</p><p>some critical data structures in heap are overwritten,</p><p><strong>buffer overflow</strong>: Buffer is a chunk of memory, an array of memory that temporarily holds data while it is being transferred from one location to another. A buffer overflow (or buffer overrun) occurs when the volume of data exceeds the storage capacity of the memory buffer and thus the program attempts to overwrite adjacent memory locations.</p><h3>Scanf</h3><p>Some of the useful functions in CS50 library can actually be implemented using scanf in C’s library, like get_int(), get_string() and so forth.</p><p><em>syntax: </em>scanf(%i, &amp;i); (datatype of the input, pointer to a variable to store the input)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23e60f8dc57b4864886fe9e74d5dc0ae/href">https://medium.com/media/23e60f8dc57b4864886fe9e74d5dc0ae/href</a></iframe><p>Possible errors:</p><ul><li>scanf() won’t check for the data type of user’s input. For example, if you type in a string in the above example, the final xwould be 0. No errors pop up.</li><li>scanf() won’t check how many bytes can be stored in the variable. If you type in a long int in the above example, the final x would not be what you expected and no errors are shown.</li></ul><h3>file I/O</h3><p>taking input and output from files</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ab7f00dec1ac5fe4e36ea726cf2cb0a/href">https://medium.com/media/4ab7f00dec1ac5fe4e36ea726cf2cb0a/href</a></iframe><p>FILE is a data type that represents a file.</p><p>fopen(filename, mode) opens the file in a certain mode. Mode includes read, write and append. Append mode means to add new text to the file.</p><p>jpeg.c helps determine if a file is probably a jpeg. And copy.c is similar to the command cp we use in the Linux system. Both of them use the data type FILE.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7934399cc9f1862812a9259cb0e47bc3/href">https://medium.com/media/7934399cc9f1862812a9259cb0e47bc3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39bd61f34cda78d2f79d693121c9c88e/href">https://medium.com/media/39bd61f34cda78d2f79d693121c9c88e/href</a></iframe><h3>References</h3><p>CS50 Week 4 lesson: <a href="https://cs50.harvard.edu/x/2021/weeks/4/">https://cs50.harvard.edu/x/2021/weeks/4/</a></p><p>Slides: <a href="https://cdn.cs50.net/2020/fall/lectures/4/lecture4.pdf">https://cdn.cs50.net/2020/fall/lectures/4/lecture4.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5cf4b837c3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[從排序學演算法( 3 ) — Merge Sort]]></title>
            <link>https://debbiecamera0704.medium.com/%E5%BE%9E%E6%8E%92%E5%BA%8F%E5%AD%B8%E6%BC%94%E7%AE%97%E6%B3%95-3-merge-sort-76a5fe46f9f8?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/76a5fe46f9f8</guid>
            <category><![CDATA[merge-sort]]></category>
            <category><![CDATA[divide-and-conquer]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[js]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 09:35:21 GMT</pubDate>
            <atom:updated>2022-03-20T09:35:21.429Z</atom:updated>
            <content:encoded><![CDATA[<h3>從排序學演算法( 3 ) — Merge Sort</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*kOd2vwxRj8fGkF20SZPvWQ.png" /><figcaption><a href="https://en.wikipedia.org/wiki/User:VineetKumar">VineetKumar</a> at <a href="https://en.wikipedia.org/wiki/">English Wikipedia</a> 2007</figcaption></figure><p>Merge sort 使用到的是 Divide and conquer 這個方法，把大問題先切割成一個個小問題，等所有小問題解決之後，大問題也解決了。有點像規劃一個旅遊行程時，你會先處理其中的小問題，比方要住哪裡，要去哪邊，用甚麼交通工具… 等你把這些小問題全部想清楚了，整個旅遊計畫也就完成了。</p><h4><strong>Merge Sort</strong></h4><p>💡 先排序小陣列，利用遞迴方式慢慢排序到整個陣列</p><p>演算法主要分成兩個步驟，分別是切割以及合併。</p><p><strong>步驟：</strong></p><ol><li>將陣列切割到最小單位，也就是一個元素的長度</li><li>接著兩兩元素進行排列，並慢慢增加排序數量，直到完成排序</li></ol><h4>切割</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*ys6SQ_uBPQQ-vI1tGcxVIg.png" /><figcaption><a href="https://en.wikipedia.org/wiki/User:VineetKumar">VineetKumar</a> at <a href="https://en.wikipedia.org/wiki/">English Wikipedia</a> 2007</figcaption></figure><p>如上圖所示，第一步是把問題縮小，先排序小陣列。因此我們把陣列不斷切割，直到最後只剩下一個元素。一個有 n 個元素的陣列，分割的次數是 n-1 次，圖中原本有 8 個元素，經過 7 次分割才完成。</p><p><strong>分割的時間複雜度為 n-1</strong></p><h4>合併</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*4aZnjreZC5tZAjS8FpzBpg.png" /><figcaption><a href="https://en.wikipedia.org/wiki/User:VineetKumar">VineetKumar</a> at <a href="https://en.wikipedia.org/wiki/">English Wikipedia</a> 2007</figcaption></figure><p>接下來是重頭戲，把剛剛切好的元素排序完再合併回去。拿圖中由左至右四個元素來輔助說明：</p><p>(1) 第一步 [38], [27], [43], [3] 這四個小陣列兩兩進行合併，<strong>合併方式是比較最左側的元素大小，比較小的元素就放左側</strong></p><p>(2) 因為目前小陣列都只有一個元素，沒有左右之分，直接比大小 + 合併後產生 [27, 38] 和 [3, 43] 這兩個新陣列</p><p>(3) 再來進行一次合併，記得剛剛的合併方式是比較最左側的元素誰比較小嗎？現在兩個陣列最左側的元素分別是 27 和 3，因為 3 比較小所以擺第一個，接著是 27，再來繼續進行比較，依序將 38 和 43 放到陣列</p><p>(4) 最一開始倒數的三個小陣列，也就是 [9], [82], [10] 也比照一樣的方式合併，最後會產生 [9, 10, 82]，最後再和 [3, 27, 38, 43] 做一次合併，就會產生一個排序過的陣列，此時整個排序結束</p><p>每次合併的過程中，都是將兩個小陣列各自最左側的元素拿來一一比較，如果整個陣列有 n 個元素，就會經過 n 次合併步驟。</p><p>merge sort 的合併方式是從小陣列到大陣列慢慢合併，將兩個小陣列合併的過程當作一回合的話，總共合併的回合數會是 log n</p><p><strong>合併的時間複雜度 = 合併步驟 * 合併回合數 = n log n</strong></p><h4>遞迴</h4><p>把上述的步驟寫成程式碼，你也許會好奇如何把陣列切到最小再開始合併呢？這裡會使用遞迴的方式達成。先來看一段簡單的程式碼：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0036fd1d46a724086edf8b4972de2652/href">https://medium.com/media/0036fd1d46a724086edf8b4972de2652/href</a></iframe><p>程式結果最後會從 7 一路倒數印到 1 為止。程式主要邏輯是判斷 num 是否為0，如果是的話就結束，不然就印出當前數字並再一次呼叫函式本身。</p><p>像這樣子，程式碼中包含自我呼叫(self-calling)的函式我們就稱為遞迴。這邊很重要的一點是設定 base case, 也就是在什麼樣的情況下要停止自我呼叫，不然會產生無窮遞迴。以 countDown 的例子來說，我們希望倒數到 0 就停止。回到 Merge sort 來說，我們希望把陣列切割到只剩一個元素並開始合併，因此這裡的 base case 就是陣列長度為 1 的時候</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49de29806593feb91a2642a35eba10d2/href">https://medium.com/media/49de29806593feb91a2642a35eba10d2/href</a></iframe><p><strong>程式碼：</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af96cb7135cb17f73eb5c280f68c7a3b/href">https://medium.com/media/af96cb7135cb17f73eb5c280f68c7a3b/href</a></iframe><p><strong>時間複雜度：O(n log n)</strong></p><p>將分割和合併步驟相加會得到 n-1 + n log n，常數省略不計得 n log n</p><p><strong>空間複雜度：O(n)</strong></p><p>每一次合併都要使用新的記憶體空間存放合併結果</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76a5fe46f9f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 pset3 Tideman (Merge sort)]]></title>
            <link>https://debbiecamera0704.medium.com/cs50-pset3-tideman-merge-sort-ea4e5e953f62?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea4e5e953f62</guid>
            <category><![CDATA[elections]]></category>
            <category><![CDATA[merge-sort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[cs50]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 11:04:24 GMT</pubDate>
            <atom:updated>2022-03-14T11:04:24.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vr28NqHebU9mGQFt" /><figcaption>Photo by <a href="https://unsplash.com/@element5digital?utm_source=medium&amp;utm_medium=referral">Element5 Digital</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is a step-by-step tutorial on how I solved the problem Tideman in CS50 week3.</p><p>Before you continue, make sure you fully understand the problem, which centers on the Tideman election and is explained carefully <a href="https://cs50.harvard.edu/x/2021/psets/3/tideman/">here</a>.</p><p>The main goal of the problem is to turn the ranked-choice voting system into codes. The main function is already written as the following shows and our tasks are to complete all the functions that have the comments “TO-DO” inside. (It is also allowed to create new functions when necessary.)</p><pre>#include &lt;cs50.h&gt;<br>#include &lt;stdio.h&gt;</pre><pre>// Max number of candidates<br>#define MAX 9</pre><pre>// preferences[i][j] is number of voters who prefer i over j<br>int preferences[MAX][MAX];</pre><pre>// locked[i][j] means i is locked in over j<br>bool locked[MAX][MAX];</pre><pre>// Each pair has a winner, loser<br>typedef struct<br>{<br>    int winner;<br>    int loser;<br>}<br>pair;</pre><pre>// Array of candidates<br>string candidates[MAX];<br>pair pairs[MAX * (MAX - 1) / 2];</pre><pre>int pair_count;<br>int candidate_count;</pre><pre>// Function prototypes<br>bool vote(int rank, string name, int ranks[]);<br>void record_preferences(int ranks[]);<br>void add_pairs(void);<br>void sort_pairs(void);<br>void lock_pairs(void);<br>void print_winner(void);</pre><pre>int main(int argc, string argv[])<br>{<br>    // Check for invalid usage<br>    if (argc &lt; 2)<br>    {<br>        printf(&quot;Usage: tideman [candidate ...]\n&quot;);<br>        return 1;<br>    }</pre><pre>// Populate array of candidates<br>    candidate_count = argc - 1;<br>    if (candidate_count &gt; MAX)<br>    {<br>        printf(&quot;Maximum number of candidates is %i\n&quot;, MAX);<br>        return 2;<br>    }<br>    for (int i = 0; i &lt; candidate_count; i++)<br>    {<br>        candidates[i] = argv[i + 1];<br>    }</pre><pre>// Clear graph of locked in pairs<br>    for (int i = 0; i &lt; candidate_count; i++)<br>    {<br>        for (int j = 0; j &lt; candidate_count; j++)<br>        {<br>            locked[i][j] = false;<br>        }<br>    }</pre><pre>    pair_count = 0;<br>    int voter_count = get_int(&quot;Number of voters: &quot;);</pre><pre>// Query for votes<br>    for (int i = 0; i &lt; voter_count; i++)<br>    {<br>        // ranks[i] is voter&#39;s ith preference<br>        int ranks[candidate_count];</pre><pre>// Query for each rank<br>        for (int j = 0; j &lt; candidate_count; j++)<br>        {<br>            string name = get_string(&quot;Rank %i: &quot;, j + 1);</pre><pre>            if (!vote(j, name, ranks))<br>            {<br>                printf(&quot;Invalid vote.\n&quot;);<br>                return 3;<br>            }<br>        }</pre><pre>        record_preferences(ranks);</pre><pre>        printf(&quot;\n&quot;);<br>    }</pre><pre>    add_pairs();<br>    sort_pairs();<br>    lock_pairs();<br>    print_winner();<br>    return 0;<br>}</pre><pre>// Update ranks given a new vote<br>bool vote(int rank, string name, int ranks[])<br>{<br>    // TODO<br>    return false;<br>}</pre><pre>// Update preferences given one voter&#39;s ranks<br>void record_preferences(int ranks[])<br>{<br>    // TODO<br>    return;<br>}</pre><pre>// Record pairs of candidates where one is preferred over the other<br>void add_pairs(void)<br>{<br>    // TODO<br>    return;<br>}</pre><pre>// Sort pairs in decreasing order by strength of victory<br>void sort_pairs(void)<br>{<br>    // TODO<br>    return;<br>}</pre><pre>// Lock pairs into the candidate graph in order, without creating cycles<br>void lock_pairs(void)<br>{<br>    // TODO<br>    return;<br>}</pre><pre>// Print the winner of the election<br>void print_winner(void)<br>{<br>    // TODO<br>    return;<br>}</pre><p>In the following will be explaining the logic behind each function and how to put these ideas into codes.</p><pre>// Query for votes<br>    for (int i = 0; i &lt; voter_count; i++)<br>    {<br>        // ranks[i] is voter&#39;s ith preference<br>        int ranks[candidate_count];</pre><pre>// Query for each rank<br>        for (int j = 0; j &lt; candidate_count; j++)<br>        {<br>            string name = get_string(&quot;Rank %i: &quot;, j + 1);</pre><pre>            if (!vote(j, name, ranks))<br>            {<br>                printf(&quot;Invalid vote.\n&quot;);<br>                return 3;<br>            }<br>             <br>            record_preferences(ranks);</pre><pre>            printf(&quot;\n&quot;);</pre><pre>        }<br>      ...</pre><p>Inside the main function, the first thing is to ask for voter’s preferences and record them by calling the vote function. Let’s say we have three candidates. When voting, each voter will first be asked their favorite candidate and then store the value in ranks, then he or she will be asked the second favorite candidate … the whole process would iterate three times.</p><h4><strong>vote</strong></h4><p>Voters give us a list of candidates ordered by their preferences and we store their choices into ranks.</p><p>The first parameter, integer rank, means the ith favorite candidate of the voter. Looping through each candidate, when candidates[i] matches the name, we get the index of the candidate and update the ranks. Otherwise, we know the name is not valid and should return false.</p><pre>// Update ranks given a new vote<br>bool vote(int rank, string name, int ranks[])<br>{<br>    // ranks[i] is the index of the candidate who is the ith preference for the voter<br>    for (int i = 0; i &lt; candidate_count; i++)<br>    {<br>        if (strcmp(candidates[i], name) == 0)<br>        {<br>            ranks[rank] = i;<br>            return true;<br>        }<br>    }<br>    return false;<br>}</pre><h4>record_preferences</h4><p>After recording all the preferences of a voter in ranks, we have to update the preferences array. This array is a 2D array that indicates how many voters prefer candidates[i] to candidates[j]. It collects every voters’ choices. For instance, if preferences[2][1] = 5, that means 5 voters like candidates[2] more than candidates[1].</p><p>Inside the function, we use a nested loop. Notice the inner loop starts from i + 1 instead of i since we don’t need to compare the preferences between two identical candidates.</p><pre>// Update preferences given one voter&#39;s ranks<br>void record_preferences(int ranks[])<br>{<br>    // TODO<br>    for (int i = 0; i &lt; candidate_count -1; i++)<br>    {<br>        for (int j = i + 1; j &lt; candidate_count; j++)<br>        {<br>            {<br>                preferences[ranks[i]][ranks[j]]++;<br>            }<br>        }<br>    }<br>    return;<br>}</pre><h4>add_pairs</h4><p>Next, we are going to add pairs where one is preferred over the other. This step helps us figure out the winner and loser of every single pair.</p><p>To determine the winner and loser of each pair, we use a nested for loop and see if preferences[i][j] &gt; preferences[j][i]. If it does, then candidates[i] wins against candidates[j], and vice versa. Record the winner and loser in pairs and increment pair_count. (Don’t forget pair_count is initialized to 0 in the beginning)</p><p>For pairs that have the same amount of votes, like preferences[1][2] = 4 and preferences[2][1] = 4, neglect them.</p><pre>// Record pairs of candidates where one is preferred over the other<br>void add_pairs(void)<br>{<br>    // if there is a tie between pairs, do not add them<br>    for (int i = 0; i &lt; candidate_count -1; i++)<br>    {<br>        for (int j = i + 1; j &lt; candidate_count; j++)<br>        {<br>            {<br>                if (preferences[i][j] &gt; preferences[j][i])<br>                {<br>                   pairs[pair_count].winner = i;<br>                   pairs[pair_count].loser = j;<br>                   pair_count++;<br>                }<br>                else if (preferences[i][j] &lt; preferences[j][i])<br>                {<br>                   pairs[pair_count].winner = j;<br>                   pairs[pair_count].loser = i;<br>                   pair_count++;<br>                }<br>            }<br>        }<br>    }<br>    return;<br>}</pre><h4>merge_sort</h4><p>Now let’s sort pairs according to the strength of victory. Why do we need to sort? That’s because we need to lock the pairs later. To lock the pair, we have to first search for the strongest pair. This step would greatly facilitate the following step.</p><p>In CS50 week3, we learned three sorting algorithms: selection sort, bubble sort and merge sort. Feel free to pick the one that you are comfortable with. I picked merge sort just to give myself a challenge.</p><p>Because the strength of victory comes from the preferences array, we need to pass both the winner and loser of the pair to preferences. That’s why you see preferences[left_winner][left_loser] in codes. It might look a bit complicated. But as long as you know what parameter you should use, everything makes sense.</p><pre>void merge_sort(int i, int j, pair pair_example[], pair temp[])<br>{   <br>    // i = the first index of array, j = the last index of array<br>    if (j &lt;= i)<br>    {<br>        return;<br>    }</pre><pre>    int mid = (i + j) / 2;</pre><pre>    merge_sort(i, mid, pairs, temp);<br>    merge_sort(mid + 1, j, pairs, temp);</pre><pre>    int left_pointer = i;<br>    int right_pointer = mid + 1;</pre><pre>    for (int k = i; k &lt; j + 1; k++) <br>        // k is the index of the start of array<br>    {<br>        int left_winner = pair_example[left_pointer].winner;<br>        int left_loser = pair_example[left_pointer].loser;<br>        int right_winner = pair_example[right_pointer].winner;<br>        int right_loser = pair_example[right_pointer].loser;</pre><pre>        if (left_pointer == mid + 1) // left array reaches its end<br>        {<br>            temp[k] = pair_example[right_pointer];<br>            right_pointer++;<br>        }<br>        else if (right_pointer == j + 1) // right array reaches its end<br>        {<br>            temp[k] = pair_example[left_pointer];<br>            left_pointer++;<br>        }<br>        else if (preferences[left_winner][left_loser] &gt; preferences[right_winner][right_loser])<br>        {<br>            temp[k] = pair_example[left_pointer];<br>            left_pointer++;<br>        }<br>        else<br>        {<br>            temp[k] = pair_example[right_pointer];<br>            right_pointer++;<br>        }<br>    }</pre><pre>    for (int k = i; k &lt; j + 1; k++)<br>    {<br>        // copy sorted array into original pair<br>        pair_example[k] = temp[k];<br>    }<br>}</pre><h4>sort_pairs</h4><p>Implement merge_sort to sort_pairs.</p><pre>// Sort pairs in decreasing order by strength of victory<br>void sort_pairs(void)<br>{<br>    pair temp[pair_count];<br>    merge_sort(0, pair_count - 1, pairs, temp);<br>    return;<br>}</pre><h4>has_cycle</h4><p>This function will be called by locked_pairs. To lock a pair, we start from the strongest pair and check whether this pair would create a cycle. If it does not, then we lock the pair.</p><p>If you are not that clear on what is a cycle and why we should avoid that, visit this <a href="https://gist.github.com/nicknapoli82/6c5a1706489e70342e9a0a635ae738c9">link</a> first. The author explained the whole concept thoroughly and helped me figure out the flaws in my previous thoughts.</p><p>To see if a pair will create a cycle, first you check if locked[cycle_end][cycle_start] equals to true. If it does, that means locking [cycle_start][cycle_end] would definitely create a cycle.</p><p>e.g. a =&gt; b =&gt; a (cycle created)</p><p>If it does not, continue to check if cycle_end is the cycle_start of any locked pair, since this condition could lead to a cycle.</p><p>e.g. Say we have a sorted pair like this:</p><p>[(d, a), (a, b), (b, c), <strong><em>(c, a)</em></strong>, (d, b), (d, c)]</p><p>The first three pairs are locked successfully without creating any cycle. However, in the fourth pair, a, the current cycle_end, is the cycle_start of (a, b), and b finally points to c, the current cycle_start. A cycle would be created if (c, a) is locked. (d =&gt; a =&gt; b =&gt; <strong><em>c =&gt; a</em></strong>)</p><p>To avoid this situation, check whether b, the cycle_end of (a, b), would eventually end with c. Here, we use recursion to repeatedly check for potential cycles. We also need to define the base case of recursion, where the cycle is found and recursion stops.</p><p>d =&gt; a =&gt; b =&gt; <strong><em>c =&gt; a</em> (cycle created)</strong></p><pre>bool has_cycle(int cycle_start, int cycle_end)<br>{<br>    if (locked[cycle_end][cycle_start]) //base case<br>    {<br>        return true;<br>    }</pre><pre>for (int i = 0; i &lt; candidate_count; i++)<br>    {<br>        if (locked[cycle_end][i] == true &amp;&amp; has_cycle(cycle_start, i)) // create a cycle<br>        {<br>            return true;<br>        }<br>    }<br>    return false;<br>}</pre><h4>lock_pairs</h4><p>If a cycle would not be created, lock the pair.</p><pre>// Lock pairs into the candidate graph in order, without creating cycles<br>void lock_pairs(void)<br>{<br>    // TODO<br>    for (int i = 0; i &lt; pair_count; i++)<br>    {<br>        if (!has_cycle(pairs[i].winner, pairs[i].loser))<br>        {<br>            locked[pairs[i].winner][pairs[i].loser] = true;<br>        }<br>    }<br>}</pre><h4>print_winner</h4><p>Finally, print out the winner. A winner has no arrows pointing to him/her, suggesting that no one beats him/her. Remember we just lock the pairs. Since winner never lose, there must be no locked pair where the winner is the second index.</p><p>e.g. If the winner is candidate[3], then looping through each candidate as i, locked[i][3] must always equal to false.</p><p>So what we can do now is looping through all the candidate with a nested loop. Since winner never lose, every candidate[i][winner_index] would produce a false. And when the false_count equals to candidate_count -1 (candidate[i][i] must equal to false, so don’t count it), we found the winner.</p><pre>// Print the winner of the election<br>void print_winner(void)<br>{<br>    // TODO<br>    for (int col = 0; col &lt; candidate_count; col++)<br>    {<br>        int false_count = 0;<br>        for (int row = 0; row &lt; candidate_count; row++)<br>        {<br>            if (locked[row][col])<br>            {<br>                break;<br>            }<br>            if (!locked[row][col])<br>            {<br>                false_count++;<br>                if (false_count == candidate_count - 1) // No one has won against the candidate<br>                {<br>                    printf(&quot;%s\n&quot;, candidates[col]);<br>                    break;<br>                }<br>            }<br>        }<br>    }<br>    return;<br>}</pre><p>Voila! After submitting the solution to check50, you should be able to see green smiling faces on the screen. It was such a great relief that I finally solved the problem.</p><p>To see the full solution to this problem, please refer to this <a href="https://gist.github.com/debbie8820/ebad8a8b2e7bf1e355d4a248a3152e4f">link</a>. If there is any error or anything I missed, feel free to let me know. Hope you find something helpful in this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea4e5e953f62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[從排序學演算法( 2 ) — Bubble Sort]]></title>
            <link>https://debbiecamera0704.medium.com/%E5%BE%9E%E6%8E%92%E5%BA%8F%E5%AD%B8%E6%BC%94%E7%AE%97%E6%B3%95-2-bubble-sort-b3dc2ad2c73f?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3dc2ad2c73f</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[bubble-sort]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 11:01:30 GMT</pubDate>
            <atom:updated>2022-03-05T08:49:26.233Z</atom:updated>
            <content:encoded><![CDATA[<h3>從排序學演算法( 2 ) — Bubble Sort</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gtT1HpRhH4KwTls7" /><figcaption>Photo by <a href="https://unsplash.com/@kindandcurious?utm_source=medium&amp;utm_medium=referral">Kind and Curious</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>這次要來介紹的排序演算法是 Bubble Sort，之所以會叫這個可愛的名字是因為使用這個演算法會慢慢將元素移動到最右側，有點像是水中的泡泡慢慢往水面漂一樣，現在還無法領會沒關係，相信跟著步驟走過一遍就會了解這個名字為什麼這樣取了！</p><h4><strong>Bubble Sort</strong></h4><p>💡 兩兩一組依序進行比較，慢慢把數值大的元素換到陣列最右側</p><p><strong>步驟：</strong></p><ol><li>未分類陣列兩兩一組依序做比較</li><li>若左側元素大於右側元素則互相交換位置，否則繼續進行比較</li><li>一輪排序結束後若還沒完成整個陣列的排序則回到步驟1，反覆執行直到完成排序</li></ol><p>陣列一開始為 const array = [67, 14, 28, 2, 35]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*IiMmZbUxZqdj0Ap-Ok8W7Q.jpeg" /><figcaption>初始陣列</figcaption></figure><p>首先從最左邊開始兩兩一組進行比較，67 比較大，要和 14 交換位置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*y3T9fcC0aNZ0zeozDQKjmg.jpeg" /><figcaption>67 和 14 要交換位置</figcaption></figure><p>交換完後接著往下，換成 67 和 28 進行比較。67較大，和 28 交換位置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*jaAO_ZEb5_4Wj_sI7yduPg.jpeg" /><figcaption>67 和 28 要交換位置</figcaption></figure><p>換好後再來是 67 和 2 交換位置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*4HbNvNm2IxLpfrXZwNsLOA.jpeg" /><figcaption>67 和 2 要交換位置</figcaption></figure><p>67 和 35 交換位置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*PVeebhZXhdutXeM0ylKKFQ.jpeg" /><figcaption>67 和 35 要交換位置</figcaption></figure><p>交換好位置後如下圖，會發現只有 35 和 67 排序好，其他元素還沒排序完成，因此繼續從頭進行步驟 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*IRsgPbYdr66xZWZDaf1RWw.jpeg" /><figcaption>第一輪排序後陣列尚未排序完畢</figcaption></figure><p>14 比 28 小，不必更動位置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*mo9bjGf9RtcQOH1-Z3RdLQ.jpeg" /><figcaption>14 和 28 維持不動</figcaption></figure><p>28 比 2 小，兩個要交換位置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*w6EjDF5Wpr02R_WJJlZ38g.jpeg" /><figcaption>28 和 2 互換位置</figcaption></figure><p>此時第二輪的排序結束，再差一步陣列就快排序完了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*3ulg2dpRMq3sqhJGwo9A2Q.jpeg" /><figcaption>第二輪排序結束，還差一點點就要結束了</figcaption></figure><p>14 和 2 再進行交換後，整個陣列就大功告成了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*bzDczcDM2jruigUatRYXIw.jpeg" /><figcaption>14 和 2 位置交換</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*LdK6O6x2-nLHOypbgw6DDQ.jpeg" /><figcaption>整個陣列完成排序</figcaption></figure><p><strong>程式碼：</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95bed46bbb0c2e1b514e7d77422a192e/href">https://medium.com/media/95bed46bbb0c2e1b514e7d77422a192e/href</a></iframe><p><strong>時間複雜度：</strong></p><p>Worst case: O(n²)</p><p>Best case: O(n)</p><p>如果陣列已經先排序好了，在第一輪兩兩比較時沒有任何 swap 就會提前結束排序</p><p><strong>空間複雜度：O(1)</strong></p><p>看著數值最大的元素隨著每次的排序慢慢移動到陣列最右邊，應該不難理解 Bubble Sort 這個名稱的由來了吧！</p><p>以上就是 Bubble Sort 的介紹，如果有興趣看 <a href="https://debbiecamera0704.medium.com/%E5%BE%9E%E6%8E%92%E5%BA%8F%E5%AD%B8%E6%BC%94%E7%AE%97%E6%B3%95-1-selection-sort-53a9178ae71e">Selection Sort 的介紹可以點這裡</a>，有任何問題或心得歡迎留言告訴我！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3dc2ad2c73f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[從排序學演算法( 1 ) — Selection Sort]]></title>
            <link>https://debbiecamera0704.medium.com/%E5%BE%9E%E6%8E%92%E5%BA%8F%E5%AD%B8%E6%BC%94%E7%AE%97%E6%B3%95-1-selection-sort-53a9178ae71e?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/53a9178ae71e</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[selection-sort]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 08:23:36 GMT</pubDate>
            <atom:updated>2022-02-23T14:49:56.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BCKAZ3b6DMk2AVt9" /><figcaption>Photo by <a href="https://unsplash.com/@andretaissin?utm_source=medium&amp;utm_medium=referral">Andre Taissin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>寫程式的時候，遇到排序問題常常都是直接呼叫built-in function來用，卻沒有真正去思考過它背後的演算法為何，這陣子面試剛好有被問到遇到排序的演算法，這才知道原來排序有這麼多種方法，決定用筆記的方式紀錄每個方法的差異。</p><p>首先從最直覺好懂的 Selection Sort 開始介紹。</p><h3>Selection Sort</h3><p>💡 不斷從未排序陣列中找出最小的元素並放到陣列最左側</p><p><strong>步驟：</strong></p><ol><li>找出未排序陣列中最小的元素</li><li>將最小的元素和最左邊的元素交換位置，並回到步驟1，直到整個陣列都完成排序</li></ol><p><strong>圖示解說：</strong></p><p>🟦 未排序元素 🟩 已排序元素 🟧 該次排序時位置有變動的元素</p><p>首先將整個陣列視為已排序過(sorted subarray)以及未排序過(unsorted subarray)的陣列。</p><p>陣列初始化為 const array = [50, 2, 31, 10, 67]，此時整個陣列都未排序。首先找出陣列中最小的元素並和未排序陣列(藍色)最左元素交換位置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*Wa-0H1YDPT1NhNatxTqOhQ.jpeg" /><figcaption>未排序陣列</figcaption></figure><p>從陣列中找出最小的元素並和未排序陣列最左元素交換位置</p><p>以本例來說就是元素 2 和元素 50 互換位置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*UJu-MYxhn4ceYUFsDUoe6Q.jpeg" /><figcaption>元素2和元素50互換位置</figcaption></figure><p>換完後元素 2 就變成已排序陣列(綠色)的一員，接著未排序陣列中最小的元素是 10，和元素 50 互換位置後如下圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*4Iy5NNkbdUyawzjJ55tJSg.jpeg" /><figcaption>元素10和元素50互換位置後</figcaption></figure><p>接著未排序陣列中元素 31 最小，也剛好位於未分類陣列中最左側，故維持不動</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*aFkXUZJCAqiiMVFDgWfXvg.jpeg" /><figcaption>元素31保持不動</figcaption></figure><p>跟元素 31 一樣，元素 50 也維持不動</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*iW2u-8Dp2P0CGu4Rjy-2ow.jpeg" /><figcaption>元素50不動</figcaption></figure><p>元素 67 也不動</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*eAl48uKQRnRRYUfDU_KZaQ.jpeg" /><figcaption>元素67不動</figcaption></figure><p>此時整個陣列都變成綠色了，代表排序完成</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*Pe2Vh-CGNw6QmXoXNKk_lw.jpeg" /><figcaption>排序完成</figcaption></figure><p>程式碼：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/846eb9a18dabf6db74c4b8994e82966a/href">https://medium.com/media/846eb9a18dabf6db74c4b8994e82966a/href</a></iframe><p>時間複雜度：O(n²)</p><p>空間複雜度：O(1)</p><p>以上就是 Selection Sort 的介紹，有任何問題或心得歡迎留言告訴我，也可以接著往下看 <a href="https://debbiecamera0704.medium.com/%E5%BE%9E%E6%8E%92%E5%BA%8F%E5%AD%B8%E6%BC%94%E7%AE%97%E6%B3%95-2-bubble-sort-b3dc2ad2c73f">Bubble Sort 的講解</a>！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a9178ae71e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[讀後筆記：原子時間]]></title>
            <link>https://debbiecamera0704.medium.com/%E8%AE%80%E5%BE%8C%E7%AD%86%E8%A8%98-%E5%8E%9F%E5%AD%90%E6%99%82%E9%96%93-da572204fa7a?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/da572204fa7a</guid>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[原子時間]]></category>
            <category><![CDATA[讀書筆記]]></category>
            <category><![CDATA[time-management]]></category>
            <category><![CDATA[時間管理]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 07:58:44 GMT</pubDate>
            <atom:updated>2022-02-05T07:58:44.770Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dc6uY2JtqkOaKDfE" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>大多數人會把一週簡單分為「平日」和「週末」，也就是「工作日」和「非工作日」，這樣的想法會讓人把平日下班後的時間拿來等待週末，做一些無意義的事情，反而浪費了時間。事實上，你可以拿下班後的時間去做你想喜歡的事情。</p><p>當你認為時間綽綽有餘時，效率會降低，擁有很多自由時間反而需要更高的自制力。</p><p>此時幫自己設截止期限就是很好的推動力，像是平日晚上做事，固定上床時間。</p><p>💡 <strong>該如何填滿生活才不會後悔？</strong></p><p>為了生活，我們還是需要工作領薪水，但這不代表你不能同時追求其他事情，建立有效率、有時間意識感的晚間計畫，就是最好的方法。</p><p>比起問「幾點能下班？」，不如問自己「下班後做什麼？」</p><h3>如何找出下班能做的事？</h3><ol><li>選擇讓你有點小忙，但壓力較小的事</li></ol><p>因為這是工作後要做的事情，如果壓力大容易做不下去，因此選擇的事情不必太有建設性，只要能讓眼睛為之一亮即可。像是看個電影、煮菜。從中獲得的資訊，可能是未來創造利潤的資源。</p><p>2. 事先計算需要付出的時間和成本</p><p>針對有興趣的副業，先去做資料了解，推算自己是否能負荷時間費用，避免做白工。</p><p>3. 先試試水溫，不適合要有放棄的勇氣</p><blockquote><strong><em>有趣很好，有錢更好</em></strong></blockquote><p>藉由副業可以增加收入很棒，但能將下班後的自由時光過得有意義，即使賺不了錢、沒有人知道，也足以被視為非常有意義的時光。</p><blockquote><strong><em>培養成習慣最重要</em></strong></blockquote><p>下班後畫畫圖、健身，不管是為了興趣、健康或是小小業外收入，每天持續實踐才是最重要的，也因此我們需要設定目標。</p><h3>晚間計畫的起點</h3><p>💡 <strong>不要等待，時機永遠不會恰到好處</strong></p><blockquote><strong><em>設定目標的前置作業</em></strong></blockquote><ol><li>思考目標背後的意義</li></ol><p>做事時光靠樂趣跟毅力是不夠的，比起注重目標的達成，去思考目標達成背後的意義和價值更為重要</p><p>e.g. 雖然作者認為擔任youtuber每次剪輯上字幕的過程很冗長且機械化，但他還是能夠堅持下去，原因是因為他想到這部影片會帶給很多人努力的動力，因此他能持續下去。</p><p>2. 目標可以量化，意義賦予動能</p><p>很多人的目標會設定成今年要賺多少錢，當他們達成這個目標時，會維持短暫的快樂，隨後內心卻會感到空虛，這是因為他們只在意淺層的「目標」，沒有去思考背後帶來的意義。這樣很容易流於盲目追尋目標，無法達到內心實質的富足。</p><p>意義可以賦予動能，讓你克服過程中遇到的困難。</p><p>e.g. 作者在擔任獸醫時常常遇到機車主人，雖然覺得煩躁，但是只要想到這份工作能夠幫助到動物，他就有動力繼續做下去。</p><blockquote><strong><em>設定計畫四步驟</em></strong></blockquote><ol><li>大目標 (這輩子或這兩年非常想要達成的計畫)</li><li>尋找意義 (意義賦予動能)</li><li>釐清方向 (要達成目標一定要做的事情)</li><li>行動方案 (為了完成方向而進行的小計畫)</li></ol><p>e.g. 使用曼陀羅計畫表把今年的終極目標寫上去，旁邊再圍繞八個小目標</p><blockquote><strong><em>達成目標的七個階段</em></strong></blockquote><ol><li>設定目標</li><li>訂出期限</li><li>製作目標清單</li><li>擬定行動步驟</li><li>去除障礙</li><li>持續實踐 &amp; 修正</li><li>持續前進</li></ol><p>訂下行動方案以後，專注在完成事項就可以了，焦點不用放在目標，因為只要把該做的事情做好，離目標自然會越來越近。</p><h3>害怕猶豫時該怎麼辦?</h3><p>💡 <strong>煩惱短一點，行動快一點</strong></p><p>想像自己是排隊打針的人，當你看到前面的人打針後哀叫，此時你的恐懼感也會跟著變大。如果你是第一個打針的人，恐懼感反而還比較小。</p><p>恐懼感會隨著時間變大，但隨著行動而消除，因此當你覺得不安時，不如趕快開始行動才是解決之道，就算要擔心，也要給自己設定期限，如果因為擔心而遲遲不敢開始，反而會綁手綁腳，沒辦法做事。</p><blockquote><strong><em>克服擔心的方法：</em></strong></blockquote><ol><li>問自己如果失敗的話是否會連累他人? 如果不會就趕快行動</li><li>給自己設定擔心的期限最多三天</li><li>把煩惱的原因用文字紀錄下來，很多時候煩惱產生都是因為感性，但用文字紀錄反而能幫助你用理性去思考，梳理情緒</li></ol><h3>建立高效的晚間計畫</h3><p>💡 人類最困難的事，就是了解自己並改變自己 (Alfred Adler)</p><blockquote><strong><em>為甚麼總是覺得沒時間?</em></strong></blockquote><p>1. 無意識的放任時間流逝</p><p>首先要了解時間的特性，當你越在意它，它流動的速度就越慢。比方有三種情況人們覺得過的最久：等泡麵的時候、等退伍的時候和做平板式支撐的時候，相對來說，和朋友聊天或是逛街的時光總是特別快，因為你不會特別關注時間。</p><p>如果能養成習慣意識一天24小時，就能比別人多出很多時間。</p><p>2. 常常做一些無關緊要的小事</p><p>比方上網看個影片傳個訊息，看起來很瑣碎的小時間，累積起來非常驚人。</p><p>要克服這種莫名其妙浪費時間的方式，就是每個半小時或一小時就檢視自己做了什麼，用回顧的方式記錄自己如何使用時間。</p><h4><strong>一天中你到底做了什麼? 利用功能性筆記進行事後回顧</strong></h4><p><strong>每小時回顧，找出高專注時段</strong></p><p>紀錄一個月之後，大致能歸納出自己專注的時段有哪些，比方講者他白天體力最好，做勞力的事情效果很好，晚上則用來做創造力相關的事情。因此他白天運動，晚上則剪片或寫文章。照這樣的模式找出自己的節奏，就能有效運用時間。</p><blockquote><strong><em>制定晚間計畫表步驟</em></strong></blockquote><p>1. 盤點空白時間</p><p>2. 把每天能夠運用的空閒時間記錄下來，這邊有一點要特別注意，必須固定抽出的時間也要記錄並且從空閒時間扣除，比方帶狗狗散步或陪伴家人等。之所以要這樣做是為了避免在全力以赴做想做的事情時，錯過最基本且重要的小事。</p><p>3. 了解時間成本和必須投入的專注度</p><p>4. 評估每件事情要花費的時間。如果是第一次嘗試的東西，建議比預估多排1.5倍的時間，並持續修正。</p><p>5. 製作晚間時刻表</p><p>6. 把想做的事情依序填到計畫表中並開始執行。記住，時間表是為了幫助你管理時間而不是來囚禁你的，因此不用因為臨時有事無法執行計畫而感到有壓力，而是根據現況進行彈性調整。</p><p>7. 不管過程遇到什麼困難，只要持續維持這個習慣，就能漸漸掌握時間。</p><p>其他方法：番茄鐘</p><blockquote><strong><em>避免浪費時間的技巧和心態</em></strong></blockquote><p>1. 問題不再追劇，在於你有沒有充電</p><p>很多人會以為時間管理很好的人一定是不停的工作&amp;自我充實，也因此對時間管理的計畫感到壓力。</p><p>作者想提倡的時間倍增術，並<strong>不是將所有時間花在具有產能的事情上，工作和休息達到平衡才是作者希望大家達到的目標。</strong></p><p>至於休息跟浪費時間該如何區分? 一個很簡單的原則：只要讓你有充電的感覺，那就是好的休息，比方同樣是放空，有人是在體力耗盡後休息，有人卻是在打發時間。</p><p>💡 管理時間最大的敵人並不是休息，而是無法好好休息，也無法好好工作，得過且過任憑時間流逝</p><blockquote><strong><em>意志力不是最關鍵的重點</em></strong></blockquote><p>培養重複性的節奏感很重要，在同樣的時間做同樣的事情，才能順勢形成習慣。因此可以把所有想養成習慣的事納入日常生活。</p><p>e.g. 每晚睡前半小時閱讀、睡前半小時做瑜珈，即使沒有意志力也可以完成。</p><blockquote><strong><em>訂晚間計畫的三大階段</em></strong></blockquote><p>一、建立小事 (簡單、好做)</p><p>二、每天同樣時間重複執行</p><p>三、堅守設定的時間</p><blockquote><strong><em>培養自己，不是一種比賽</em></strong></blockquote><p>有些事情必須燃燒精力去做，有些事情則需要慢慢享受，穩穩做下去。知道這個道理以後，會了解之所以有些事會中途放棄，就是因為一開始衝太快了，到後來無法駕馭。</p><blockquote><strong><em>思考像大人，行動像孩子</em></strong></blockquote><p>無論如何都要有趣，讓成果顯而易見</p><p>e.g. 利用 Habit Tracker 紀錄習慣</p><p>形象塑造，讓自己變成理想中的樣子</p><blockquote><strong><em>改變自我認知</em></strong></blockquote><p>人們對身邊的人多少有一點刻板印象，比方「那個人太善良了，一定老是被欺負」，我們對自己的認知也是如此，很多時候這些認知反而會限制我們的行為，彷彿像一個框架，覺得自己只能在框架下行動。</p><p>舉例，覺得自己沒有運動細胞的人就不太會去運動，並永遠停留在「我沒有運動細胞」的自我印象。</p><p>當一個人對自己的認知過於負面，周遭的人也容易被影響，比方認定你就是不會運動的人，未來有這樣的活動就不會找你。</p><blockquote><strong><em>你問我是誰？我是很厲害的人</em></strong></blockquote><p>要以正面的形象來定義自己，最有效的時機是「付出一點努力取得等值的小成功」之後，這是略帶吹噓的方式激勵自己最合理也最自在。</p><p>現在有些理論會告訴你，想成為XX人，要從潛意識告訴自己就是XX人，比方想變有錢人，就告訴自己已經是有錢人了，但作者認為「自我暗示」必須和「行動」相結合才有效果。</p><p>把自己當作小孩子看待，先做出小小成就 → 浮誇讚美自己 → 進而在腦中重塑自己的形象 → 當你的自我認知變正面了，未來下意識能做出符合自己的形象的決定。</p><blockquote><strong><em>想耍廢的時候怎麼辦：</em></strong></blockquote><ol><li>我只要有做一點點就好</li></ol><p>有時可能會遇到下列情況，朋友有約、工作累不想繼續、一下班很想躺在床上，這時候該怎麼辦？直接延到明天，還是告訴自己做一點點就好，答案是後者，從過往的經驗可以知道，當你今天一旦放棄，明天絕對不會做事，而且會加倍不想做，因為人有惰性，當下讓自己放棄的藉口，明天會變得更加強大。</p><p>2. 修正是為了走更遠</p><p>假設你的目標原本是每天跑 7 km，但你常常因為沒達標而想要放棄，那不如就把目標變成是每天有跑就好，不限定距離，當壓力變小時，腦袋自然會浮現想比昨天多跑一點的念頭。相反地，如果今天不想跑，就隨興的跑五分鐘也可以，只要能持續維持，有彈性的調整是沒問題的。</p><blockquote><strong><em>低潮期或無力感來襲時：</em></strong></blockquote><ol><li>不是低潮，而是離峰期</li></ol><p>之所以把低潮稱為離峰期，是因為語言帶來的意義與影響力很大。低潮會帶來無力以及負面的情緒，相對來說，既然有離峰，那就代表有尖峰的存在，也可以告訴自己只是暫時性地碰到熱度較低的時期，活力充沛的日子很快會再到來。</p><p>2. 減少事情的份量</p><p>重點在於有彈性、有節奏的去駕馭低潮。大浪來襲時，不是捨命應戰，而是放掉力氣，適當融入，狀態不好的時候少做一點，告訴自己重點是不能放棄。</p><p>3. 不要恐慌，充分休息</p><p>當低潮來襲，想減少事情的份量並休息時，就放輕鬆好好休息吧，不用覺得恐慌，如同前面提到的，能達到充電效果的休息就是好的休息，而不是空虛的度過時間。</p><p>4. 得失心不要太重，目標只是方向鍵</p><p>常聽人說，想要實現夢想就要努力，但是努力不一定能實現夢想，當今天你已經盡力卻依然無法達成目標時，不用太過沮喪，盡人事聽天命，好好吸取這次的經驗，為下一次繼續努力，不要產生這次無法成功就想放棄一切的想法。目標只是指引你努力的方向，不是為了折磨現在的生活，最理想的狀態是，你的願望能變成可量化的目標，同時也能享受過程中把每個小行動完成的成就感。</p><blockquote><strong><em>反省演算法：避免過度自責和合理化</em></strong></blockquote><ol><li>為甚麼沒有按照計畫執行？</li></ol><p>沒有辦法完成計畫的原因有很多種，試著去找出實際的原因，而不是單純覺得自己就是意志力不夠，比方影響意志力的原因可能是身體狀況不佳，天氣太熱，上班壓力大等，如果是身體不好，那就想辦法去改善身體狀況，比如多去運動等。</p><p>2. 問題是否在於我無法駕馭？</p><p>分析完為什麼沒有按照計畫進行的原因後，如果發現這個問題是我就算努力也無法改變，那就不用再想了，不需要為此過度糾結。</p><p>3. 是否已盡了全力？</p><p>筆者從 Marshall Goldsmith 的書 Trigger 學到很好的自省標準。訂出每天想實踐的幾種主題後，設計幾個問題自問自答以取得反饋，而每個問題的最後都必須以「我是否已經盡了全力？」作為結束</p><p>4. 不要讓完美主義綁住你</p><p>不求做得好，但求做得久。我們要做的事情不像是開飛機、醫治生命，大部分都是可以容許出錯的，因此不要太糾結完美，只要記得每一次都可以慢慢修正，不求做得好，先求做得久，積少成多，累積屬於自己的能量。</p><blockquote><strong><em>意志力不夠時：</em></strong></blockquote><p>很多人覺得一定是意志力很強才會長期做一件事情，但問題其實不在行動力，而是行動力。實踐不需要強烈的意志，就只是做昨天做過的事和現在該做的事情而已。</p><pre><strong>與意志力相反，行動力的養成，盡可能越自然越好。</strong></pre><p>1. 不要對所有事情卯足全力</p><p>從心靈層面來看，意志力和自律是綁在一起的，太常使用意志容易帶來壓力，反而會產生抗拒心理。因此如果不是跟人生有重大影響的事情，就帶著「沒什麼大不了」的心情去做吧。</p><p>在行動前或是行動期間都不要想太多，甚至是刻意想少一點，因為通常在行動前的想法常常會是負面的，像是我會不會做不好等，都還沒行動興致已經少一半了。</p><p>不被情緒綁架的方法就是即時察覺，在自我合理化以前即時行動。</p><p>💡 無論什麼事，感覺不想做之前必須趕快去做。</p><p>不要想「我果然沒有自制力！」，請改成「嗯，我又開始亂想了，不要想了，走吧！」</p><h4>想放棄時，問自己三個問題</h4><p>💡 放棄不是失敗，而是一種決定</p><p>多方嘗試後，剔除不適合的事，也是一種方法，特別是對「挑戰新手」來說，因為不太了解自己的喜好，嘗試不同的挑戰都是有意義的。</p><p>反覆試錯、找路，是每個人必經的過程。</p><p>1. 是否覺得不再開心</p><p>如果像是起身去做的前一刻覺得懶，試著忍耐一下，堅持看看。單純覺得麻煩的事，養成習慣之後就沒那麼難了。</p><p>2. 長期來看，是否沒有正面成果</p><p>3. 是否只對別人有好處，自己呢？</p><p>如果做這件事沒辦法獲得任何樂趣、成就感，那果斷放棄也無妨。</p><blockquote><strong><em>不要當喪屍，管理體力的訣竅</em></strong></blockquote><ol><li>運動</li></ol><p>為了避免自己沒時間、太忙了的藉口，作者利用上班前的時間運動，一開始真的很累，很想睡，但撐過一兩個月後身體就習慣了。</p><p>2. 兩個月定律</p><p>人是習慣的動物，撐過兩個月以後，就會慢慢維持住那個習慣的體力</p><p>3. 吃得好，就是對自己好</p><p>4. 陽光比 3C 重要</p><p>5. 冥想</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da572204fa7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[資料庫設計要注意什麼？]]></title>
            <link>https://debbiecamera0704.medium.com/%E8%B3%87%E6%96%99%E5%BA%AB%E8%A8%AD%E8%A8%88%E8%A6%81%E6%B3%A8%E6%84%8F%E4%BB%80%E9%BA%BC-8c0e4ff324fe?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c0e4ff324fe</guid>
            <category><![CDATA[normalization]]></category>
            <category><![CDATA[entity-relationship-model]]></category>
            <category><![CDATA[database-design]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Mon, 04 Oct 2021 14:34:00 GMT</pubDate>
            <atom:updated>2021-10-04T14:34:00.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Ek9xnebnO6vlkyR" /><figcaption>Photo by <a href="https://unsplash.com/@kaleidico?utm_source=medium&amp;utm_medium=referral">Kaleidico</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>文章大綱</h3><ul><li>資料庫設計是什麼</li><li>常見的資料庫設計方法</li><li>設計資料庫時要注意的細節</li><li>常見的資料庫設計方法</li></ul><h3>何謂資料庫設計？(Database Design)</h3><p>它是一系列可以幫助你建立並且維護商業資訊的方法，讓你建造出一個有邏輯且好維護的資料庫系統。</p><h3>好的資料庫設計旨在達成以下原則：</h3><ol><li>避免儲存多餘的資料</li></ol><p>多餘或是不會用到的資訊就不要放到資料庫中，避免浪費空間或是增加資料出錯的機會。</p><p>2. 保持資料正確性</p><h3>資料庫設計要注意的細節：</h3><p>為了達成資料查詢的效能，資料庫的設計與優化非常重要，有些問題在資料庫規模小的時候可能沒有太大感受，不過一旦規模變大，效能差別會非常明顯，影響使用者體驗。下面列出常見的四個細節</p><ol><li>能夠用數字型別的欄位就不要用字串型別</li></ol><p>資料庫在處理字串比對的速度會比數字的判別來得慢，且字串所需要的儲存空間會大於數字，因此如果能使用數字就盡量使用數字型別</p><p>2. 避免將多種資訊儲存在同一個欄位</p><p>比方以地址來說就包含多種資訊：</p><ul><li>街道名稱</li><li>城市</li><li>國家</li><li>巷弄</li></ul><p>假設今天要進行使用者分析，想找尋位於「台中市」的所有使用者時，你必須要用LIKE或是部分字串比對的方式去查找，而這種尋找方式會耗費大量效能。</p><p>相對來說，如果把地址的資訊分散儲存，查詢上會更容易且未來在更新也更方便。</p><p>3. 索引(index)使用方式錯誤</p><p>索引就像是在一本書裡面放分類標籤一樣，可以讓你在查找時更加快速。在資料庫中，索引是一種資料結構，正確使用會加快查資料的速度</p><p><strong>完全不用索引：</strong>資料量小的時候可能不會察覺速度差異，但隨著資料慢慢增長，會發現查找的速度也會跟著變慢，就像是一本字典裡沒有目錄一樣，查找需要每一頁都看過，耗費大量時間。</p><p><strong>使用過多索引：</strong>使用索引可以有效加快讀取速度，但是反而會拖慢增刪改資料的速度，因為在修改資料時，索引也需要一併更新。</p><p>4. 命名方式不一致</p><p>資料庫設計一定會碰到命名，像是Table, Column等，不論採取什麼命名原則，很重要的一點就是要「一致」，比方大小寫、單複數、分隔符號、縮寫等。使用通用且一致的方式命名才能讓團隊容易理解使用，未來在維護上也更容易。</p><h3>常見的資料庫設計方法：</h3><ol><li>正規化 (Normalization)</li></ol><p>正規化也被稱為標準化，主要的目的是為了要避免儲存重複或是不必要的資料，同時增進資料庫的效能，藉由正規化，可以達成資料的一致性。</p><p>正規化主要包含以下三個階段：</p><p>1NF (First Normal Form): 去除關聯表中的重複值或複合屬性</p><ul><li>一個欄位只能有單一個值</li><li>每個欄位都是唯一，不重複</li></ul><p>NG 範例：成績這個欄位有一個以上的值</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*ogUI4GrwawtEY1QdQ_3lnQ.jpeg" /><figcaption>1NF</figcaption></figure><p>正確應該將每個值分開紀錄：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*GMRUAVsNvR24eB8bZsTn8Q.jpeg" /></figure><p>2NF (Second Normal Form): 讓每個關聯資料表只儲存同類的資料</p><ul><li>根據主鍵，將資料表拆成多張資料表</li></ul><p>NG範例：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*QrKILAvPLKJ3W5XOLUN-pA.jpeg" /><figcaption>2NF</figcaption></figure><p>什麼樣的資料能稱為同類型的資料呢？最簡單的方式可以從主鍵作為區別，比方上述的表格中學號和課程編號的數值都是唯一，可以做為識別資料表的標示，因此可以做為主鍵，將上述資料表再分為學生和成績兩張表。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*eSQPdx8v7GRqqIRYHvRSIA.jpeg" /></figure><p>3NF (Third Normal Form):</p><p>如果某個欄位可以用其他欄位推斷出來，就需要再開一個表來紀錄</p><ul><li>移除遞迴相依的非主鍵屬性，讓所有非主鍵屬性都只相依於該表的主鍵，而且互不相依</li></ul><p>從上述2NF中成績的資料表中可以發現，只要知道課程編號，就能夠推算出課程名稱是什麼，因此我們可以再分出一個表</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*ozum9J7ier-y4IwPK3Ulgw.jpeg" /><figcaption>3NF</figcaption></figure><p>表格分好以後就完成第三階段正規化，現在我們總共有三張表，學生、成績以及課程。</p><p>2. 實體關聯圖 (Entity-Relationship Diagram)</p><p>它可以被視為資料設計的草圖，把資料所需的屬性與資料之間的關聯性畫出來，以圖像的方式呈現抽象的資料設計，不僅在繪製過程能夠幫助仔細規劃，也更讓整個團隊知道如何從資料庫獲取資料，或是即時發現設計上的問題。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5q5wk6APUdptH0mhtTFNA.jpeg" /><figcaption>ERD</figcaption></figure><p>實體關聯圖主要包括三個元素：</p><ul><li>實體：它是指系統中可以被定義的事物或概念，比方評論、使用者等</li><li>屬性：我們希望從實體中得到的資訊，比方以使用者的資料表來說，我們希望得到名字、性別跟電話</li><li>關聯：描述不同實體之間的關聯性，比方一對多、多對一等。</li></ul><p>線上好用的繪圖工具：</p><p><a href="https://online.visual-paradigm.com/tw/diagrams/features/erd-tool/">在線ERD工具</a></p><p>以上就是這次資料庫設計的分享內容，如果文章有任何心得反饋都歡迎留言告訴我！</p><p>參考資料</p><ul><li><a href="https://www.toptal.com/database/database-design-bad-practices">Bad Practices in Database Design: Are You Making These Mistakes?</a></li><li><a href="https://www.databasestar.com/database-design-mistakes/">24 Database Design Mistakes and How to Avoid Them</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c0e4ff324fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[如何用 Mocha.js 寫測試?]]></title>
            <link>https://debbiecamera0704.medium.com/%E5%A6%82%E4%BD%95%E7%94%A8-mocha-js-%E5%AF%AB%E6%B8%AC%E8%A9%A6-6fce7c44990d?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fce7c44990d</guid>
            <category><![CDATA[test]]></category>
            <category><![CDATA[mocha-js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Fri, 27 Aug 2021 05:41:03 GMT</pubDate>
            <atom:updated>2021-08-27T05:41:03.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*de7HTfmNX9yKiHIh" /><figcaption>Photo by <a href="https://unsplash.com/@framemily?utm_source=medium&amp;utm_medium=referral">Frame Harirak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Mocha.js 是什麼？</h3><p><a href="https://mochajs.org/">Mocha</a> 是一款專門在 Node.js 使用的 JavaScript 測試框架，用來撰寫容易閱讀的測試碼，另外再搭配斷言庫( Assertion Library) 驗證測試結果，像是 Chai.js 。</p><p>接下來就實際用Mocha撰寫測試看看吧！</p><h3>專案建立</h3><p>首先建立一個新的資料夾並建立主程式檔</p><pre>$ mkdir mocha_demo<br>$ cd mocha_demo</pre><p>使用npm init幫我們建立專案，這個指令會問你一些專案相關的問題，像是名稱、敘述等，如果想之後再填可以使用npm init -y 先建立 package.json 檔，這裡面會記錄專案資訊</p><pre>$ npm init -y</pre><p>建立 converter.js 放主要程式。創建一個測試資料夾，裡面放測試的所有檔案</p><pre>$ touch converter.js<br>$ mkdir tests<br>$ touch tests/converter.spec.js</pre><p>安裝測試框架 mocha 和斷言庫 chai</p><pre>$ npm i --save-dev mocha chai</pre><h3>撰寫測試程式碼</h3><p>採用 TDD 開發模式時，會先寫好測試再來撰寫主要程式碼。接下來的範例會以攝氏和華氏溫度的轉換作為這次要撰寫的主程式。</p><p>首先打開剛剛建立的 converter.spec.js :</p><pre>// tests/converter.spec.js</pre><pre>const { expect } = require(&#39;chai&#39;)<br>const { convertToCelcius } = require(&#39;../converter&#39;)<br>const { convertToFahrenheit } = require(&#39;../converter&#39;)</pre><pre>describe(&#39;Temperature Converter&#39;, function () {<br>  describe(&#39;Celcius to Fahrenheit conversion&#39;, function () {<br>    it(&#39;# is not a number&#39;, function () {<br>      expect(() =&gt; { convertToFahrenheit(&#39;a&#39;) }).to.throw(&#39;The parameter is not a number&#39;)<br>    })</pre><pre>    it(&#39;# converts to Fahrenheit&#39;, function () {<br>      expect(convertToFahrenheit(34)).to.equal(93.2)<br>      expect(convertToFahrenheit(0)).to.equal(32)<br>      expect(convertToFahrenheit(100)).to.equal(212)<br>      expect(convertToFahrenheit(-18)).to.equal(-0.4)<br>    })<br>  })</pre><pre>  describe(&#39;Fahrenheit to Celcius conversion&#39;, function () {<br>    it(&#39;# is not a number&#39;, function () {<br>      expect(() =&gt; { convertToFahrenheit(&#39;b&#39;) }).to.throw(&#39;The parameter is not a number&#39;)<br>    })</pre><pre>    it(&#39;# converts to Celcius&#39;, function () {<br>      expect(convertToCelcius(32)).to.equal(0)<br>      expect(convertToCelcius(48)).to.equal(8.9)<br>      expect(convertToCelcius(212)).to.equal(100)<br>      expect(convertToCelcius(-10)).to.equal(-23.3)<br>    })<br>  })<br>})</pre><p>describe 用來描述測試的情境或形成特定區塊</p><p>it 表示一個單獨的測試，做為測試的最小單位，撰寫測試案例的名稱或說明，內部會放程式的預期結果</p><p>expect Chai 斷言庫提供的判斷工具，它提供的語法和口語非常類似，可以一眼看出預期結果是什麼，比方：</p><ul><li>expect(convertToCelcius(32)).to.equal(0) 預期結果是 0</li><li>expect([{a: 1}]).to.deep.include({a: 1}) 預期回傳的陣列要包含{a:1}</li><li>expect(badFn).to.throw(err); 預期結果會報錯</li></ul><p>除了這些語法外，還有很多其他判斷條件，查看<a href="https://www.chaijs.com/api/bdd/">這裡</a>有更多用法</p><h3>撰寫主程式</h3><pre>// converter.js</pre><pre>const converter = {<br>  convertToFahrenheit: (degree) =&gt; {<br>    if (isNaN(degree)) throw new Error(&#39;The parameter is not a number&#39;)<br>    return Math.round((degree * (9 / 5) + 32) * 10) / 10 //四捨五入<br>  },</pre><pre>  convertToCelcius: (degree) =&gt; {<br>    if (isNaN(degree)) throw new Error(&#39;The parameter is not a number&#39;)<br>    return Math.round(((degree - 32) * 5 / 9) * 10) / 10<br>  }<br>}</pre><pre>module.exports = converter</pre><h3>執行測試</h3><p>在執行測試檔以前，要先在package.json進行設定，告訴mocha測試檔的位置等。</p><p>下面的設定表示在執行npm test的指令時，mocha 會去 tests資料夾執行內部所有測試檔案，如果執行 5 秒後都沒回應則會判斷測試不通過，等所有檔案執行完後會自動結束</p><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;mocha tests --exit --recursive --timeout 5000&quot;<br>}</pre><p>接著在終端機執行 npm test就可以看到測試的結果了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*yE6i36-Y7jJSxEwdWNxG7Q.jpeg" /><figcaption>test result</figcaption></figure><p>以上就是本次 mocha.js 的簡單示範，如果有任何意見反饋都歡迎留言告訴我！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fce7c44990d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[除錯] 遇到 ECONNRESET 如何處理？]]></title>
            <link>https://debbiecamera0704.medium.com/%E9%99%A4%E9%8C%AF-%E9%81%87%E5%88%B0-econnreset-%E5%A6%82%E4%BD%95%E8%99%95%E7%90%86-b76f04137303?source=rss-1d35a82d3fba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b76f04137303</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[econnreset]]></category>
            <category><![CDATA[bluebird]]></category>
            <dc:creator><![CDATA[De_]]></dc:creator>
            <pubDate>Fri, 20 Aug 2021 10:52:04 GMT</pubDate>
            <atom:updated>2021-08-20T10:53:00.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C2rMpLsRhj7gwPd0" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>在實作爬蟲專案時，有時候需要連續發幾個HTTP request到server端請求資料(比方搜尋頁數較多時)，我直覺想到的是這樣的做法：</p><p>同時發送所有request, 等全部的request完成再進行下個步驟</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b7ce50c44409f8007a91c182008e402/href">https://medium.com/media/0b7ce50c44409f8007a91c182008e402/href</a></iframe><p>一次發送 5 個請求可能沒什麼問題，不過當請求數量變大，你很可能會遇到這個報錯 Error: read ECONNRESET 原因是因為Node沒有辦法一次處理太多請求。</p><h4>解決辦法</h4><p>使用Bluebird Promise.map 設定 concurrency：原先使用的Promise.all並沒有設定處理事件的上限，也就是說假設放了100個item在Promise.all裡面，這100個item會同時啟動。這時候可以使用Bluebird幫我們達成任務。</p><p>Bluebird是一個第三方的promise庫，它相容原本的promise物件，並提供額外的擴充功能。</p><p>我們要使用的就是其中的 promise.map，官方文件的操作方法如下：</p><pre>Promise.map(<br>    Iterable&lt;any&gt;|Promise&lt;Iterable&lt;any&gt;&gt; input,<br>    function(any item, int index, int length) mapper,<br>    [Object {concurrency: int=Infinity} options]<br>) -&gt; Promise</pre><p>第一個參數放可迭代的對象，第二個參數放callback function，第三個參數放concurrency，也就是一次要運行的promise數量</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aafd19cf62b46a0f6ec494760cdf962/href">https://medium.com/media/6aafd19cf62b46a0f6ec494760cdf962/href</a></iframe><p>這樣的寫法就可以控制一次發送request的數量，避免連線中斷或是造成他人伺服器的負荷。</p><h4>其它作法</h4><p>使用 <a href="https://github.com/timdp/es6-promise-pool">es6-promise-pool</a>或是 <a href="https://github.com/featurist/promise-limit">promise-limit</a> 也可以達到類似的效果</p><h4>參考文章</h4><ul><li><a href="https://www.gregjs.com/javascript/2015/how-to-scrape-the-web-gently-with-node-js/">How to scrape the web gently with Node.js</a></li><li><a href="https://dev.to/karataev/handling-a-lot-of-requests-in-javascript-with-promises-1kbb">Handling a lot of requests in JavaScript with promises</a></li></ul><p>以上就是本次除錯的紀錄，如果文章有任何錯誤或反饋歡迎留言告訴我！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b76f04137303" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>