<?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 SF on Medium]]></title>
        <description><![CDATA[Stories by SF on Medium]]></description>
        <link>https://medium.com/@dentured?source=rss-25cad916b48e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Qde7yDJZ1lMp3jM6PsTQmw.jpeg</url>
            <title>Stories by SF on Medium</title>
            <link>https://medium.com/@dentured?source=rss-25cad916b48e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:20:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dentured/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 2020 Final Project: A Summarising Tool and Concluding Thoughts]]></title>
            <link>https://medium.com/@dentured/cs50-2020-final-project-a-summarising-tool-and-concluding-thoughts-df2b566f035b?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/df2b566f035b</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[summary]]></category>
            <category><![CDATA[cs50]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 13:48:23 GMT</pubDate>
            <atom:updated>2024-04-11T13:48:23.393Z</atom:updated>
            <content:encoded><![CDATA[<p>Admittedly, this is very much delayed. I chanced upon my final submission for the module while clearing my drive and figured it’s time to share it, with some minor edits.</p><p>The final project provided much freedom to explore the many platform tools available, and coincided with a time during my semester where I was struggling to get through my readings. After some thought, a tool that would let me summarise papers/longforms seemed like a bright idea — of course, taking into account my severe limitations as a novice coder, I settled upon a more basic tool that would just simplify web articles by acting as a Chrome extension. The project predominantly borrowed from p-sets Readability, Speller and Finance.</p><p>So, to build a Chrome extension that summarises a webpage article using JavaScript, HTML, and CSS, you would need to follow these general steps:</p><p>(1) Set up the project structure:</p><ol><li>Create a new folder for your extension.</li><li>Inside the folder, create separate files for the manifest, HTML, CSS, and JavaScript code.</li></ol><p>(2) Create the manifest.json file:</p><ol><li>This file provides information about your extension, such as its name, version, and permissions.</li><li>Add the required fields and permissions for your extension, including the permissions to access the active tab and execute JavaScript code.</li></ol><p>(3) Design the user interface (UI):</p><ol><li>Create an HTML file that will serve as the UI for your extension popup.</li><li>Design the layout using HTML and CSS to create a simple interface where the summarized article will be displayed.</li></ol><p>(4) Write the JavaScript code:</p><ol><li>Use JavaScript to interact with the webpage and extract the article’s content.</li><li>You can use DOM manipulation techniques to retrieve the relevant elements, such as the article text, headings, or paragraphs.</li><li>Implement a summarization algorithm to generate a summary of the article content.</li><li>Update the UI with the generated summary.</li></ol><p>(5) Test the extension:</p><ol><li>Load the extension in Chrome by going to chrome://extensions.</li><li>Enable the “Developer mode” if not already enabled.</li><li>Click on “Load unpacked” and select the folder containing your extension files.</li><li>Test the extension by clicking on its icon, which should open the popup UI and display the summarized article.</li></ol><p>(1) Set up the project structure: Create a new folder for your extension called ‘Scrub’ — my name for the project lmao. Inside it, create the following:</p><ul><li>manifest.json: This file provides information about your extension and its permissions.</li><li>popup.html: This file will serve as the UI for your extension popup.</li><li>popup.css: This file will contain the CSS styles for the popup.</li><li>popup.js: This file will contain the JavaScript code for the popup functionality.</li></ul><p>(2) Create the manifest.json file: The manifest.json file is a crucial part of any Chrome extension. It defines the extension’s properties, permissions, and more, as follows:</p><pre>{<br>  &quot;manifest_version&quot;: 2,<br>  &quot;name&quot;: &quot;Scrub&quot;,<br>  &quot;version&quot;: &quot;1.0&quot;,<br>  &quot;description&quot;: &quot;Summarises webpage articles&quot;,<br>  &quot;permissions&quot;: [&quot;activeTab&quot;],<br>  &quot;browser_action&quot;: {<br>    &quot;default_popup&quot;: &quot;popup.html&quot;,<br>    &quot;default_icon&quot;: &quot;icon.png&quot;<br>  },<br>  &quot;icons&quot;: {<br>    &quot;16&quot;: &quot;icon.png&quot;,<br>    &quot;48&quot;: &quot;icon.png&quot;,<br>    &quot;128&quot;: &quot;icon.png&quot;<br>  }<br>}</pre><p>The ‘activeTab’ permission allows the extension to access the current tab it’s opened on. We link this .js file to “popup.html”, which we will examine below.</p><p>(3) Design the user interface</p><p>Open the popup.html file and add the following code for a basic user interface structure:</p><pre>&lt;!DOCTYPE HTML&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Scrub&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;style.css&quot;&gt;<br>    &lt;script src=&quot;jquery.min.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;popup.js&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body id=&quot;popup&quot;&gt;<br>    &lt;h1 id=&quot;title&quot;&gt;&lt;/h1&gt;<br>    &lt;p id=&quot;text&quot;&gt;&lt;/p&gt;<br>    &lt;button id=&quot;settings&quot; onclick=&quot;openSettings()&quot;&gt;Settings&lt;/button&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Here, we have linked the code to “style.css”.</p><p><em>CSS</em> is used to style a HTML document with different elements.</p><ol><li><strong><em>style.css</em></strong></li></ol><p>Here, the code targets the appearance of the tool — how the popup will look like when implemented on a chrome webpage, and is pretty easy to interpret. I toyed with this quite a bit to get the dimensions (width/margin), fonts (title) and location (top centre) of it.</p><pre>body#popup {<br>  width: 400px;<br>  margin:0;<br>} <br><br>h1 {<br>  font-size: 20px;<br>}<br><br>/* POPUP */<br><br>#title {<br>  max-width: 100%;<br>  margin: 0;<br>  display: block;<br>  background-color: #ff8c69;<br>  color: #fff8e7;<br>  padding-top: 10px;<br>  padding-left: 10px;<br>  padding-bottom: 10px;<br>  padding-right: 10px;<br>}<br><br>p {<br>  max-height: 400px;<br>  overflow: scroll;<br>  padding-left: 5px;<br>  padding-right: 5px;<br>}<br><br>#text h2 {<br>  padding-left: 5px;<br>}<br><br>#settings {<br>  float: right;<br>  margin-right: 5px;<br>  margin-bottom: 5px;<br>}<br><br>/* SETTINGS */<br><br>body#settings {<br>  width: 100%;<br>  margin:0;<br>}<br><br>div#form {<br>  margin-left: 30px;<br>  margin-top: 40px;<br>}<br><br>.range {<br>  position: relative;<br>  left: 50px;<br>}<br>.option[disabled=disabled] {<br>  opacity: 0.5;<br>  pointer-events: none;<br>}<br>.option:not([disabled=disabled]) {<br>  opacity: 1;<br>  pointer-events: auto;<br>}<br>.range input {<br>  position: relative;<br>  top: 3px;<br>  width: 400px;<br>}</pre><p><strong>(4) Implementing the Javascript code</strong></p><p>Now, let’s implement the JavaScript logic to summarise the article and update the user interface.</p><p>Open the popup.js file and add the following code:</p><pre>chrome.storage.local.get(function (val) {<br> if (val[&quot;scrub-title&quot;] == undefined || val[&quot;scrub-summarized&quot;] == undefined) {<br>    document.getElementById(&quot;title&quot;).textContent = &quot;scrub&quot;;<br>    document.getElementById(&quot;text&quot;).innerHTML = &quot;To summarise, right-click and select \&quot;Click to summarise article...\&quot;&quot;<br>   } else {<br>     document.getElementById(&quot;title&quot;).textContent = val[&quot;scrub-title&quot;];<br>     document.getElementById(&quot;text&quot;).innerHTML = val[&quot;scrub-summarized&quot;];<br> }<br>});<br><br>chrome.storage.onChanged.addListener(function(changes, areaName) {<br>  chrome.storage.local.get(function (val) {<br><br>   if (val[&quot;scrub-title&quot;] == undefined || val[&quot;scrub-summarized&quot;] == undefined) {<br>    document.getElementById(&quot;title&quot;).textContent = &quot;scrub&quot;;<br>    document.getElementById(&quot;text&quot;).innerHTML = &quot;To summarise, right-click and select \&quot;Click to summarise article...\&quot;&quot;<br>   } else {<br>     document.getElementById(&quot;title&quot;).textContent = val[&quot;scrub-title&quot;];<br>     document.getElementById(&quot;text&quot;).innerHTML = val[&quot;scrub-summarized&quot;];<br> }<br>    chrome.browserAction.setBadgeText({text: &quot;I&quot;});<br>  });<br>});<br><br>chrome.browserAction.setBadgeText({text: &quot;&quot;});<br><br>document.addEventListener(&#39;DOMContentLoaded&#39;, function() {<br><br> document.getElementById(&quot;settings&quot;).addEventListener(&#39;click&#39;, function() {<br><br>  chrome.tabs.create({url:chrome.extension.getURL(&quot;settings.html&quot;)});<br> });<br><br>});</pre><p><strong><em>select.js</em></strong></p><p>The mechanism behind the summarisation, and my favourite part. This essentially forms the meat of the tool. This kind of tool, one that does predictive and anticipatory work is very much in the realm of AI and ML, but applying simple algorithms to remove ‘redundancy’ seems fit for CS50.</p><p>Inside the javascript file, I started off removing typical details you would find in a text<em>.</em></p><pre>var blacklist = [<br>  &quot;the&quot;, &quot;a&quot;, &quot;and&quot;, &quot;of&quot;, &quot;is&quot;, &quot;or&quot;, &quot;also&quot;, &quot;it&quot;, &quot;non&quot;, &quot;an&quot;<br>];<br><br>var period_blacklist = [&quot;Ms\\.&quot;, &quot;Mrs\\.&quot;, &quot;Mr\\.&quot;, &quot;e\\.g\\.&quot;, &quot;i\\.e\\.&quot;,<br>       &quot;\\.\\.&quot;, &quot;p\\.m\\.&quot;, &quot;a\\.\\m.&quot;, &quot;P\\.M\\.&quot;, &quot;A\\.M\\.&quot;];<br><br>var tag_blacklist = [&quot;LI&quot;, &quot;UL&quot;, &quot;OL&quot;, &quot;TABLE&quot;, <br>     &quot;TBODY&quot;, &quot;THEAD&quot;, &quot;TD&quot;, &quot;TR&quot;];<br><br>//using blacklist<br><br><br>var selection = window.getSelection();<br>var parent = selection[&quot;focusNode&quot;][&quot;parentElement&quot;][&quot;parentElement&quot;];<br><br>while (parent.tagName != &quot;DIV&quot;) {<br> parent = parent.parentNode;<br>}//while<br><br>var tags = parent.children;<br><br>var headers = [];<br>var paragraphs = [];<br><br>var totalText = &quot;&quot;;<br>var temp = gatherTextData(parent);<br>paragraphs = temp[0];<br>headers = temp[1];<br><br>if (tags.length == 0) {<br> paragraphs.push(parent.textContent || parent.innerText || &quot;&quot;)<br>}//if<br><br>totalText = paragraphs.join(&quot;\n&quot;);<br><br>var overallFreq = generateFrequencyTable(totalText);<br>var sentences = [];<br>var scores = [];<br>var paragraphBreaks = [0];<br><br>var count = 0;<br><br>for (var i = 0; i &lt; paragraphs.length; i++) {<br> var paraScore = scoreText(overallFreq, paragraphs[i]);<br> var paraTable = generateFrequencyTable(paragraphs[i]);<br><br> var thisSentences = splitSentences(paragraphs[i]);<br> var thisScores = [];<br><br> thisSentences.forEach(function(val, idx) {<br>  thisScores.push([idx + count, <br>   combineSentenceAndParagraphScores(idx, i, scoreText(paraTable, val), <br>            scoreText(overallFreq, val), <br>            paraScore)]);<br> });<br><br> sentences = sentences.concat(thisSentences);<br> scores = scores.concat(thisScores);<br><br> count += thisSentences.length;<br> paragraphBreaks.push(count);<br>}//for<br><br>if (num_sentences &lt; 1) {<br> num_sentences *= sentences.length;<br>}//if<br><br>num_sentences = Math.max(1, num_sentences);<br><br>//sort scores in descending order wrt/ sentence scores<br>scores.sort(function(a,b) {<br> return b[1] - a[1];<br>});<br>scores = scores.slice(0, num_sentences);<br><br>//sort scores in ascending order wrt/ sentence indexes<br>scores.sort(function(a,b) {<br> return a[0] - b[0];<br>});<br><br>var summarized = &quot;&quot;;<br><br>var prevParIdx = 0;<br>scores.forEach(function(val, scoreIdx) {<br> var idx = val[0];<br> var paraIdx = floor(paragraphBreaks, idx);<br><br> if (paraIdx &gt; prevParIdx) {<br>  if (scoreIdx != 0) {<br>   summarized += &quot;&lt;/p&gt;&quot;<br>  }//if<br><br>  for (var i = 0; i &lt; headers.length; i++) {<br>   if (paraIdx &gt; headers[i][0] &amp;&amp; (i == headers.length - 1 || paraIdx &lt;= headers[i + 1][0])) {<br>    summarized += &quot;&lt;h2&gt;&quot; + headers[i][1].replace(/(\[.*\])/g, &quot;&quot;) + &quot;&lt;/h2&gt;&quot;;<br><br>    headers = headers.slice(i + 1, -1);<br><br>    break;<br>   }//if<br>  }//for<br><br>  summarized += &quot;&lt;p&gt;&quot;;<br> }//if<br> prevParIdx = paraIdx;<br><br> summarized += sentences[idx].trim() + &quot; &quot;;<br>});<br><br>chrome.storage.local.set({&quot;summBot-summarized&quot;:summarized, &quot;summBot-title&quot;: document.title});<br>chrome.runtime.sendMessage({<br> from:&quot;select-summBot&quot;,<br> subject:&quot;ShowNotification&quot;<br>});<br><br>//get greatest value in array that is less than or equal to val<br>function floor(array, val) {<br> if (array[0] &gt; val) {<br>  return -1;<br> }//if<br><br> for (var i = 1; i &lt; array.length; i++) {<br>  if (array[i] &gt; val) {<br>   return i;<br>  }//if<br> }//for<br>}//floor<br><br>function gatherTextData(parent) {<br> var tags = parent.children;<br><br> var paragraphs = [];<br> var headers = [];<br><br> var count = 0;<br> for (var i = 0; i &lt; tags.length; i++) {<br>  var tag = tags[i].tagName;<br>  var text = tags[i].textContent || tags[i].innerText || &quot;&quot;;<br><br>  if (text.replace(/\W+/g, &quot; &quot;).length &gt; 0) {<br>   if (tag.length == 2 &amp;&amp; tag[0] == &quot;H&quot;) {<br>    headers.push([paragraphs.length, text]);<br>   } else if (tag == &quot;P&quot;) {<br>    paragraphs.push(text.trim());<br>   } else if (!tag_blacklist.includes(tag)) {<br>    var temp = gatherTextData(tags[i]);<br>    paragraphs = paragraphs.concat(temp[0]);<br><br>    temp[1].forEach(function(val,idx) {<br>     temp[1][idx] = [val[0] + count, val[1]];<br>    });<br><br>    headers = headers.concat(temp[1]);<br><br>   }//else<br><br>   count = paragraphs.length;<br>  }//if<br> }//for<br><br> return [paragraphs, headers];<br>}<br><br>/*******************************************<br><br>   SUMMARIZER FUNCTIONS<br> <br>********************************************/<br><br>function combineSentenceAndParagraphScores(idx, paraIdx, sentToParaScore, sentToAllScore, paraToAllScore) {<br> var score = sentToParaScore*0.5 + sentToAllScore * 0.5 + paraToAllScore * 0.1;<br><br> if (idx == 0) {<br>  score += sentToParaScore * 0.5;<br> }//if<br><br> if (paraIdx == 0) {<br>  score += paraToAllScore * 0.5;<br> }//if<br><br> return score;<br>}//combineSentenceAndParagraphScores<br><br>function splitSentences(text) {<br><br>  period_blacklist.forEach(function(val) {<br>    text = text.replace(new RegExp(val, &quot;g&quot;), val.replace(/\\\./g,&quot;&quot;));<br>  });<br>  text = text.replace(/\[[0-9]+\]/g, &quot;&quot;);<br><br>  var sentences = text.split(/(?&lt;=[\.|!|\?])\s/g);<br><br>  if (sentences[sentences.length - 1].trim().length == 0) {<br>   return sentences.slice(0,-1);<br>  } else {<br>   return sentences;<br>  }//else<br>}//splitSentences<br><br>function verifyWord(word) {<br> return word.length &gt; 1 &amp;&amp; !blacklist.includes(word);<br>}//verifyWord<br><br>function generateFrequencyTable(text) {<br> var words = text.toLowerCase().replace(/\W+/g, &quot; &quot;).split(&quot; &quot;);<br><br> var table = {};<br><br> for (var i = 0; i &lt; words.length; i++) {<br>  if (verifyWord(words[i])) {<br>   var search = tableContains(table, words[i]);<br><br>   if (search) {<br>    table[search]++;<br>   } else {<br>    table[words[i]] = 1;<br>   }//else<br>  }//if<br> }//for<br><br> return table;<br>}<br><br>function tableContains(table, word) {<br> for(var key in table) {<br>  if (equiv(key, word)) {<br>   return key;<br>  }//if<br> }//for<br><br> return false;<br>}<br><br>function scoreText(wordTable, text) {<br> var words = text.toLowerCase().replace(/\W+/g, &quot; &quot;).split(&quot; &quot;);<br><br> var score = 0;<br><br> for (var i = 0; i &lt; words.length; i++) {<br>  score += scoreWord(wordTable, words[i]);<br> }//for<br><br> score /= Math.pow(text.length, 0.5);<br><br> return score;<br>}//scoreText<br><br>function equiv(word1, word2) {<br> return word1.includes(word2) || word2.includes(word1);<br>}//equiv<br><br>function scoreWord(wordTable, word) {<br><br> for(var key in wordTable) {<br>  if (equiv(key, word)) {<br>   return wordTable[key];<br>  }//if<br> }//for<br><br> return 0;<br>}//scoreWord</pre><p>We have the backbone of the tool set.</p><p>With the mechanism of the summarisation is codified, I want the user to also be able to tailor the experience for themselves. This is by way of the extent to which you want something summarised (a percentage tool), or a word count threshold. By formulating <em>setting.js</em>, we allow for the ‘settings’ of the tool (i.e. how a user would navigate it simply) and customise that.</p><p><strong><em>setting.js</em></strong></p><pre>document.addEventListener(&#39;DOMContentLoaded&#39;, function() {<br> <br> if (localStorage[&quot;SETTINGS-compressto&quot;] == undefined) {<br>  localStorage[&quot;SETTINGS-compressto&quot;] = &quot;percent&quot;;<br>  localStorage[&quot;SETTINGS-percentval&quot;] = 50;<br>  localStorage[&quot;SETTINGS-numsentval&quot;] = 10;<br> }<br> <br> readSettings(); <br> updateNumSentLabel();<br> updatePercentLabel(); <br> $(&quot;#&quot; + localStorage[&quot;SETTINGS-compressto&quot;] + &quot;radio&quot;).attr(&quot;checked&quot;, &quot;true&quot;);<br> $(&quot;input[name=method]&quot;).change(function() {<br>  toggleCompressionMethod($(this).val());<br>  if (typeof $(&quot;#percent&quot;).attr(&quot;disabled&quot;) == typeof undefined || $(&quot;#percent&quot;).attr(&quot;disabled&quot;) == false) {<br>   localStorage[&quot;SETTINGS-compressto&quot;] = &quot;percent&quot;;<br>  } else {<br>   localStorage[&quot;SETTINGS-compressto&quot;] = &quot;numsent&quot;;<br>  }//else<br> })<br> $(&quot;#percentval&quot;).on(&quot;input&quot;, function() {<br>  updatePercentLabel();<br> });<br> $(&quot;#percentval&quot;).on(&quot;change&quot;, function() {<br>  localStorage[&quot;SETTINGS-percentval&quot;] = $(&quot;#percentval&quot;).val();<br> });<br> $(&quot;#numsentval&quot;).on(&quot;input&quot;, function() {<br>  updateNumSentLabel();<br>  localStorage[&quot;SETTINGS-numsentval&quot;] = $(&quot;#numsentval&quot;).val();<br> }); <br><br>});<br>function readSettings() {<br> toggleCompressionMethod(localStorage[&quot;SETTINGS-compressto&quot;]);<br> $(&quot;#percentval&quot;).val(localStorage[&quot;SETTINGS-percentval&quot;]);<br> $(&quot;#numsentval&quot;).val(localStorage[&quot;SETTINGS-numsentval&quot;]);<br> updateNumSentLabel();<br> updatePercentLabel();<br>}<br>function updatePercentLabel() {<br> $(&quot;#showpercent&quot;).text($(&quot;#percentval&quot;).val() + &quot;%&quot;); <br>}<br>function updateNumSentLabel() {<br> if ($(&quot;#numsentval&quot;).val() &gt; 1) {<br>  $(&quot;#shownumsent&quot;).text(&quot; sentences&quot;);<br> } else {<br>  $(&quot;#shownumsent&quot;).text(&quot; sentence&quot;);<br> }//else<br>}<br>function toggleCompressionMethod(val) {<br> if (val == &quot;percent&quot;) {<br>  $(&quot;#numsent&quot;).attr(&quot;disabled&quot;, &quot;true&quot;);<br> } else if (val == &quot;numsent&quot;) {<br>  $(&quot;#percent&quot;).attr(&quot;disabled&quot;, &quot;true&quot;);<br> }//else<br> $(&quot;#&quot; + val).removeAttr(&quot;disabled&quot;);<br>}</pre><p>For web development, by and large, you can’t use JavaScript without HTML. HTML is used to create the structure and layout of web pages, while JavaScript is used to add interactivity and dynamic content. Thus, for every .js that is to be operated on a webpage, there is an equivalent .html. In this case, <em>settings.html.</em></p><p><strong><em>settings.html</em></strong></p><pre>&lt;!DOCTYPE HTML&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Scrub&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;style.css&quot;&gt;<br>    &lt;script src=&quot;settings.js&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;jquery.min.js&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body id=&quot;settings&quot;&gt;<br>   &lt;h1 id=&quot;title&quot;&gt;Settings&lt;/h1&gt;<br>   &lt;div id=&quot;form&quot;&gt;<br>      &lt;h1&gt;Filter&lt;/h1&gt;<br>    &lt;input type=&quot;radio&quot; name=&quot;method&quot; id=&quot;percentradio&quot; value=&quot;percent&quot;&gt;<br>    &lt;span class=&quot;option&quot; id=&quot;percent&quot;&gt;<br>   Summarise by percentage: &lt;br /&gt;<br>     &lt;span class=&#39;range&#39;&gt;&lt;input id=&quot;percentval&quot; type=&quot;range&quot; min=&quot;1&quot; max=&quot;100&quot; value=&quot;50&quot; class=&quot;slider&quot; /&gt;&amp;nbsp;&lt;label id=&quot;showpercent&quot;&gt;&lt;/label&gt;&lt;/span&gt;<br>    &lt;/span&gt;<br>   &lt;br /&gt;&lt;br /&gt;<br>    &lt;input type=&quot;radio&quot; name=&quot;method&quot; id=&quot;numsentradio&quot; value=&quot;numsent&quot;&gt;<br>    &lt;span class=&quot;option&quot; id=&quot;numsent&quot;&gt;<br>     Summarise by number of sentences: &lt;br /&gt;<br>     &lt;span class=&#39;range&#39;&gt;&lt;input id=&quot;numsentval&quot; type=&quot;text&quot; min=&quot;1&quot; max=&quot;10000&quot; value=&quot;50&quot; /&gt;&amp;nbsp;&lt;label id=&quot;shownumsent&quot;&gt;sentence(s)&lt;/label&gt;&lt;/span&gt;<br>        &lt;/span&gt;<br>   &lt;/div&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><p>**Here, I link back to <em>style.css</em>. <em>CSS</em> is the language used to ‘style’ a HTML document — i.e. the language used for describing the presentation of a document written in a markup language such as HTML. The style.css document is what I use to design the overall look, and describe in detail below. But for now, this html file links back to it.</p><p><strong><em>background.js</em></strong></p><p>Now, the user needs to be able to link your tool to the webpage on which they’re using it — for example, the by highlighting a chunk of text they want summarised, by choosing the ‘percentage’ level etc.</p><pre>addContextMenu(); chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {<br>  if (request[&quot;subject&quot;] == &quot;ShowNotification&quot;) {<br>      chrome.browserAction.setBadgeText({text: &quot; &quot;});<br>      chrome.browserAction.setBadgeBackgroundColor({&quot;color&quot;:[0, 200, 100, 255]});<br>  }//if<br>});<br>function addContextMenu() {<br>  chrome.contextMenus.create({<br>      &quot;title&quot;: &quot;Click to summarise article...&quot;,<br>      &quot;id&quot;:&quot;sum_selected&quot;,<br>      &quot;contexts&quot;:[&quot;selection&quot;]});<br>  chrome.contextMenus.onClicked.addListener(function(info, tab) {<br>    if (info.menuItemId == &quot;sum_selected&quot;) {<br>        chrome.browserAction.setBadgeText({text: &quot; &quot;});<br>        chrome.browserAction.setBadgeBackgroundColor({&quot;color&quot;:[0, 100, 200, 255]});<br>  if (localStorage[&quot;SETTINGS-compressto&quot;] == undefined) {<br>   localStorage[&quot;SETTINGS-compressto&quot;] = &quot;percent&quot;;<br>   localStorage[&quot;SETTINGS-percentval&quot;] = 50;<br>   localStorage[&quot;SETTINGS-numsentval&quot;] = 10;<br>  }<br>        var num_sentences = 0;<br>        if (localStorage[&quot;SETTINGS-compressto&quot;] == &quot;numsent&quot;) {<br>          num_sentences = localStorage[&quot;SETTINGS-numsentval&quot;];<br>        } else {<br>          num_sentences = localStorage[&quot;SETTINGS-percentval&quot;] / 100.0;<br>        }//else<br>        chrome.tabs.executeScript(null, {code: &quot;var num_sentences=&quot; + num_sentences + &quot;;&quot;}, function() {<br>                    chrome.tabs.executeScript(null, {file:&#39;select.js&#39;});});<br>    }//if<br>  });<br>}</pre><p>After that, when you have the package, it’s a matter of uploading the manifest.json file as an extension on your Chrome browser. This part is simply a matter of navigating Google settings:</p><ol><li>Go to the “…” at the top right of the browser then select <em>Extensions</em> from the menu</li><li>Enable<em> Developer Mode</em> and then click <em>Load unpacked </em>— this allows you to basically upload your own extensions, so simply select your file</li></ol><p>It’s 2024 now, almost 4 years after my completion of CS50 2020 and this tool, so for context, this draft has been in the works for a long time. I haven’t been up to much coding since then, admittedly, but I do stand by the course for being a fantastic introduction into logic, math and coding — and tying it all together with a focus on creativity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df2b566f035b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dark Webs and Data (pt 1)]]></title>
            <link>https://medium.com/@dentured/dark-webs-and-data-pt-1-88251ce931a5?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/88251ce931a5</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[darkweb]]></category>
            <category><![CDATA[thesis]]></category>
            <category><![CDATA[cybercrime]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 08:41:33 GMT</pubDate>
            <atom:updated>2023-01-02T08:44:47.421Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>part 1 of a final year thesis writing journey: what’s the topic?</blockquote><p>The nexus between data and criminality is a hot grey space — cybersecurity, cryptocurrency, privacy and many other buzzwords exist here. A significant game-changer in this regard is the recent gearing up of regulations, pioneered predominantly by the EU’s General Data Protection Regulations (GDPR) which targets transparency of data, compliance of entities to data protection and punishment for breaches.</p><p>Observing the impact of regulation on legal data markets and flows (e.g. corporation’s data breaches) has occupied the bulk of academia’s focus, but there remains a fascinating and gravely understudied area: the impact of surface web regulations on dark web activities. The immediate association to the ‘dark web’ remains the infamous Silk Road’s drug trade, but the data markets there are increasingly gaining attention given the post Covid-19 prevalence of cybercrime, the crypto boom as well as the volatile nature of the dark web itself. How do you regulate something that is, by nature, designed to be unobservable?</p><p>In many ways, my journey through data protection, cybersecurity and the broader umbrella of charting the economics of technological diffusion has led me here to attempt to tackle the question of <strong><em>how surface web privacy regulations affect the economics of the dark web data trade.</em></strong></p><p>In this context, important questions arise regarding how the dark web data trade occurs and is measured — this includes the sale of identities, private corporate information, credit card information, netflix accounts. Thus, I propose an empirical model that identifies and consolidates the pricing of each ‘unit’ of data — measured accross different categories of financial, medical, entertainment information- and use this to assess how the larger economic activity of the main markets have been affected post-introduction and implementation of the GDPR. <em>Does the price of a Chase bank account pin become more expensive? Is a German driving license now worth less? How about CCTV footage of random public spaces in Singapore, or someone’s booking information for a scheduled flight? </em>Naturally, there is a geographical element to this — if the data originates from Europe, the impacts of the GDPR will be different (and presumably more significant) as opposed to the Americas. A comparison with prices of off-data goods traded on the dark web across the same timeline will also be interesting — <em>does the price of drugs change in the same linear fashion as data?</em></p><p>Ideally, these questions will shape my research going forward. Penning down these preliminary thoughts about my capstone topic was supposed to be an one-off event just to consolidate my own thoughts, but perhaps making it into a series would be a more effective journey. I suppose the next part would now be to dive into the dark web itself!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88251ce931a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 2020 Pset 6: DNA]]></title>
            <link>https://medium.com/@dentured/cs50-2020-pset-6-dna-66105b3425a2?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/66105b3425a2</guid>
            <category><![CDATA[cs50]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Sat, 03 Oct 2020 15:48:27 GMT</pubDate>
            <atom:updated>2020-10-03T15:48:27.533Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>tl;dr: implementing a program that identifies a person based on their DNA in python.</blockquote><p>I must say that I really appreciate the real-world context of the questions and psets of CS50. The last part of python entails writing a program that will take sequences of DNA (in a permutation of A, G, T and C) to find which patterns repeated the most consecutively, and match it to the person to whom the DNA likely belongs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*SSumznG7Fy8cR0TvMNlj0g.jpeg" /></figure><p>The specifications provided are rather comprehensive and break down the task at hand. Firstly, the program should ask for an input of the relevant text files (namely, dna.py, data.csv and sequence.txt). After opening the files and reading the contents into its memory, the program should compute the longest run of consecutive repeats of the DNA patterns, and print out the name of the individual with the corresponding pattern. The pseudocode is as such:</p><ol><li>Check if input is valid (i.e. if there are 3 arguments); if not, print error message.</li><li>Read the DNA sequence from the file</li><li>Store the information in a string</li><li>Create a dictionary to store the DNA sequences that are to be counted</li><li>Extract the sequences from the database into a list</li><li>Copy the list into a dictionary where the genes are the keys</li><li>Iterate through the DNA sequence</li><li>Add a counter — if repetitions of the values from sequence dictionaries are found, add them up</li><li>Open the database (of people) file</li><li>Iterate through and compare to the sequences dictionary</li><li>If there is a match, print the name of the person; if not, no match.</li></ol><p>I was a bit daunted by how complicated it looked but once broken down, it’s digestible!</p><p>First, check the length of the input. If there are less than 3 arguments keyed in, show error message.</p><pre><strong><em>#check length<br></em></strong>if len(argv) &lt; 3:<br>    print(&quot;Usage: python dna.py data.csv sequence.txt&quot;)<br>    exit()</pre><p>Then, read the first file — the DNA sequence. Store this as strings and create a dictionary for the next part.</p><pre><strong><em># read the dna sequence from the file<br></em></strong>with open(argv[2]) as DNAfile:<br>    DNAreader = reader(DNAfile)<br>    for row in DNAreader:<br>        DNAlist = row</pre><pre><strong><em>#store in string<br></em></strong>DNA = DNAlist[0]</pre><pre><strong><em>#create a dictionary<br></em></strong>sequences = {}</pre><p>Fifth, extract the sequences from the DNA database into a list.</p><pre>with open(argv[1]) as peoplefile:<br>    people = reader(peoplefile)<br>    for row in people:<br>        DNASequences = row<br>        DNASequences.pop(0)<br>        break</pre><p>Then copy this list into a dictionary — the point of this is so that now each gene is a key in itself. This allows for iteration and one-by-one comparison.</p><pre>for item in DNASequences:<br>    sequences[item] = 1</pre><p>Iterate through the DNA sequence.</p><pre><strong><em># if repetitions of the values from sequence dictionary are found, count<br></em></strong>for key in sequences:<br>    l = len(key)<br>    tempMax = 0<br>    temp = 0<br>    for i in range(len(DNA)):<br>       <strong><em> # after having counted a sequence</em></strong><br>        <strong><em># skip at the end of it to avoid counting again</em></strong><br>        while temp &gt; 0:<br>            temp -= 1<br>            continue</pre><pre><strong><em># if the segment of dna corresponds to the key &amp;&amp; <br>        #there is a repetition of it <br>        #increment counter</em></strong>  <br>        if DNA[i: i + l] == key:<br>            while DNA[i - l: i] == DNA[i: i + l]:<br>                temp += 1<br>                i += l</pre><pre><strong><em># compare the value to the previous longest sequence &amp;&amp; <br>            # if it is longer it becomes the new max</em></strong><br>            if temp &gt; tempMax:<br>                tempMax = temp</pre><pre><strong><em># store the longest sequences in the dictionary using the correspondent key<br></em></strong>    sequences[key] += tempMax</pre><p>In order to compare, the other file aka the database of people needs to be opened and iterated through as well. Similarly, this needs to be in a dictionary form for comparison.</p><pre>with open(argv[1], newline=&#39;&#39;) as peoplefile:<br>    people = DictReader(peoplefile)<br>    for person in people:<br>        match = 0<br><strong><em>        # compares the sequences to every person and prints name <br>        # leave the program if there is a match<br></em></strong>        for DNA in sequences:<br>            if sequences[DNA] == int(person[DNA]):<br>                match += 1<br>        if match == len(sequences):<br>            print(person[&#39;name&#39;])<br>            exit()<br><strong><em>    #otherwise, no match<br></em></strong>    print(&quot;No match&quot;)</pre><p>The concluding part is just a matter of printing the corresponding name. Admittedly, this took a while for me to get through but again, much much better than C.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66105b3425a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 2020 Pset 6: Readability]]></title>
            <link>https://medium.com/@dentured/cs50-2020-pset-6-readability-f584da59f74c?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f584da59f74c</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cs50]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 04:00:23 GMT</pubDate>
            <atom:updated>2020-09-29T04:00:23.322Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>tl;dr: design and implement a program that computes the Coleman-Liau index (i.e. readability) of the text.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2ZxGrI-8XZHoS5Df40i1Q.jpeg" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@alfonsmc10?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Alfons Morales</em></a><em> on </em><a href="https://unsplash.com/s/photos/reading?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Unsplash</em></a>. Beautiful tbh.</figcaption></figure><p>Readability in C and Python are really similar — the main issue here is understanding what are the distinctive elements that let you differentiate between letters, words and sentences. But before that, let’s look at the pseudocode:</p><ol><li>Prompt user for a string of text</li><li>Initialise the 3 different counters to 0 — counter for letters, words and sentences.</li><li>Iterate through each individual letter using the len()</li><li>For each iteration, then count: no. of letters, no. of words and no. of sentences</li><li>Compute the index using 0.0588 * L - 0.296 * S - 15.8, where L is the average number of letters per 100 words in the text, and S is the average number of sentences per 100 words in the text.</li><li>Round the index to the nearest integer</li><li>If resulting index number is 16 or higher, print &quot;Grade 16+&quot;; if the index number is less than 1, print &quot;Before Grade 1&quot;. Otherwise, print the index number itself.</li></ol><p>The initial parts are as such:</p><pre>from cs50 import get_string</pre><pre><strong><em>//get input<br></em></strong>text = get_string(&quot;Text: &quot;)</pre><pre><strong><em>//initialise counters to 0 <br></em></strong>n_words = n_sent = n_let = i = 0<br>length = len(text)</pre><p>Next up, to identify which are letters, words and sentences:</p><p>Since letters are the base unit of the text input, they can simply be found using .isalpha() which sieves out alphabets and not the spaces in between.</p><p>For words, there are two parts:</p><p>(a) the first word, which is found where i = 0 and [i + 1] immediately after is <strong>not</strong> a &lt;space&gt;.</p><p>(b) second to last word, which is found by counting where there is a letter immediately after a &lt;space&gt; — text[i] == “ ” and text[i + 1] != “ ”. Note that this search has to stop after the last word, and so i != length.</p><p>For sentences, the number of sentences = number of punctuation marks. Hence, we find where i = “.” or “?” or “!”.</p><p>And for each one, we add to their respective counters.</p><p>Hence:</p><pre>while i &lt; length:</pre><pre><strong><em>//counting letters</em></strong></pre><pre>    if text[i].isalpha():<br>        n_let += 1</pre><pre><strong><em>//counting words</em></strong></pre><pre>    if (i == 0 and text[i] != &quot; &quot;) or (i != length and text[i] == &quot; &quot; and text[i + 1] != &quot; &quot;):<br>        n_words += 1</pre><pre><strong><em>//counting letters</em></strong></pre><pre>    if text[i] == &quot;.&quot; or text[i] == &quot;?&quot; or text[i] == &quot;!&quot;:<br>        n_sent += 1<br>    i += 1</pre><pre><strong><em>//using the given formula</em></strong></pre><pre>L = (n_let / n_words) * 100<br>S = (n_sent / n_words) * 100<br>index = round(0.0588 * L - 0.296 * S - 15.8)</pre><pre><strong><em>//print</em></strong></pre><pre>if index &lt; 1:<br>    print(&quot;Before Grade 1&quot;)<br>elif index &gt;= 16:<br>    print(&quot;Grade 16+&quot;)<br>else:<br>    print(f&quot;Grade {index}&quot;)</pre><p>The last part is just a matter of rounding and finding the average count, and printing accordingly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f584da59f74c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 2020 Pset 6: Cash]]></title>
            <link>https://medium.com/@dentured/cs50-2020-pset-6-cash-e7b5f243d939?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b5f243d939</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cs50]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 14:10:31 GMT</pubDate>
            <atom:updated>2020-09-25T14:10:31.981Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>tl;dr: calculating the minimum number of coins required to give someone their change in Python</blockquote><p>Really starting to like python!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Enas0g5DrBytsaPbV4K0vQ.jpeg" /></figure><p>Here, the logic behind cash in python is the same as that of C. The pseudocode is simply:</p><ol><li>Set coin counter to 0.</li><li>Prompt user for an amount in dollars.</li><li>If input is &gt; 0, ask again.</li><li>Convert the amount from dollars to cents and start eliminating — that is, for every 25c in the given input of, say, X, the coin counter increases</li><li>Repeat this for 10c, 5c and 1c</li><li>Print the number of coins</li></ol><p>This is rather intuitive; it’s a bit like you sorting out a pile of coins, starting with the biggest coin, and counting them while you go. Naturally, once all the big 25c coins are accounted for, you’ll progress to smaller 10c and 5c coins.</p><pre>from cs50 import get_float</pre><pre><strong><em>//set coin counter to 0</em></strong><br>coins = 0</pre><pre><strong><em>//ask for input; stop asking only when input is valid (i.e. &gt; 0)<br></em></strong>while True:<br>    change_dollar = get_float(&quot;Change (dollars): &quot;)<br>    if change_dollar &gt; 0:<br>        break</pre><pre><strong><em>//convert it into cents and round</em></strong></pre><pre>change = round(int(change_dollar * 100))</pre><pre><strong><em>//for every coin sorted, the counter +1</em></strong><br>while change &gt; 0:<br>    while change &gt;= 25:<br>        coins += 1<br>        change -= 25<br>    while change &gt;= 10:<br>        coins += 1<br>        change -= 10<br>    while change &gt;= 5:<br>        coins += 1<br>        change -= 5<br>    while change &gt;= 1:<br>        change -= 1<br>        coins += 1</pre><pre>print(coins)</pre><p>get_float is used here so that the program can work with inputs like 5.0 and 5.000 and not worry about formatting or decimal spaces!</p><p>In C however, it was slightly more tedious — for every coin added, you had to make sure the amount from subtracted from the change amount. That is,</p><pre>while (cent &gt;= 25)<br>    {<br>        coins ++;<br>        <strong>cent = cent - 25;</strong><br>    }<br>    //while we can use dimes, add a dime<br>    while (cent &gt;= 10)<br>    {<br>        coins ++;<br><strong>        cent = cent - 10;<br></strong>    }<br>    <br>    //while we can use pennies, add a penny<br>    while (cent &gt;= 5)<br>    {<br>        coins ++;<br><strong>        cent = cent - 5;<br></strong>    }<br>    <br>    //while we can use pennies, add a penny<br>    while (cent &gt;= 1)<br>    {<br>        coins ++;<br><strong>        cent = cent - 1;<br></strong>    }</pre><p>Next pset: Readability!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b5f243d939" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 2020 Pset 6: #Mario]]></title>
            <link>https://medium.com/@dentured/cs50-2020-pset-6-mario-a6cde68569c6?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6cde68569c6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[cs50]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 07:44:25 GMT</pubDate>
            <atom:updated>2020-09-25T07:52:21.996Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>tl;dr: implementing a program that prints out a half-pyramid of a specified height in Python</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiVPUAFOQECF-NShqYdF_w.png" /></figure><p>Back to CS50!</p><p>Who knew I needed a 2 month break after Speller.</p><p>But rest assured, venturing into Python territory feels far more comfortable and fun. I find myself appreciating the slowburn syllabus of CS50 more and more — starting off with C and then gradually transitioning into much easier (and more usable) languages means that I can genuinely see the transferability and applicability of the skills I so arduously learnt. Plus I think the counter-intuitiveness of C (at least to me) just makes everything else seem easier.</p><p>Anyways, Mario! Compared to C, the process using Python is much more streamlined and concise. Here goes the pseudocode:</p><ol><li>Prompt user for height <strong>h </strong>(1 ≤ h ≤ 8) using get_int.</li><li>Check if input is valid; else, break</li><li>Iterate through h — for every iteration through h, there will be (h-1) &lt;spaces&gt; before the ‘#’, and so on.</li></ol><p>Essentially it’s math, in that if my height is 4, then naturally my first row will be 3 &lt;spaces&gt; and 1 #, then 2 &lt;spaces&gt; and 2 #s etc etc. Thus, in code, it look as such:</p><pre>from cs50 import get_int</pre><pre><strong><em>//ensure valid input; prompt user if h is &lt;1 or &gt;8</em></strong></pre><pre>while True:<br>    h = get_int(&#39;height: &#39;)<br>    if h &lt; 1 or h &gt; 8:<br>        h = get_int(&#39;height: &#39;)<br>    if h &gt;= 1 or h &lt;= 8:<br>        break</pre><pre><strong><em>// iterate through h</em></strong></pre><pre>for i in range(h):<br>    print((h - 1 - i) * &quot; &quot;, end=&quot;&quot;)<br>    print((i + 1) * &quot;#&quot;)</pre><p>The end= “” is simply a way to combat the fact that python’s print() function default ends with a newline. With end= “”, the # will continue from the &lt;space&gt; as opposed to beginning a newline below.</p><p>I think there’s about 3 more python psets to do, so let’s go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6cde68569c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 2020 Pset 5: Speller]]></title>
            <link>https://medium.com/@dentured/cs50-2020-pset-5-speller-c9d05afc490?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9d05afc490</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[cs50]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 13:26:01 GMT</pubDate>
            <atom:updated>2020-07-22T13:26:01.944Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>tl;dr: walking through a coding problem that takes words in a dictionary and checks if they’re spelt correctly, in the shortest amount of time possible</blockquote><p>Week 5 focused on data structures, dereferencing and general low-level access to computer memory. The idea of hash tables and linked lists was like a singular enlightening moment for me, given the amount of real world examples that utilise that concept. Not to say that the concepts i’ve learnt thus far were in the abstract, but I think strategically this was a good note to end C at.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18_rOe_1RefP49jggB2hjw.jpeg" /><figcaption>speller — spelling bee — beehive — the little honey pockets resembling buckets — buckets in a linked list — data structures!</figcaption></figure><p>So, <em>prima facie,</em> speller seems rather fun. The crux of this problem set is to implement the fastest possible spell checker. Fastest here meaning in seconds, so like a real world application of the O(n) algorithms.</p><p>Like runoff, I was daunted at first but the code being broken down into 5 different blocks, and the walkthrough, helped tremendously. Key ideas here include a helper function, <strong>load</strong>, which stores and reads the dictionary file; <strong>hash, </strong>which utilises the linked list knowledge and requires the building of a hash table and an index to store the words efficiently; <strong>check</strong> which cross references and sees whether a given word is in the dictionary; <strong>size</strong> returns the number of words in the dictionary; and <strong>unload</strong> frees the dictionary from memory .</p><p><strong>part 0: definitions</strong></p><pre><strong>// Implements a dictionary&#39;s functionality</strong></pre><pre>#include &lt;stdbool.h&gt;<br>#include &quot;dictionary.h&quot;<br>#include &lt;stdio.h&gt;<br>#include &lt;cs50.h&gt;<br>#include &lt;ctype.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;strings.h&gt;</pre><pre><strong>//represents a node in a hash table<br></strong>typedef struct node<br>{<br>    char word[LENGTH + 1];<br>    struct node *next;<br>}<br>node;</pre><pre><strong>// no. of buckets in hash table<br></strong>const unsigned int N = 26;<strong><br>// initialise positive hash value using unsigned int </strong><br>unsigned int hash_value;<br><strong>// initialise (positive) hash table word count <br></strong>unsigned int word_count;<br><strong>// hash table<br></strong>node *table[N];</pre><p>Inserting this “part 0” here retrospectively, as I realised after finishing up the rest of this walkthrough that I didn’t mention anything about initialising the functions! This was just a matter of using <strong>unsigned int</strong> (for positive integers) to initialise the different values we need, and setting N = 26 preliminarily such that each alphabet gets a bucket. More about that under <strong>part 2: hash</strong>!</p><p><strong>part 1: load</strong></p><p>Calling the load function on a dictionary text file stores the words in the dictionary data structure into a hash table, which basically maps keys to values by using a hash function to compute an index (i.e. hash code) into an array of buckets (from which we can pluck the word we want). Each bucket then has a linked list, where each node has a value and a pointer to the next node, with the last node pointing to a NULL value.</p><p><strong>malloc</strong> takes an argument (the number of bytes you want to allocate) and returns that chunk of memory by way of the first address stored in the pointer. This allows for dynamic memory allocation. Here, malloc is used for every new word that’s in the file.</p><p>Now, onto the actual loading.</p><ol><li>Take as argument a char* or a string which is the dictionary file to open up and read from</li><li>Use <strong>fopen</strong> to open file</li><li>Return true if executed successfully</li><li>If return value is NULL, return false (memory allocation error)</li><li>Use <strong>fscanf</strong> to read the strings in the file till EOF (end of file)</li><li>Use <strong>malloc </strong>to create and allocate memory for each new node</li><li>If it returns NULL, return false</li><li>Copy word into node using <strong>strcpy</strong></li><li>Use <strong>hash</strong> to take the words and return a hash value/index</li><li>Insert node into hash table by setting pointer to consecutive nodes</li><li>Count the number of words being input</li></ol><pre><strong><em>// Loads dict into memory, returning true if successful else false</em></strong><br>bool load(const char *dictionary)<br>{<br>    <strong><em>// Open dict </em></strong><br>    FILE *file = fopen(dictionary, &quot;r&quot;);</pre><pre><strong><em>// If file is not opened, return false</em></strong><br>    if (file == NULL)<br>    {<br>        return false;<br>    }<br>    <strong><em>// storage space for word</em></strong><br>    char word[LENGTH + 1];</pre><pre><strong><em>// Scan dict for strings that are not the end of the file</em></strong><br>    while (fscanf(file, &quot;%s&quot;, word) != EOF)<br>    {<br>        <strong><em>// Allocate memory for new node</em></strong><br>        node *n = malloc(sizeof(node));</pre><pre><strong><em>// If malloc returns NULL, return false</em></strong><br>        if (n == NULL)<br>        {<br>            return false;<br>        }</pre><pre><strong><em>// Pointer to next node and word itself</em></strong><br>        strcpy(n-&gt;word, word);<br>        <strong><em>// Hash the word to get hash value</em></strong><br>        hash_value = hash(word);<br>        <strong><em>// Set new pointer</em></strong><br>        n-&gt;next = table[hash_value];<strong><br>        <em>// Set head to new pointer</em></strong><br>        table[hash_value] = n;<br>        <strong><em>// Increment word count</em></strong><br>        word_count++;<br>    }</pre><pre><strong><em>// Close file</em></strong><br>    fclose(file);</pre><pre><strong><em>// If dict is loaded, return true</em></strong><br>    return true;<br>}</pre><p><strong>part 2: hash</strong></p><p>The hash function takes a word and returns the hash or numerical value of the word to check if it’s correct.</p><ol><li>take in inputs which are alphabetical characters, irregardless of capitalisation and possibly with apostrophes</li><li>the output should be a numerical index between 0 and N-1, inclusive</li><li>deterministic</li></ol><p>The bigger N is, the more efficiently the programme will run. If function ends up with a value greater than N, <strong>% N</strong> can be used to get a value within the appropes range.</p><p>I played it simple by going for a ‘first letter’ hash function, with N = 26 buckets. So here I poked around on reddit to find hash functions and found this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnjEmt8JzcRQS8TIXZYbOA.png" /><figcaption><a href="http://www.cse.yorku.ca/~oz/hash.html">http://www.cse.yorku.ca/~oz/hash.html</a></figcaption></figure><p>Had to adapt it a little for my own use, but before that, I really had to understand what the hash function was even doing. Turns out that the hash &lt;&lt; 5 (left shift operator) means that the hash is moved left (in terms of binary) by 5 bits (as specified by the right operand). Not sure how Dan Bernstein arrived at this but kudos to him and i’m just going to use this function and see what happens.</p><p>So a customised version of that looked like this. Both <strong>toupper </strong>and <strong>tolower</strong> can be used to standardise the capitalisation since that affects the hash value.</p><pre><strong><em>// Hashes word to a number</em></strong><br>unsigned int hash(const char *word)<br>{<br>    unsigned long hash = 5381;<br>    int c;<br>    while ((c = <strong>toupper</strong>(*word++)))<br>    {<br>        hash = ((hash &lt;&lt; 5) + hash) + c; /* hash * 33 + c */<br>    }<br>    return hash % N;<br>}</pre><p><strong>part 3: size</strong></p><p>In order to return the number of the words, the programme should keep track of the number of words added in real time. <strong>word_count </strong>has already been defined in <strong>load</strong>, so this was just a matter of returning that.</p><pre><strong><em>// Returns number of words in dictionary if loaded, else 0 if not yet loaded</em></strong><br>unsigned int size(void)<br>{<br>    <strong><em>// Check if there are any words</em></strong><br>    if (word_count &gt; 0)<br>    {<br>        <strong><em>// Return count</em></strong><br>        return word_count;<br>    }<br>    <strong><em>// Else</em></strong><br>    return 0;<br>}</pre><p><strong>part 4: check</strong></p><p>Check if the word is in the dictionary or not, regardless of capitalisation. The output is in the form of a bool.</p><ol><li>Hash word to obtain a hash value</li><li>Access linked list at that hash value at that particular index in the hash table</li><li>Traverse linked list, looking at one node at a time, for the particular word.</li><li>To traverse, set a cursor or a pointer to the first node in linked list</li><li>Use <strong>strcasecmp</strong>, which is like <strong>strcmp</strong> but insensitive to case, to check if the word is in the dictionary.</li><li>If that is not the word, <strong>cursor = cursor -&gt;next</strong> to move to the next node.</li><li>Do this until cursor = NULL (eof), and if the word isn’t found, return false</li></ol><pre><strong><em>// Returns true if word is in dictionary else false</em></strong><br>bool check(const char *word)<br>{<br>    <strong><em>//hash the word to get hash value</em></strong><br>    hash_value = hash(word);<br>    <strong><em>//access the linked list  </em></strong><br>    node *cursor = table[hash_value];</pre><pre><strong><em>//go through the linked list</em></strong><br>    while (cursor != NULL)<br>    {<br>        <strong><em>//check if the word matches</em></strong><br>        if (strcasecmp(word, cursor-&gt;word) == 0)<br>        {<br>            return true;<br>        }</pre><pre><strong><em>//move cursor to next node</em></strong><br>        cursor = cursor-&gt;next;<br>    }</pre><pre>return false;<br>}</pre><p><strong>part 5: unload</strong></p><p>As stressed in the lecture, good practice is to free up any memory that might have been allocated in the process of running a programme. While it seemed rather complicated to unload by creating a temporary cursor as a ‘placeholder’ as opposed to freeing the cursor itself, the reasoning behind it is rather intuitive. The walkthrough reiterates the concepts in the lecture — it is imperative that one doesn’t simply truncate a linked list because that would mean losing all the relevant linked information.</p><ol><li>Go through each bucket and set a cursor to its location</li><li>Create a temp variable that points to the first node</li><li>Move the actual cursor to the next node in the list</li><li>Free up the temp variable</li><li>Repeat until cursor reaches the last bucket and is NULL</li><li>Return true</li></ol><pre><strong><em>// Unloads dictionary from memory, returning true if successful else false<br></em></strong>bool unload(void)<br>{<br>    <strong><em>// Iterate through buckets</em></strong><br>    for (int i = 0; i &lt; N; i++)<br>    {<br>        <strong><em>// Set cursor to this each bucket location  </em></strong><br>        node *cursor = table[i];</pre><pre><strong><em>// If cursor is not NULL, free  </em></strong><br>        while (cursor)<br>        {<br>            <strong>// Create temp </strong><br>            node *tmp = cursor;<br>            <strong>// Move cursor to next node</strong><br>            cursor = cursor-&gt;next;<br>            <strong>// Free up temp</strong><br>            free(tmp);<br>        }</pre><pre><strong><em>// If cursor is NULL</em></strong><br>        if (i == N - 1 &amp;&amp; cursor == NULL)<br>        {<br>            return true;<br>        }<br>    }<br>    return false;<br>}</pre><p>With the code done, it was time for the actual time testing. I ran it on the koran.txt and I must admit it took quite a while for the summary table to pop up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*FWLIU5ZN4UL4gQ92RQMAVw.png" /><figcaption>where N = 26</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*TC38r9jBLtTwrIjagklfDw.png" /><figcaption>the staff code</figcaption></figure><p>The solid difference of 18 seconds! I increased N from 26 to 1000000 (because why not) and got it down to 0.18 hah.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*fjPTZdZxwBCIPu5QlrRGWQ.png" /><figcaption>N = 1000000</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9d05afc490" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 2020 Pset 4: Recover!]]></title>
            <link>https://medium.com/@dentured/cs50-2020-pset-4-recover-44601624d573?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/44601624d573</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cs50]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 15:58:47 GMT</pubDate>
            <atom:updated>2020-07-16T16:04:56.561Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>tl;dr: walking through a coding problem that implements a program to recover JPEGS from a forensic image</blockquote><p>I was well into week 5 before I realised there’s a whole other problem set in week 4 that I forgot existed, so here I am.</p><p>This problem set went a bit deeper into memory as opposed to the previous problems which were more superficial (?) functions, if I can call them that. The quaint scenario that accompanied this challenge is that I have deleted some photos from my computer, and I have to use the data that’s still written into the memory to recover the nearly 50 JPEGs in card.raw. It was rather thrilling to see the recovered pictures, and while I think this modulated foray into forensic analysis is the closest i’ll get to meeting my hacker-esque alter-ego, the process of writing this code was <em>exhausting</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDoXfaMcPB_Nv0GtmfyD4Q.jpeg" /><figcaption>This was the first result for a Google search of “forensic analysis”.</figcaption></figure><p>I had to refer to the <a href="https://man.cs50.io/">CS50 doc</a> often for this, and had to play around quite a bit to figure out how certain functions were actually used in order to get an idea of how to read memory and pieces the images back. Maybe this was because the past problems have been more logic and arithmetic based? I’m not entirely sure, but oh well.</p><p>As Brian goes through, the pseudocode is as such:</p><pre>1. check if input is valid<br>      2.  else, return 1<br>2. open input file (the memory card)<br>3. repeat until end of card<br>       4. read 512 bytes into a buffer<br>       5. if start of new jpeg<br>               6. if first jpeg<br>                      7. write new jpeg<br>               8. else<br>                      9. close current file<br>                      10. open new file</pre><pre>       11. else<br>               12. if already found jpeg<br>                      13. keep writing to jpeg<br>14. end of memory card<br>15. close all open files</pre><p>Essentially, the program iterates over a copy of the memory card and picks out JPEG signatures. Each time a signature, and hence a JPEG, is found, it opens a new file for writing and start filling that file with bytes from the memory card. Once another signature is found, the current file is closed and a new one is opened and the process repeats. This process is fast tracked by the fact that the program can read 512 bytes of the memory card at a time into a buffer, rather than reading them one by one.</p><p>Unlike runoff or even filter, this code wasn’t as easy to fragment into consecutive blocks. But for the sake of organisation and consolidation, I shall try.</p><p><strong>part 1: check for valid input</strong></p><p>This was just a matter of making sure only one argument was entered into the program. Otherwise, a reminder would be displayed.</p><pre>int main(int argc, char *argv[])<br>{<br>    <strong><em>// Check for invalid input</em></strong><br>    if (argc != 2)<br>    {<br>        printf(&quot;Usage: ./recover image\n&quot;);<br>        return 1;<br>    }</pre><p><strong>part 2: open input file</strong></p><p>The program should be able to take the input file, and assign to it a pointer. <strong>char*</strong> here is a pointer to one char, or to an array of chars, which is argv[1]. The given <strong>FILE*</strong> is simply a kind of structure that holds information about the input file specified, and using the <strong>fopen</strong> function returns the FILE pointer. Where the input file is not working/not being opened, a reminder will be printed as such.</p><pre>    char* input_file = argv[1];<br>    FILE* input_pointer = fopen(input_file, &quot;r&quot;);<br>    if (input_file == NULL)<br>    {<br>        printf(&quot;Unable to open: %s\n&quot;, input_file);<br>        return 1;<br>    }</pre><p><strong>part 3: creating buffers and counters</strong></p><pre><strong>// Create buffer<br></strong>    unsigned char buffer[block_size];</pre><pre><strong>// File counter, initialise<br></strong>    int image_counter = 0;<br>    FILE *output_pointer = NULL;</pre><pre><strong>// Check if JPEG is found<br></strong>    int jpg_has_alr_been_found = 0; //False </pre><p><strong>part 4: read through file</strong></p><p>Here, the program has to read through the whole block, and repeat for all files till there are no blocks left. Helpful definitions were given here, like <strong>fread</strong>, <strong>sprintf</strong> and bitwise arithmetic, which is a handy way of isolating and recognising the four telltale beginning bytes of a typical JPEG file: 0xff, 0xd8, 0xff and anything ranging from 0xe0 to 0xef.</p><p>After reading through the block, if such a signature exists, the program should close current picture being read so as to read the new incoming image. If not, it can continue to write on the file being read.</p><p>Before that, the file naming and counter should be nested within the inner loop. The file name consists of 8 characters (“001.jpg” + null terminator “\0” to symbolise the end of a string). The output pointer is set to null, and the counter is updated here as well.</p><p>Just like fread, fwrite is written in a (data, size, number, inptr) format. For data, I realised that buffer alone didn’t seem to work, and “&amp;buffer” was needed to specify the address where the data being read should be stored. <strong>inptr</strong> is the file from which that data is being read from, which refers to both the input and output pointer files respectively.</p><pre><strong><em>//Read through the whole block, repeat for all files</em></strong><br>    while (fread(&amp;buffer, block_size, 1, input_pointer) == 1)<br>    {<br>        <strong><em>//if start of new JPEG</em></strong><br>        if (buffer[0] == 0xff &amp;&amp; buffer[1] == 0xd8 &amp;&amp; buffer[2] == 0xff &amp;&amp; (buffer[3] &amp; 0xf0) == 0xe0)<br>        {<br>            <strong><em>//if JPEG has been found</em></strong><br>            if (jpg_has_alr_been_found == 1)<br>            {<br>                <strong><em>// Start of an image has been found, so close current image</em></strong><br>                fclose(output_pointer);<br>            }</pre><pre>            <strong><em>//if first JPEG, create a new first file and write in it</em></strong><br>            else<br>            {<br>                <strong><em>//new JPEG discovered and we can write on file</em></strong><br>                jpg_has_alr_been_found = 1;<br>            }</pre><pre>            char filename[8];<br>            sprintf(filename, &quot;%03i.jpg&quot;, image_counter);<br>            output_pointer = fopen(filename, &quot;w&quot;);<br>            image_counter++;<br>        }</pre><pre>        if (jpg_has_alr_been_found == 1)<strong><em>//once new JPEGS are found</em></strong><br>        {<br>            <strong>//copy over the blocks from buffer into new file</strong><br>            fwrite(&amp;buffer, block_size, 1, output_pointer);<br>        }<br>    }</pre><p><strong>part 5: closing the files</strong></p><p>This was pretty straightforward — just close the files when they’re no longer in use, and return 0.</p><pre>    if (output_pointer == NULL)<br>    {<br>        fclose(output_pointer);<br>    }</pre><pre>    if (input_pointer == NULL)<br>    {<br>        fclose(input_pointer);<br>    }</pre><pre>    return 0;</pre><p>This problem set truly was a challenge, and the walkthrough was exceptionally helpful in explaining the new functions, though admittedly I refrained from using <strong>malloc</strong> and <strong>uint8_t</strong> as I didn’t feel particularly confident in my understanding or usage of them. I kept getting segmentation faults so I just decided to use what I knew.</p><p>I’ll go back and review pointers again, and maybe try this pset again in a few weeks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44601624d573" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 2020 Pset 4: Filter(less)]]></title>
            <link>https://medium.com/@dentured/cs50-2020-pset-4-filter-less-8497211d0d3?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8497211d0d3</guid>
            <category><![CDATA[cs50]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Sat, 11 Jul 2020 16:31:59 GMT</pubDate>
            <atom:updated>2020-07-11T16:48:19.491Z</atom:updated>
            <content:encoded><![CDATA[<h3>CS50 2020 Pset 4: Filter(less), finally</h3><blockquote>tl;dr: walking through a coding problem which entails making a bunch of filters by manipulating pixels</blockquote><p>I just read through the filter (less) problem set for Week 4, and suffice to say, I might have to read it a few times more just to even remotely get some idea as to how to start this code.</p><p>So far, it seems to be different manipulations and permutations of red, green and blue values. I’ll try writing some pseudocode and come back here.</p><p><strong>part 1: summary</strong></p><ul><li><em>bmp.h</em></li></ul><p>Stores information about bitmap images and the structs needed to complete the assignment.</p><ul><li><em>filters.c</em></li></ul><p>Programme required to actually run the filters, takes care of the logic of reading the file from memory, powering a function to apply a filter and then writing the new image disk as a brand new file.</p><ul><li><strong><em>helpers.c</em></strong></li></ul><p><strong>The file that contains all of the functions that are going to implement each of the filters.</strong></p><ul><li><em>helpers.h</em></li></ul><p>Header file that declares all the functions that show up in helpers.c, telling you the return type of the functions and what all the types of the arguments of the functions are.</p><ul><li><em>Makefile</em></li></ul><p>Combines all the files into an executable that you can run to apply these filters to images of your very own.</p><p>Hence, each of the 4 functions in <strong>helpers.c</strong> — grayscale, sepia, reflect and blur — take 3 arguments:</p><ol><li>int height</li><li>int width</li><li>array RGBTRIPLE image[height][width] (i.e. the 2nd pixel in a 2D image would be image[0][0])</li></ol><p><strong>part 2: greyscale</strong></p><p>Grey is implemented by an equal portion of red, blue and green. The only condition is that neither of the colours are at the minimum, 0, (forming black) or at the maximum, 255 (forming white), though I didn’t really bother with this because it’s taken as an average.</p><p>As the walkthrough posits, a good algorithm was this is to take the average of rgbtRed, rgbtGreen and rgbtBlue, and set this to be the new value of the greyscale-ed rgbtRed, rgbtGreen and rgbtBlue.</p><ol><li>Iterate through each pixel</li><li>Calculate the average pixel value</li><li>Round to nearest integer, accounting for floats</li><li>Set each colour value to that calculated average pixel value</li></ol><pre>void grayscale(int height, int width, RGBTRIPLE image[height][width])<br>{</pre><pre><strong><em>//iterate through each column of pixel</em></strong></pre><pre>    for (int i = 0; i &lt; height; i++)<br>    {<br><strong><em>        //iterate through each row of pixel in each column</em></strong></pre><pre>        for (int j = 0; j &lt; width; j++)<br>        {<br>            <strong>//get into the 2D array, obtain value of each colour</strong></pre><pre>            int red = image[i][j].rgbtRed;<br>            int blue = image[i][j].rgbtBlue;<br>            int green = image[i][j].rgbtGreen;</pre><pre><strong><em>            //calculate the average value of each pixel, rounded<br></em></strong>            int avg = round(((float)red + (float)blue + (float)green)/3);</pre><pre><strong><em>            //set the calculated average to be the new value of each pixel<br></em></strong>            image[i][j].rgbtRed = image[i][j].rgbtBlue = image[i          [j].rgbtGreen = avg;<br>        }<br>    }</pre><pre>}</pre><p>I had some trouble with the .bmp files because I couldn’t open any of the given images, but it turns out that I needed to specify the location of the infile.bmp:</p><pre>./filter -g images/yard.bmp gyard.bmp</pre><p><strong>part 3: sepia</strong></p><p>Sepia works pretty much the same way, with an added conditional statement to make sure the value stays within 255.</p><ol><li>Iterate through each pixel</li><li>Calculate new sepia pixel value</li><li>Check if value ≤ 255</li><li>If not, set value as 255</li><li>Repeat for each colour</li></ol><pre>void sepia(int height, int width, RGBTRIPLE image[height][width])<br>{<br>    for (int i = 0; i &lt; height; i++)<br>    {<br>        for (int j = 0; j &lt; width; j++)<br>        {<br>            int red = image[i][j].rgbtRed;<br>            int blue = image[i][j].rgbtBlue;<br>            int green = image[i][j].rgbtGreen;</pre><pre><strong><em>            //new sepia value</em></strong></pre><pre>           int sepiaRed = round(0.393 * red + 0.769 * green + 0.189 * blue);</pre><pre>            if (sepiaRed &gt; 255)<br>            {<br>                image[i][j].rgbtRed = 255;<br>            }</pre><pre>            else<br>            {<br>                image[i][j].rgbtRed = sepiaRed;<br>            }</pre><pre>           int sepiaGreen = round(0.349 * red + 0.686 * green + 0.168 * blue);</pre><pre>            if (sepiaGreen &gt; 255)<br>            {<br>                image[i][j].rgbtGreen = 255;<br>            }</pre><pre>            else<br>            {<br>                image[i][j].rgbtGreen = sepiaGreen;<br>            }</pre><pre>           int sepiaBlue = round(0.272 * red + 0.534 * green + 0.131 * blue);</pre><pre>            if (sepiaBlue &gt; 255)<br>            {<br>                image[i][j].rgbtBlue = 255;<br>            }</pre><pre>            else<br>            {<br>                image[i][j].rgbtBlue = sepiaBlue;<br>            }</pre><pre>         }</pre><pre>      }<br>}</pre><p><strong>part 4: reflect</strong></p><p>I was confused by this at first because I kept thinking I had to swap the colours <strong>and</strong> the pixels, which in hindsight makes little sense. Still, the actual reflecting/swapping of the pixels was admittedly, daunting.</p><p>The task here is to swap around the integer elements in the row of the array, which requires using temporary locations to store elements.</p><ol><li>Iterate through each pixel until the midpoint (because the swaps need only occur from one side till the halfway point).</li><li>Store left-hand side elements in a temporary storage</li><li>Swap right half with left (middle pixel remains unchanged if odd-numbered row)</li><li>Reinsert elements in temp storage back into right side</li></ol><p>For example, in an array of 10, swapping the first and last element in the array would look like this:</p><pre>int temp = array[0];<br>array[0] = array[9];<br>array[9] = temp;</pre><p>If the pattern continued, the pairs to be switched would be [0][9], [1][8], [2][7], [3][6], [4][5].</p><pre>int temp = array[i];<br>image[i] = image[total - (i + 1)];<br>image[i][total - (i + 1)] = temp;</pre><p>This also works for odd numbered sets as well:</p><pre><strong><em>//if total 11 elements</em></strong><br>int temp = array[5];<br>image[5] = image[11 - (5 + 1)]; <strong><em>//which would be image[5] = image [5]</em></strong><br>image[11 - (5 + 1)] = temp;</pre><p>Now, in an array of an unspecified number of elements, j, swapping horizontally would be as such:</p><pre>void reflect(int height, int width, RGBTRIPLE image[height][width])<br>{<br>    for (int i = 0; i &lt; height; i++)<br>    {<br>        <strong><em>// iterate through the array until you get to the mid-point</em></strong></pre><pre>        for (int j = 0; j &lt; (width/2); j++)<br>        {</pre><pre>            RGBTRIPLE temp = image[i][j];</pre><pre>            <strong><em>//just like how [0][9]...[4][5], [i] will swap with [total-1-i]</em></strong></pre><pre>            image[i][j] = image[i][width - (j + 1)];<br>            image[i][width - (j + 1)] = temp;</pre><pre>        }<br>    }<br>    return;<br>}</pre><p><strong>part 5: blur</strong></p><p>My first impression of the blur filter was that it was basically greyscale on steroids. Instead of taking the average of red, blue and green of 1 pixel, I have to calculate the average of 9 red values of the 9 pixels in a square, then blue and green similarly. It took me basically three entire days of head-banging and pleas for help on reddit for this part, but I finally have it, thanks to r/cs50 and stack overflow. Can’t believe I thought the blur filter would be the easiest, because in my mind it just seemed to be taking pixels and shifting them around haphazardly, but this was easily the most frustrating moment in CS50 so far (made it so much more rewarding though!!).</p><p>This seemed to be rather verbose code, as there are nine unique situations/pixel types to account for — the 4 corner pixels (teal), the bottom edge pixels (orange), top edge pixels (pink), right edge (green), left edge (yellow) and the middle pixels (red). This separation of pixels allows us to stipulate how many of the surrounding pixels are involved in calculating the average pixel colour value: if it’s a corner pixel, out of the 9 possible, only 4 (including the corner pixel itself) can be accounted for. However, for a middle pixel, there are 9 pixels intact that can be taken.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*6lU6Thk562lkv67SKKt6OA.png" /></figure><p>And then, for each of these pixels, I calculate the average red/blue/green value of the 3/5/8 surrounding pixels (depending on whether the pixel is a corner/edge or middle pixel) + itself.</p><p>An additional caveat was that the blur function had to transpire on a copy of the image array — once the pixels have been blurred, they can’t be factored into the blurring of its neighbouring pixels because the colours have all been mixed up. For this, I had to preserve the original values until I calculated all the neighbouring pixels. This could be done by declaring a temporary array with a copy step at the beginning of the function.</p><p>The pseudocode went something like this:</p><ol><li>Create a temporary array on which the blurring loop occurs</li><li>Iterate through the column and row</li><li>Create integer variables and initialise</li><li>If pixel is a corner pixel -</li><li>If pixel is located on the edges -</li><li>If pixel is in the middle -</li><li>Add to red, blue, green counters</li><li>Find the average colour value and set it to the original array</li></ol><pre>void blur(int height, int width, RGBTRIPLE image[height][width])<br>{</pre><pre><strong><em>//create a temporary image to be blurred<br></em></strong>    RGBTRIPLE temp[height][width];<br>    for (int i = 0; i &lt; height; i++)<br>    {<br>        for (int j = 0; j &lt; width; j++)<br>        {<br>            temp[i][j] = image[i][j];<br>        }<br>    }</pre><pre>    for (int i = 0; i &lt; height; i++)<br>    {<br>        for (int j = 0; j &lt; width; j++)<br>        {<br>            int sum_blue;<br>            int sum_green;<br>            int sum_red;<br>            float counter;</pre><pre>            sum_blue = sum_green = sum_red = counter = 0;</pre><pre><strong><em>//CORNERS</em></strong></pre><pre><strong><em>            //corner pixel on bottom right<br></em></strong>            if (i &gt;= 0 &amp;&amp; j &gt;= 0)<br>            {<br>                sum_red += temp[i][j].rgbtRed;<br>                sum_green += temp[i][j].rgbtGreen;<br>                sum_blue += temp[i][j].rgbtBlue;<br>                counter++;<br>            }<br><strong><em>            //corner pixel on bottom left<br></em></strong>            if (i &gt;= 0 &amp;&amp; j - 1 &gt;= 0)<br>            {<br>                sum_red += temp[i][j-1].rgbtRed;<br>                sum_green += temp[i][j-1].rgbtGreen;<br>                sum_blue += temp[i][j-1].rgbtBlue;<br>                counter++;<br>            }<br><strong><em>            //corner pixel on top left<br></em></strong>            if (i - 1 &gt;= 0 &amp;&amp; j &gt;= 0)<br>            {<br>                sum_red += temp[i-1][j].rgbtRed;<br>                sum_green += temp[i-1][j].rgbtGreen;<br>                sum_blue += temp[i-1][j].rgbtBlue;<br>                counter++;<br>            }<br><strong><em>            //corner pixel on top right<br></em></strong>            if (i - 1 &gt;= 0 &amp;&amp; j - 1 &gt;= 0)<br>            {<br>                sum_red += temp[i-1][j-1].rgbtRed;<br>                sum_green += temp[i-1][j-1].rgbtGreen;<br>                sum_blue += temp[i-1][j-1].rgbtBlue;<br>                counter++;<br>            }</pre><pre><strong><em>//FOUR EDGES</em></strong></pre><pre><strong><em>            //pixels on bottom edge<br></em></strong>            if ((i &gt;= 0 &amp;&amp; j + 1 &gt;= 0) &amp;&amp; (i &gt;= 0 &amp;&amp; j + 1 &lt; width))<br>            {<br>                sum_red += temp[i][j+1].rgbtRed;<br>                sum_green += temp[i][j+1].rgbtGreen;<br>                sum_blue += temp[i][j+1].rgbtBlue;<br>                counter++;<br>            }</pre><pre><strong><em>            //pixels on top edge<br></em></strong>            if ((i - 1 &gt;= 0 &amp;&amp; j + 1 &gt;= 0) &amp;&amp; (i - 1 &gt;= 0 &amp;&amp; j + 1 &lt; width))<br>            {<br>                sum_red += temp[i-1][j+1].rgbtRed;<br>                sum_green += temp[i-1][j+1].rgbtGreen;<br>                sum_blue += temp[i-1][j+1].rgbtBlue;<br>                counter++;<br>            }<br><strong><em>            //pixels on left edge<br></em></strong>            if ((i + 1 &gt;= 0 &amp;&amp; j &gt;= 0) &amp;&amp; (i + 1 &lt; height &amp;&amp; j &gt;= 0))<br>            {<br>                sum_red += temp[i+1][j].rgbtRed;<br>                sum_green += temp[i+1][j].rgbtGreen;<br>                sum_blue += temp[i+1][j].rgbtBlue;<br>                counter++;<br>            }<br><strong><em>            //pixels on right edge<br></em></strong>            if ((i + 1 &gt;= 0 &amp;&amp; j - 1 &gt;= 0) &amp;&amp; (i + 1 &lt; height &amp;&amp; j - 1 &gt;= 0))<br>            {<br>                sum_red += temp[i+1][j-1].rgbtRed;<br>                sum_green += temp[i+1][j-1].rgbtGreen;<br>                sum_blue += temp[i+1][j-1].rgbtBlue;<br>                counter++;<br>            }</pre><pre><strong><em>//MIDDLE PIXELS</em></strong></pre><pre><strong><em>            //middle pixels<br></em></strong>            if ((i + 1 &gt;= 0 &amp;&amp; j + 1 &gt;= 0) &amp;&amp; (i + 1 &lt; height &amp;&amp; j + 1 &lt; width))<br>            {<br>                sum_red += temp[i+1][j+1].rgbtRed;<br>                sum_green += temp[i+1][j+1].rgbtGreen;<br>                sum_blue += temp[i+1][j+1].rgbtBlue;<br>                counter++;<br>            }</pre><pre>            <strong><em>//find average colour value</em></strong><br>            image[i][j].rgbtRed = round(sum_red / counter);<br>            image[i][j].rgbtGreen = round(sum_green / counter);<br>            image[i][j].rgbtBlue = round(sum_blue / counter);<br>        }<br>    }</pre><pre>return;<br>}</pre><p>Writing down the code for this was painstakingly long, and surely there had to be a more efficient way to do it.</p><p>While there are still 9 scenarios, a more concise method would be to simply check if the surrounding pixels exist, and if so, to add the colours’ value to the RGB variables and increment the counter of pixels. The last few lines of the code would just be to take the total colour value of the pixels and to divide it by the counted number of pixels to get the average.</p><p>After declaring the temporary array and iterating through i and j, I can choose to iterate through the row and column again with <strong>w </strong>and <strong>h, </strong>which runs from -1 to +1. If there is no pixel to the right/left/top/bottom of the pixel in question, the function skips that pixel via the ‘continue<em>’</em> function.</p><pre><strong><em>            //iterate through the column, from -1 to +1<br></em></strong>            for (int h = -1; h &lt; 2; h++)<br>            {<br>                <strong><em>//iterate similarly through rows</em></strong><br>                for (int w = -1; w &lt; 2; w++)<br>                {<br>                    <strong><em>//if pixel is outside the image (column)</em></strong><br>                    if (i + h &lt; 0 || i + h &gt; (height - 1))<br>                    {<br>                        continue; <strong><em>//skip</em></strong><br>                    }</pre><pre><strong><em>                    //if pixel is outside the image (row)<br>                    </em></strong>if (j + w  &lt; 0 || j + w &gt; (width - 1))<br>                    {<br>                        continue; <strong><em>//skip</em></strong><br>                    }</pre><pre><strong><em>                    //sum up the values of all the pixels</em></strong></pre><pre>                    sum_blue += image[i + h][j + w].rgbtBlue;<br>                    sum_red += image[i + h][j + w].rgbtRed;<br>                    sum_green += image[i + h][j + w].rgbtGreen;<br>                    counter++;<br>                }<br>            }</pre><p>End this off with the same counter and set the values onto the original array!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuePDoAJWNQc50xyLEMFyw.jpeg" /><figcaption>blurred!</figcaption></figure><p>This was a tough pset to finish, with the inevitable mid-course slump that hit me for a solid few days. At one point I tried to visualise myself as a pixel, not sure if it helped, but i’m just glad I got to see the little green smiley faces in the terminal window when this was done. And of course, consolidating my thoughts helped me to review my code and try to make it better, so that was fun.</p><p>I’ll give myself a break before I go onto week 5, but till then, lesson learnt — do not take Instagram filters for granted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8497211d0d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CS50 2020 Pset 3: Of Runoffs and Politics]]></title>
            <link>https://medium.com/@dentured/cs50-pset-3-of-runoffs-and-politics-6946862dc7a7?source=rss-25cad916b48e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6946862dc7a7</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cs50]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[SF]]></dc:creator>
            <pubDate>Tue, 07 Jul 2020 08:58:51 GMT</pubDate>
            <atom:updated>2020-07-11T16:42:48.754Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>tl;dr: walking through a coding problem set which runs a runoff election using C</blockquote><p>I was pleasantly surprised when I went through the lecture and shorts of week 3 to find that it was about elections and politics. Given the local political climate here, with the 2020 general elections (plurality!) coming up, it felt slightly more invigorating switching up the names to reflect those of local politicians and running some of my own estimates to feel like a ballot-counter.</p><p>It took me about two days, with numerous questions to comsci friends/reddit/overflow to come up with a coherent code for Runoff, and when I finally ran it again, there was the final fatal compilation error. I’ve been stuck at this for about 3 days now, and in the midst of a frustrated rampage I thought it might help to write down my entire code again from scratch, and explain it to myself as I go. I figured, why not do it on a public space then. It’ll help me learn, and hopefully someone else too.</p><p><strong>part 1: summary</strong></p><p>As opposed to plurality.c, runoff.c requires a winner to have &gt; 50% of votes and embodies a ranking system. This involves going through each voter, and then going over each of their ranked candidates, and eliminating the lowest cumulative over and over again till the winners are printed — either all, some, one, or none.</p><p><strong>part 2: explanation of given code</strong></p><pre>#include &lt;cs50.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;string.h&gt;</pre><pre><strong><em>// Max voters and candidates</em><br></strong>#define MAX_VOTERS 100<br>#define MAX_CANDIDATES 9</pre><pre><strong><em>// preferences[i][j] is jth preference for voter i</em><br></strong>int preferences[MAX_VOTERS][MAX_CANDIDATES];</pre><p>This just includes the usual headers and sets the boundaries for voters and candidates. The last part is the provision of a matrix/2-dimensional array of preferences[voter][rank]. As you go, it’ll be akin to adding [i] to the 2D array because it stands for the [i]th voted candidate in the array.</p><pre><strong><em>// Candidates have name, vote count, eliminated status<br></em></strong>typedef struct<br>{<br>    string name;<br>    int votes;<br>    bool eliminated;<br>}<br>candidate;</pre><pre><strong><em>// Array of candidates<br></em></strong>candidate candidates[MAX_CANDIDATES];</pre><pre><strong><em>// Numbers of voters and candidates<br></em></strong>int voter_count;<br>int candidate_count;</pre><pre><strong><em>// Function prototypes<br></em></strong>bool vote(int voter, int rank, string name);<br>void tabulate(void);<br>bool print_winner(void);<br>int find_min(void);<br>bool is_tie(int min);<br>void eliminate(int min);</pre><p>The typedef function written defines 3 properties — the string of names, the integer count of votes and the true/false option of whether a candidate is eliminated. Next is the definition of an array, followed by two more integer variables of voter_count and candidate_count and lastly, a whole bunch of functions that we have to implement later on.</p><pre>int main(int argc, string argv[])<br>{<br>    <strong><em>// Check for invalid usage </em></strong><br>    if (argc &lt; 2)<br>    {<br>        printf(&quot;Usage: runoff [candidate ...]\n&quot;);<br>        return 1;<br>    }</pre><p>so this makes sure there’s 2 arguments or more; otherwise, it’ll return 1 and repeat the programme.</p><pre><strong><em>// Populate array of candidates - argc<br></em></strong>    candidate_count = argc - 1;<br>    if (candidate_count &gt; MAX_CANDIDATES)<br>    {<br>        printf(&quot;Maximum number of candidates is %i\n&quot;, MAX_CANDIDATES);<br>        return 2;<br>    }<br>    for (int i = 0; i &lt; candidate_count; i++)<br>    {<br>        candidates[i].name = argv[i + 1];<br>        candidates[i].votes = 0;<br>        candidates[i].eliminated = false;<br>    }</pre><pre>voter_count = get_int(&quot;Number of voters: &quot;);<br>    if (voter_count &gt; MAX_VOTERS)<br>    {<br>        printf(&quot;Maximum number of voters is %i\n&quot;, MAX_VOTERS);<br>        return 3;<br>    }</pre><p>candidate_count is argument count minus 1 as the first argument is the programme itself. If the number of candidates exceeds the max candidate count stipulated above, the programme returns 2 and repeats the programme.</p><p>Then, we iterate through the candidate_count, such as the argument vector increases with each unique candidate’s name. The vote count is initialised to zero, and none of them are eliminated thus far so eliminated = false.</p><p>Similarly, if voter_count exceeds max voters, the programme prints a reminder and returns 3.</p><pre><strong><em>// Keep querying for votes</em></strong><br>    for (int i = 0; i &lt; voter_count; i++)<br>    {</pre><pre><strong><em>// Query for each rank</em></strong><br>        for (int j = 0; j &lt; candidate_count; j++)<br>        {<br>            string name = get_string(&quot;Rank %i: &quot;, j + 1);</pre><p>Again, this is a process of iterating and collecting the candidates’ names from the user.</p><p>So the basic background has been set for the programme, and here the crux of it begins. There’s a loop embedded within an outer loop — for each voter, you iterate through each rank and each candidate in that rank, and then record it. If the vote is invalid (that is, it does not pass the arguments of i, j and name, the programme will print “invalid” and return 4.</p><pre><strong><em>// Record vote, unless it&#39;s invalid </em></strong><em>--&gt; go to</em><strong><em> part 3:vote</em></strong><br>            if (!vote(i, j, name))<br>            {<br>                printf(&quot;Invalid vote.\n&quot;);<br>                return 4;<br>            }<br>        }</pre><pre>printf(&quot;\n&quot;);<br>    }</pre><pre><strong><em>// Keep holding runoffs until winner exists </em></strong><em>--&gt; go to</em><strong><em> part 4:tabulate<br></em></strong>    while (true)<br>    {<br>        // Calculate votes given remaining candidates<br>        tabulate();</pre><pre><strong><em>// Check if election has been won </em></strong><em>--&gt; go to</em><strong><em> part 5:print winner<br></em></strong>        bool won = print_winner();<br>        if (won)<br>        {<br>            break;<br>        }</pre><pre><strong><em>// Eliminate last-place candidates </em></strong><em>--&gt; go to</em><strong><em> part 6:find_min </em></strong><em>and</em><strong><em> part 7:is_tie<br></em></strong>        int min = find_min();<br>        bool tie = is_tie(min);</pre><pre><strong><em>// If tie, everyone wins<br></em></strong>        if (tie)<br>        {<br>            for (int i = 0; i &lt; candidate_count; i++)<br>            {<br>                if (!candidates[i].eliminated)<br>                {<br>                    printf(&quot;%s\n&quot;, candidates[i].name);<br>                }<br>            }<br>            break;<br>        }</pre><pre><strong><em>// Eliminate anyone with minimum number of votes </em></strong><em>--&gt; go to</em><strong><em> part 8:eliminate<br></em></strong>        eliminate(min);</pre><pre><strong><em>// Reset vote counts back to zero<br></em></strong>        for (int i = 0; i &lt; candidate_count; i++)<br>        {<br>            candidates[i].votes = 0;<br>        }<br>    }<br>    return 0;<br>}</pre><p><strong>part 3: vote</strong></p><p>This function checks the validity of a vote and stores it in the respective location of the array such that the candidate (who was voted) will see an increase in their vote count.</p><p>The reasoning / pseudocode behind this was as follows:</p><ol><li>Iterate through candidates</li><li>Check for name in existing candidate</li><li>Compare the two strings and if they are the same, return 0 meaning true</li><li>If name matches, add vote choice to the correct location in the array: pass in the index of candidate with the matched name, [i] to this 2D array as it represents the<br>[i]th voted candidate in the array</li><li>When preference array is updated, return true inside the loop</li><li>Else return false outside of the loop to stop</li></ol><pre><strong><em>// Record preference if vote is valid</em></strong><br>bool vote(int voter, int rank, string name)<br>{</pre><pre><strong><em>//iterate</em></strong></pre><pre>    bool exist = false;<br>    for (int i = 0; i &lt; candidate_count; i++)<br>    {</pre><pre><strong><em>//compare </em></strong></pre><pre>        if (strcmp(name, candidates[i].name) == 0)<br>        {</pre><pre><strong><em>//add vote to location in array</em></strong><br>            preferences[voter][rank] = i;<br>            exist = true;<br>            break;<br>        }<br>    }</pre><pre>return exist;</pre><p><strong>part 4: tabulate</strong></p><p>Tabulate votes for non-eliminated candidates. This means that we have to go through the array and for each of the positions, we will find the index of the candidate, go to the candidates array and increment their vote count.</p><ol><li>Iterate through voters, voter_count</li><li>For each voter, iterate through their votes and candidate ranking</li><li>Check through each vote in voter’s rank 1 to see if the candidate has been eliminated</li><li>If not, add to the ranked first candidate’s vote count</li><li>If eliminated, move to rank 2</li><li>Check if the candidate in rank 2 has been eliminated</li><li>If not, add to the ranked second candidate’s vote count</li></ol><pre>void tabulate(void)<br>{<br>    <strong><em>// iterate through votes</em></strong></pre><pre>    for (int i = 0; i &lt; voter_count; i++) <br>    {<br>    <br>    <strong><em>// iterate through ranks</em></strong></pre><pre><strong><em>        </em></strong>for (int j = 0; j &lt; candidate_count; j++)<br>        {</pre><pre><strong><em>    // has the candidate been eliminated?</em></strong></pre><pre>            if (candidates[preferences[i][j]].eliminated == false)<br>            {<br>                candidates[preferences[i][j]].votes++;<br>            }<br>        }<br>    }<br>    return;<br>}</pre><p>but! the tabulate function did not work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*wrMPQ6jiGHMkmdDBpgoXjg.png" /></figure><p>Was kind of stuck before I realised that I hadn’t stipulated the number of rankings — that is, told the programme to stop after the second rank. We don’t need to go past the second rank for each voter, so this was easily remedied by incorporating a ‘break’ <em>inside</em> the inner loop.</p><pre>void tabulate(void)<br>{<br>     <br>    for (int i = 0; i &lt; voter_count; i++) <br>    {<br>        for (int j = 0; j &lt; candidate_count; j++)<br>        {<br>            if (candidates[preferences[i][j]].eliminated == false)<br>            {<br>                candidates[preferences[i][j]].votes++;</pre><pre>                <strong>break</strong>;<br>            }<br>        }<br>    }<br>    return;<br>}</pre><p><strong>part 5: print winner</strong></p><p>This entailed checking and printing out a winner who had more than 50% of the votes. It was relatively straight forward, with a bit of simple fraction.</p><ol><li>Iterate through candidates</li><li>Check that each candidate’s total votes is more than half the total votes</li><li>If true, then that candidate is the winner</li><li>Print candidate’s name, return true</li><li>If none of the candidates have more than half, return false</li></ol><pre>bool print_winner(void)</pre><pre>{<br>    for (int i = 0; i &lt; candidate_count; i++)<br>    {</pre><pre>    <strong><em>// check if candidate&#39;s votes are more than half</em></strong></pre><pre>        if (candidates[i].votes &gt; voter_count / 2)<br>        {<br>            printf(&quot;%s\n&quot;, candidates[i].name);<br>            return true;<br>        }<br>     <br>    }<br>    return false;<br>}</pre><p><strong>part 6: find_min</strong></p><p>Here, we find the smallest number of votes any of the remaining candidates have, so as to eliminate the candidate in the last place. I didn’t know any dynamic way to incorporate the min tool and was stumped for a while, resorting to various arithmetic nonsense but the first google search kind of effectively gave me my answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nX2mqLdtYJWCxvoLv5eCeA.png" /></figure><p>This basically reminded me what the whole of week 3 was about, which was about sorting and patterns. Effectively, finding the max or min of any array would just require you to set one element in that array as a starting point, and continuously compare every other element to that one element (insertion sort!) till you determine which is the lowest element.</p><ol><li>Make a new variable called min_vote and set/equate this to a single element, such as the first candidate’s vote</li><li>Iterate through each candidate</li><li>Check if candidate has been eliminated</li><li>For each non-eliminated candidate, check whether that candidate’s vote is less than the first candidate’s vote</li><li>If true, set that new candidate’s vote as the new minimum, min_vote.</li><li>Repeat the cycle through each candidate, and finally</li><li>Return min_vote</li></ol><pre>int find_min(void)</pre><pre>{<br>    <strong><em>//create new variable, set it as the first candidate&#39;s vote</em></strong><br>    <br>    int min_vote = candidates[0].votes;</pre><pre>   <strong><em> //iterate</em></strong><br>    <br>    for (int i = 1; i &lt; candidate_count; i++)<br>    {<br>    <br><strong><em>     // if candidate is not eliminated and &lt; min_vote, make them the new min-vote</em></strong></pre><pre>        if (candidates[i].eliminated == false &amp;&amp; min_vote &gt; candidates[i].votes)<br>        {<br>            min_vote = candidates[i].votes;<br>        }</pre><pre>     }<br>     return min_vote;<br>}</pre><p><strong>part 7: is_tie</strong></p><p>This is a continuation of part 6. There, we eliminated the sole last place candidate. Here, we eliminate the candidates who, if any, are tied for the last place because they have the same minimum number of votes. Hence, the given: <strong>bool tie = is_tie(min).</strong></p><p>The programme should return true if the election is tied between all candidates, and false otherwise. A simple way to get this would be to make the function return true if there is a candidate who simply has more than the minimum number of votes.</p><ol><li>Iterate through each candidate</li><li>If a candidate who is still running has more than the minimum vote count, it logically follows that the election cannot be a tie.</li><li>Return false</li></ol><pre>bool is_tie(int min_vote)</pre><pre>{<br>    for (int i = 0; i &lt; candidate_count; i++)<br>    {<br>        if (candidates[i].eliminated == false &amp;&amp; candidates[i].votes &gt;  min_vote)<br>        {<br>            return false;<br>        }<br>    }<br>    return true;<br>}</pre><p><strong>part 8: eliminate</strong></p><p>To eliminate the candidate(s) in the last place, we just need to find the candidate with min_vote and eliminate them, if they haven’t already been.</p><ol><li>Iterate through each candidate</li><li>If candidate has min_vote votes and remains in the running, eliminate them.</li></ol><pre>void eliminate(int min_vote)</pre><pre>{<br>    for (int i = 0; i &lt; candidate_count; i++)<br>    {<br>        if (candidates[i].eliminated == false &amp;&amp; candidates[i].votes == min_vote)<br>        {<br>            candidates[i].eliminated = true;<br>        }<br>    }<br>    return;<br>}</pre><p>It really helped that the pset was broken down into different discrete functions, and penning down my thought process as I went helped me figure out any errors or inconsistencies. Consolidating it all like this was particularly conducive for me as well, and gave me that bit of retrospective thinking to fiddle around to have a more cleaner and stylistic solution.</p><p>Ending this with a thanks to Dr Malan and a reminder to myself to maybe come back to this at a later date after the election statistics/results come out so that I can play around with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6946862dc7a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>