amethyst/assets/indices/contentIndex.json

440 lines
196 KiB
JSON
Raw Normal View History

{
"/": {
"title": "💜 Welcome to Amethyst!",
2023-01-05 16:48:50 -05:00
"content": "\n## What is Amethyst?\nAmethyst is a free [Obsidian Publish](https://obsidian.md/publish) alternative that is derived from two existing projects, [Quartz](https://quartz.jzhao.xyz/) and [Hugo Book](https://github.com/alex-shpak/hugo-book).\n\nThe purpose of Amethyst is to provide a space to publish more structured notes created in Obsidian that may not fit in the [digital garden](https://joelhooks.com/digital-garden/) archetype that is well-supported by existing projects.\n\nAmethyst was primarily created as a theme for my [course notes](https://notes.bencuan.me).\n\n## Get Started\n\u003e 📚 Step 1: [Setup your own Amethyst instance](setup/setup.md)\n\n\u003e ✏️ Step 2: [Editing Notes in Amethyst](setup/editing.md)\n\n\u003e 🔗 Step 3: [How to setup your Obsidian Vault to work with Amethyst](setup/obsidian.md)\n\n\u003e 👀 Step 4: [Preview Changes](setup/preview%20changes.md)\n\n\u003e 🌍 Step 5: [Hosting Amethyst online!](setup/hosting.md)\n\n\u003e 🎨 Step 6: [Customizing Amethyst](setup/config.md)\n\nReturning user? Here's how to [[setup/updating|update]] your existing Amethyst instance.\n\nHere's a list of all [setup-related notes](/tags/setup), which are also accessible via the sidebar menu under the \"Getting Started\" section.\n\n### Troubleshooting\n- 🚧 [Troubleshooting and FAQ](setup/troubleshooting.md)\n- 🐛 [Submit an Issue](https://github.com/64bitpandas/amethyst/issues)\n- 👀 [Contact me](https://bencuan.me/contact)\n",
"lastmodified": "2023-01-05T21:05:01.97004604Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/": {
"title": "Welcome to CS61B!",
"content": "\n# Welcome\n\n## Welcome to 64bitpanda's CS61B Guide!\n\n(If you are looking at this in github, go to [cs61b.bencuan.me](https://cs61b.bencuan.me) for a much better experience!)\n\nThis is a **non-comprehensive** guide to data structures written with an intention to supplement learning and reviewing of Berkeley's [CS61B](https://inst.eecs.berkeley.edu/\\~cs61b) material. Main topics include:\n\n* Object oriented programming basics\n* Abstract data types\n* Asymptotics and runtime analysis\n* Sorting algorithms\n* Search algorithms\n* And some more miscellaneous topics thrown in!\n\nThis guide is written to be as easy to follow and digestible as possible😀I've included lots of diagrams, practice problems, and more intuitive explanations instead of the more straightforward approach most textbooks use. **This isn't a replacement for lectures and other course content.** You probably need to look at those first, and come here if something isn't sticking!\n\n### The 61B Concept Map\n\n![](\u003cimg/assets/image (6).png\u003e)\n\n\n\n## Who is this for?\n\nMostly me; making unnecessarily detailed guides is my goto method of making sure I understand everything😁But you are welcome to use it as well for reviewing for 61B exams, touching up on data structures knowledge, or whatever you want!\n\n**Basic knowledge gained from** [**CS61A**](https://cs61a.org/) **or equivalent is assumed.** [Click here](https://cs61a.bencuan.me) for my notes for that!\n\n## How to use this guide\n\nAgain, I will emphasize that this **isn't a textbook.** While I try to be as comprehensive as possible, I'm sure I missed plenty of important concepts or assume you know others. I don't have an army of peer reviewers and guinea pigs to test-read the thing, so it's also not guaranteed that everything is 100% accurate. Please [open an issue](https://github.com/64bitpandas/cs61b-notes/issues) if you think something's wrong!\n\n{% hint style=\"warning\" %}\nFor more difficult topics, I'll put a warning like this at the top of the page with links to prerequisites or supporting topics so that you won't feel completely lost 😉\n{% endhint %}\n\nThere are also plenty of practice problems to try out! Here's an non-exhaustive list of pages with those if you are mostly interested in them and not the conceptual content.\n\n* [Access Control](oop/access-control.md#practice)\n* [Dynamic Method Selection](oop/dynamic-method-selection.md)\n* [Generic Types](oop/generics.md#generic-subtypes)\n* [Asymptotics Practice](asymptotics/asymptotics-practice.md)\n\n\n\n## How to contribute\n\nFork the [GitHub repository](https://github.com/64bitpandas/cs61b-notes) and create a pull request. All contributions are welcome! Pages are formatted in [Markdown syntax](https://docsimg.com/editing-content/markdown). Please **edit existing pages only** unless you have [created an issue](https://github.com/64bitpandas/cs61b-notes/issues) and I have gotten back to you about making a new page. Thanks 😄\n\nThe pages that could be most improved (in no particular order) are [Union Find (Disjoint Sets)](abstract-data-types/union-find-disjoint-sets.md), [Stacks and Queues](abstract-data-types/collections/stacks-and-queues.md), [Linked Lists](abstract-data-types/collections/linked-lists.md), [Sets](abstract-data-types/collections/sets.md), [Sorting](sorting/sorting-basics.md), [Searching](algorithms/searching/), [Binary Search](algorithms/searching/binary-search.md), [Shortest Paths](algorithms/shortest-paths/), and [Exceptions](misc-topics/exceptions.md). Feel free to add whatever content you like (explanations, examples, practice problems, memes...) to these!\n\nAdditionally, there are plenty of topics (Regex, Testing, Files/Scanners, Ranges, GUI just to name a few) that aren't currently covered in this guide. If you want to add one of these topics, please create an issue first but it will almost certainly be approved.\n\n### Credits\n\n* [Ben Cuan (64bitpandas)](https://github.com/64bitpandas)\n* [Arin Chang](https://github.com/arinchang)\n\n\n\n![[classes/cs61b/SUMMARY]]
"lastmodified": "2023-01-05T06:38:49.27788034Z",
"tags": null
},
"/cs61b/SUMMARY": {
"title": "CS61B",
"content": "\n# Table of contents\n\n* [Welcome](CS61B%20Index.md)\n\n## Object Oriented Programming \u003ca id=\"oop\"\u003e\u003c/a\u003e\n\n* [Inheritance](oop/inheritance.md)\n* [Access Control](oop/access-control.md)\n* [Dynamic Method Selection](oop/dynamic-method-selection.md)\n* [Java Objects](oop/objects.md)\n* [Generic Types](oop/generics.md)\n\n## Asymptotics\n\n* [Asymptotic Analysis Basics](asymptotics/asymptotics.md)\n* [Amortization](asymptotics/amortization.md)\n* [Asymptotics Practice](asymptotics/asymptotics-practice.md)\n\n## Abstract Data Types\n\n* [Collections](abstract-data-types/collections/README.md)\n * [Arrays](abstract-data-types/collections/arrays.md)\n * [Linked Lists](abstract-data-types/collections/linked-lists.md)\n * [Sets](abstract-data-types/collections/sets.md)\n * [Stacks and Queues](abstract-data-types/collections/stacks-and-queues.md)\n* [Binary Trees](abstract-data-types/binary-trees/README.md)\n * [Heaps](abstract-data-types/binary-trees/heaps.md)\n * [Balanced BSTs](abstract-data-types/binary-trees/balanced-search-structures.md)\n * [Tries](abstract-data-types/binary-trees/tries.md)\n* [Graphs](abstract-data-types/graphs.md)\n* [Hashing and Hash Tables](abstract-data-types/hashing.md)\n* [Union Find \\(Disjoint Sets\\)](abstract-data-types/union-find-disjoint-sets.md)\n* [Comparables and Comparators](abstract-data-types/comparables-and-comparators.md)\n\n## Sorting\n\n* [Sorting](sorting/sorting-basics.md)\n\n## Algorithms\n\n* [Minimax Algorithm](algorithms/minimax.md)\n* [Searching](algorithms/searching/README.md)\n * [Binary Search](algorithms/searching/binary-search.md)\n * [Depth First Search \\(DFS\\)](algorithms/searching/depth-first-search-dfs.md)\n * [Breadth First Search \\(BFS\\)](algorithms/searching/breadth-first-search-bfs.md)\n* [Shortest Paths](algorithms/shortest-paths/README.md)\n * [Dijkstra's Algorithm](algorithms/shortest-paths/dijkstras-algorithm.md)\n * [A\\* Search](algorithms/shortest-paths/a-search.md)\n* [Minimum Spanning Trees](algorithms/minimum-spanning-trees/README.md)\n * [Prim's Algorithm](algorithms/minimum-spanning-trees/prims-algorithm.md)\n * [Kruskal's Algorithm](algorithms/minimum-spanning-trees/kruskals-algorithm.md)\n\n## Misc Topics\n\n* [Modular Arithmetic and Bit Manipulation](misc-topics/modular-arithmetic.md)\n* [Exceptions](misc-topics/exceptions.md)\n* [More Resources](misc-topics/more-resources.md)\n\n",
"lastmodified": "2023-01-03T02:02:19.144391466Z",
"tags": null
},
"/cs61b/abstract-data-types/binary-trees/README": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Binary Trees\n\n{% hint style=\"success\" %}\n\"The most important concept in computer science\" - Josh Hug\n{% endhint %}\n\n## Humble Origins\n\nLinked lists are great, but we can do better! Let's try **rearranging the pointers** in an interesting way.\n\nInstead of starting at one end of the list, let's set our first pointer at the **middle** of the list!\n\n![](\u003c../../img/assets/image (69).png\u003e)\n\nNow, let's make new pointers going to the **center** of each **sublist** on the left and right of the center.\n\n![](\u003c../../img/assets/image (70).png\u003e)\n\nLet's do it again!\n\n![](\u003c../../img/assets/image (71).png\u003e)\n\nWould ya look at that, we've got a **tree**! 🌲\n\n![🌲🌲🌲🌲🌲](\u003c../../img/assets/image (73).png\u003e)\n\n## Types of Trees\n\nRight now, we can determine some properties that all trees have.\n\n* All trees have a **root node**.\n* All nodes can point to **child nodes.** Or, if they don't have any children, they are **leaves.**\n\nWe can add more and more constraints to our tree to make them more useful!\n\nFirst, let's add the constraint that **node can only have 2 or fewer children** to create a **binary tree.**\n\nThen, let's **ensure our tree is sorted** to create a **binary search tree.** A tree is sorted if it has these properties:\n\n* Every value in the **left subtree** of a node is **less than** the node's value.\n* Every value in the **right subtree** of a node is **greater than** the node's value.\n* Values are **transitive** - there are **no duplicate values**.\n* The tree is **complete** - it is possible to **compare any two values** in the tree and say that one is **either less than or greater than the other.**\n* The tree is **antisymmetric** - If `p \u003c q` is true and `q \u003c r` is also true, then it must follow that `p \u003c r`.\n\n## Tree Operations\n\nThere are **three important operations** that trees should support: **find, insert, and delete.**\n\n### **Find**\n\nFinding a value in a tree uses Binary Search. Click the link below to read up on it!\n\n{% content-ref url=\"../../algorithms/searching/binary-search.md\" %}\n[binary-search.md](../../algorithms/searching/binary-search.md)\n{% endcontent-ref %}\n\n### Insert\n\nThe insert algorithm is **very similar to binary search.** Here are the steps to take:\n\n* Search for the item. **If it's found, then do nothing** since the value is already in the tree.\n* If it's not found (search would return null in this case), then create a node and put it where it should be found. If using recursion, this last step is already done- all we need to do is return a new node!\n\nHere's the algorithm:\n\n```java\npublic BST insert(BST T, Key sk) {\n if (T == null) {\n // Create new leaf with given key. Different from search\n return new BST(sk, null, null); \n }\n if (sk.equals(T.key)) {\n return T;\n } else if (sk \u003c T.key) {\n T.left = find(T.left, sk); // Different from search\n } else {\n T.right = find(T.right, sk); // Different from search\n }\n}\n```\n\n### Delete\n\nThis one's a bit trickier because we need to make sure that the new tree still **preserves the binary search tree structure.** That means that we might have to shuffle around nodes after the deletion. There are **three cases:**\n\nA) The node to delete is a **leaf**. This is an easy case- just remove that node and you're done!\n\n![Deleting a leaf.](\u003c../../img/assets/image (64).png\u003e)\n\nB) The node to delete has **one child.** In this case, **swap** the node with its child, then **delete the node.**\n\n![Deleting a node with one child.](\u003c../../img/assets/image (65).png\u003e)\n\nC) The node to delete has **two children.** This one's trickier, because we still need to preserve the tree structure! In this case, we have to **traverse the node's children** to find the **next biggest value** and swap that up to replace the old node.\n\n![Deleting a node with two children.](\u003c../../img/assets/image (66).png\u003e)\n\n## Asymptotic Analysis\n\
"lastmodified": "2023-01-03T01:48:32.700428829Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/binary-trees/balanced-search-structures": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Balanced BSTs\n\n{% hint style=\"warning\" %}\nPlease read [Binary Trees](./) before continuing!\n{% endhint %}\n\n**Balanced Binary Search Trees** are an even more specific subcategory of binary trees that have an important property: **they are always bushy.**\n\n## B Trees (2-4 Trees)\n\n**The basic idea:** Nodes can hold multiple values now! When nodes have too many values, we will split it.\n\nA **2-4 tree** is named such because each parent can have **2 to 4 children.** Another constraint we will put on is a **limit on the** **number of items allowed in a single node**, so that we can guarantee that searching a single node will always be $\\Theta(n).$\n\n### **Adding Values to a B-Tree**\n\nAdding values to a B Tree can be a bit tricky because we need to make sure all the properties are still followed. Here are some example scenarios:\n\nIf a node already has 2 or more children, place the new value in one of its existing children.\n\n![](\u003c../../img/assets/image (81).png\u003e)\n\nIf a node is full (reaches the limit), we must **split the node** by **moving one value up to the parent** and **creating another child node**. Here, we'll use a limit of **3**.\n\n![](\u003c../../img/assets/image (82).png\u003e)\n\n### Properties of B Trees\n\n* Searching in a single node is **constant runtime** since the limit is a constant.\n* All leaves must be the **same distance** from the root.\n* A non-leaf node with **k** items must have **k+1** children.\n* The height of a B tree is guaranteed to be $\\Theta(\\log(n))$ because it is bushy.\n\n## Red-Black Trees and Tree Rotation\n\n**The basic idea:** Let's try to represent B trees in a **binary tree format.** That means that every parent can only have 2 children! In order to do this, we'll **add an extra color property** to each node.\n\n**Black nodes** are just like any normal binary tree node, but **Red nodes** represent the nodes in B Trees that have **more than one value.** For example, let's convert the B Tree we were working with before into a RB Tree.\n\n![](\u003c../../img/assets/image (83).png\u003e)\n\nIn order to make our lives easier, we'll restrict our Red Black trees into **left leaning red black trees** which can **only have red nodes on the left.**\n\n### **Tree Rotation**\n\nIn order to ensure that adding new nodes won't break the Red Black Tree structure, we will use a concept called **tree rotation** which swaps around nodes. There are two rotations, a **left rotation** and a **right rotation,** which move a child node up to replace its parent. For example, a **left rotation** moves the **right node up and left** to replace the parent.\n\nA \"left rotation on 7\" looks like this:\n\n![](\u003c../../img/assets/image (84).png\u003e)\n\nNotice that the **8** gets moved to be a **right child** of **7** after the rotation! This is necessary to preserve the binary tree structure.\n\nA \"right rotation on 7\" looks like this:\n\n![](\u003c../../img/assets/image (85).png\u003e)\n\nHere, the **6** gets moved to be a **left child** of **7.**\n\nIf you want to see how these rotations can be implemented into the `insert` algorithm, [try the homework](https://inst.eecs.berkeley.edu/\\~cs61b/sp20/materials/hw/hw8/index.html) on implementing a LLRB Tree! Below is a brief outline on how insert works:\n\n* **Always add values to a leaf node as a red node first.** Follow normal sorted binary tree rules.\n* If the link is leaning right, rotate the tree to make it left leaning.\n* If a node already has a red link to the left, temporarily add it to the right also as a red link.\n * Then, flip the color of all links connected to the node (if previously black, turn red; if previously red, turn black)\n * Might need to fix right-leaning red nodes that are created as a result\n* If a node has red links to both parent and child, rotate it such that it becomes the above case, and then handle that case like you did before.\n\n### Properties of Red Black Trees\n\nLike B Trees, Red Black Trees have some important properties that allow them to be easily distinguisha
"lastmodified": "2023-01-03T01:48:32.700428829Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/binary-trees/heaps": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Heaps\n\n## What are Heaps?\n\nA heap is a **specific order of storing data,** often in a list. Heaps are very similar to binary trees, but have some differences:\n\n* Unlike trees, heaps **only care about the root node.** Usually, the root node is either the **largest** or **smallest** value in the heap (corresponding with max-heaps and min-heaps), and we don't care too much about the rest.\n* Every element in the heap must be **larger than all its children** (in a max-heap) or **smaller than all its children** (in a min-heap). This is known as the **heap property.**\n\nWhen stored in a list, there is an **important rule** to figure out how to identify parent nodes and their children: **a node's parent has an index equal to half of that node's index.** More specifically, `parentIndex = nodeIndex / 2` where `/` has floor-division properties.\n\n![Converting a heapified list into a min-heap diagram.](\u003c../../img/assets/image (60).png\u003e)\n\n## The Heapify Algorithm\n\nThe most important heap algorithm is **heapify**, which converts any non-heap list into a heap. This algorithm is vital to most heap functions like insert or remove, since these functions often break the heap structure before fixing it with heapify.\n\n**Here's how it works:**\\\n****(This example is an excerpt from my [Sorting Guide](https://docs.google.com/document/d/1dUfzdh5V3okrwFbB9o0PgtEBaLHyCqJFwpQWyQ53IeU/edit). The example provided is a max-heap \\[5,6,2,4,1].)\n\nStart with the element in the middle of the array (which is the root of the heap).\n\n![](\u003c../../img/assets/image (61).png\u003e)\n\nIf the root is smaller than either of its children (larger for a min-heap), swap it with its largest child (smallest for a max-heap).\n\n![](\u003c../../img/assets/image (62).png\u003e)\n\n\n\nIf the root was swapped, recursively call heapify on the new position. Otherwise, stop recursion.\n\nAfter heapify is complete, it should look like this:\n\n![](\u003c../../img/assets/image (63).png\u003e)\n\n## Practical Applications\n\n[Lab 9](https://inst.eecs.berkeley.edu/\\~cs61b/sp20/materials/lab/lab9/index.html) is a fantastic resource for practicing heap implementations and working with the algorithms that are needed to work with heaps (like heapify, insert, remove). Since this lab goes into plenty of detail about how each of these algorithms work, I won't explain them too much here.\n\nHeap sort relies on the heap structure to provide consistent nlogn sorting! I have more information about this on page 11 in my [sorting guide](https://docs.google.com/document/d/1dUfzdh5V3okrwFbB9o0PgtEBaLHyCqJFwpQWyQ53IeU/edit).\n",
"lastmodified": "2023-01-03T01:48:32.700428829Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/binary-trees/tries": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Tries\n\n## Main Ideas\n\nA **trie** is a specific implementation of a set and is short for **retrieval tree.**\n\nIt only works on sets with a **finite alphabet**, like digits or ASCII characters, for example. The idea is that each node can act like an **array containing all characters in the alphabet** and we can just access the branches super fast by indexing into them!\n\nTries are fantastic for searching to see if a word is contained in a set. Here's an example:\n\n![This trie contains the words 'batcat', 'batman', and 'banana'.](\u003c../../img/assets/image (74).png\u003e)\n\nThis is great because it makes the `add()` and `contains()` functions run in $\\Theta(1)$ time! Additionally, it makes special string operations like prefix matching or autocomplete very efficient.\n\nWe can improve this data structure a lot- for instance, we can condense the leaves to reduce the number of nodes like this:\n\n![](\u003c../../img/assets/image (75).png\u003e)\n\nI won't go into too much detail on how to optimize it further, or how to implement the actual functions efficiently, but hopefully you'll have a good sense of how to do it yourself after learning about concepts like [Hashing and Hash Tables](../hashing.md) or [Sets](../collections/sets.md) etc.\n",
"lastmodified": "2023-01-03T01:48:32.700428829Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/collections/README": {
"title": "",
"content": "# Collections\n\n![An overview of all the Collections in Java.](\u003c../../img/assets/image (3).png\u003e)\n\n**Collection** is a Java interface for common abstract data types that store multiple items in them.\n\n## Sub-Interfaces\n\n* **Lists** are indexed sequences with duplication. The two most common types are [**ArrayLists**](arrays.md#array-lists) **** and [**Linked Lists**](linked-lists.md)**.**\n* ****[**Sets**](sets.md) **** are non-indexed sequences with no duplication. (That is, every value in a set is unique.)\n* **Maps** are key-value pairs. See [Hashing and Hash Tables](../hashing.md) for a description on one common map implementation, the HashMap. All keys in a map must be unique, but values can be duplicated.\n* ****[**Stacks and Queues**](stacks-and-queues.md) **** are two ordered collections that have two core behaviors:\n * push(T x): puts x on the top.\n * pop(): Removes the first item. (See the stacks and queues page for more information.)\n\n## Common Functions\n\n* **Membership tests** `contains()` and `containsAll()` that can determine whether or not an element is in the collection.\n* `size()` to get the number of items in the collection.\n* `isEmpty()` returns true if there is nothing in the collection.\n* `iterator()` returns an Iterator object to go through all the values in the collection.\n* `toArray()` converts the collection to a standard Java array.\n* **Optional** functions that aren't implemented in the interface: `add, addAll, clear, remove, removeAll, retainAll (intersection)`\n * Throws `UnsupportedOperationException` if not implemented.\n",
"lastmodified": "2023-01-03T01:48:32.700428829Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/collections/arrays": {
"title": "",
"content": "# Arrays\n\n{% hint style=\"info\" %}\nThis page assumes prior knowledge of Python lists from CS61A or equivalent.\n{% endhint %}\n\nArrays are a very popular data structure that stores an indexed list of data. \\\n\n\n![An artistic interpretation of a new int\\[5\\] {6, 1, 2, 3, 99};](\u003c../../img/assets/image (37).png\u003e)\n\n## Properties\n\n* **Fixed length:** after instantiation, the length of an array cannot be changed.\n* Every value in array is the **same type** and holds the **same amount of bits** in memory.\n* **Zero-indexed.** That means `arr[0]` returns the first value, and `arr[arr.length]` is out of bounds.\n* **No methods.** Helper methods from other libraries (like `System.arraycopy`) need to be used to manipulate arrays.\n* **Retrieval is independent of size** and takes constant time regardless of how big arrays are.\n\n## Using Arrays in Java\n\n**Instantiation:**\n\n* `int[] a = {1, 2, 3, 4, 5};` assigns values.\n* `int b = new int[3];` creates array of provided length populated with default values.\n\n**Copying**\n\n* Simply assigning `int[] c = b` will copy the **pointer** to array b! Not the values! See [Java Objects](../../oop/objects.md) for a discussion on why this is significant.\n* Use `System.arraycopy(source, start, target, startTarget, amountToCopy)` to **shallow copy** the values (or pointers) in the array. That is, if an array is holding **reference types,** only the pointers will be copied and not the actual values of the reference objects being held.\n* `System.arraycopy(b, 0, x, 3, 2)` is equivalent to `x[3:5] = b[0:2]` in Python.\n\n**Multidimensional Arrays**\n\n* `int[][] 2d = new int[4][4];`or `int[][] 2d = new int[][] {{1}, {2, 3}, {4, 5, 6}};`will create **arrays inside of an array.** This is useful for storing matrices, coordinate maps, or any other multidimensional data!\n\n**Generic Arrays**\n\n* Arrays of generic objects are NOT allowed! Use ArrayLists instead.\n* Or, this workaround can be used:`Type[] items = (Type[]) new Object[length]`\n\n## Array Lists\n\nJava has another built-in type that uses an array under the hood, which is the `ArrayList`. Here's how ArrayLists are different from normal arrays:\n\n* ArrayLists can resize arbitrarily. (They use something similar to the array case study in the [Amortization](../../asymptotics/amortization.md#what-if-we-doubled-the-size-instead-of-adding-one) page.\n* ArrayLists use [Generic Types](../../oop/generics.md) and therefore do not support primitive types like `int`.\n* ArrayLists have all behaviors expected from the [Collections](./) interface.\n",
"lastmodified": "2023-01-03T01:48:32.700428829Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/collections/linked-lists": {
"title": "",
"content": "# Linked Lists\n\n{% hint style=\"info\" %}\nThis page assumes prior knowledge of linked lists from CS61A or equivalent. I'll assume you have already worked with basic singly linked lists before.\n{% endhint %}\n\nThe linked list is an extremely common recursive data structure that allows storage and access of an arbitrary amount of data.\n\n## Feature List of an Effective Linked List\n\n1. **Rebranding**- represents Node as an individual object rather than having one monolithic List type.\n2. **Bureacracy:** Create an abstraction barrier so that users do not need to know how methods or Nodes work, only how to call them.\n3. **Access Control:** Data cannot be accessed directly to prevent dangerous behavior; only the provided methods are used.\n4. **Nested Class:** Nodes are nested within the List object since other classes do not need it.\n5. **Caching:** The size of the list is incremented every time a node is added, so running size() is O(1) and traversal is not needed.\n6. **Generalizing:** A **sentinel node** represents an empty list and remains the first node of the list. When getFirst() is called, the second node is actually returned (since the first node is always the sentinel).\n7. **Doubly Linked:** Nodes have both first and last pointers for even faster traversal.\n8. **Circular list:** Sentinel last pointer points to the last value in the node, allowing for fast removeLast().\n\n![An illustration of an effective linked list.](\u003c../../img/assets/image (36).png\u003e)\n\n## Method List\n\n| Method | Description | Optimal Runtime |\n| -------------------------------------------------------------------- | ------------------------------------------------ | --------------- |\n| \u003cp\u003e\u003ccode\u003eaddFirst(T x)\u003c/code\u003e\u003c/p\u003e\u003cp\u003e\u003ccode\u003eaddLast(T x)\u003c/code\u003e\u003c/p\u003e | Adds a node to the front/back of the list. | $\\Theta(1)$ |\n| \u003cp\u003e\u003ccode\u003egetFirst()\u003c/code\u003e\u003c/p\u003e\u003cp\u003e\u003ccode\u003egetLast()\u003c/code\u003e\u003c/p\u003e | Gets the node at the front/back of the list. | $\\Theta(1)$ |\n| \u003cp\u003e\u003ccode\u003eremoveFirst()\u003c/code\u003e\u003c/p\u003e\u003cp\u003e\u003ccode\u003eremoveLast()\u003c/code\u003e\u003c/p\u003e | Removes the node at the front/back of the list. | $\\Theta(1)$ |\n| `size()` | Returns the number of nodes in the list. | $\\Theta(1)$ |\n| `contains(T x)` | Returns true if the list contains element `x`. | $\\Theta(n)$ |\n| \u003cp\u003e\u003ccode\u003eadd(T x, int pos)\u003c/code\u003e\u003c/p\u003e\u003cp\u003e\u003ccode\u003eremove(T x)\u003c/code\u003e\u003c/p\u003e | Adds/remove an element at an arbitrary location. | $\\Theta(n)$ |\n\n## Limitation: Arbitrary Retrieval\n\nYou may have noticed in the chart above that it takes $\\Theta(n)$ time to retrieve arbitrary values from the list. This will get really slow if the list is large! If arbitrary values need to be accessed frequently, [Arrays](arrays.md) are much better.\n\n## The Java List Interface\n\nJava has a built-in `LinkedList` class so you don't have to implement it yourself! Read up on the [official docs](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html/) to learn more about the specific methods and behaviors provided.\n\n",
"lastmodified": "2023-01-03T01:48:32.704428808Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/collections/sets": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Sets\n\n{% hint style=\"warning\" %}\nThis page is from my original notes and is not up to the latest quality standards. Read with care or [help make it better!](https://github.com/64bitpandas/cs61b-notes/pulls)\n{% endhint %}\n\n## Basics\n\nA Set stores a collection of values with **no duplicates.** Sets have no inherent order, so you can't rely on expecting any value to come before any other value when iterating through them.\n\nSome set functions include:\n\n* `add(T x)`\n* `contains(T x)`\n* `size()`\n\n## ArraySet\n\nAn ArraySet is an array-based solution to a set implementation.\n\n* Objects get added to an array that gets [resized](../../asymptotics/amortization.md) when it's too full.\n* In order to allow for iteration, we can use one of two methods:\n * One method is to use **iterators** which work very similarly to Python iterators:\n\n ```java\n Iterator\u003cInteger\u003e seer = set.iterator();\n while (seer.hasNext()) {\n System.out.println(seer.next());\n }\n ```\n * Another method is to implement the `Iterator` and `Iterable` interface.\n * Iterator must implement `hasNext()` and `next()` methods\n * Requires generic type\n * Iterable must implement `iterator()` method which returns the Iterable object\n * Allows usage of for/foreach loops\n",
"lastmodified": "2023-01-03T01:48:32.704428808Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/collections/stacks-and-queues": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Stacks and Queues\n\nStacks and queues are two very common data structures used for a variety of applications from [CPU processes](https://www.tutorialspoint.com/operating\\_system/os\\_processes.htm) to [finding shortest paths using Dijkstra's Algorithm](../../algorithms/shortest-paths/dijkstras-algorithm.md). Fundamentally, they are very similar in structure and **only differ by the order in which items are popped from them**.\n\n## Pushing and Popping\n\n### Pushing\n\nAdding an item to a stack or queue is called **pushing**. This will either put the item on the **top** of a stack or in the **back** of a queue.\n\nYou can think of a stack like a pile of pizza boxes- the one on the top is the first one you have to take off if you need one!\n\n![](\u003c../../img/assets/image (52).png\u003e)\n\nOn the other hand, you can think of a queue like lining up for a ride at Disneyland. The first person who gets in line will get to go first, and the last person who gets in will go last. (Of course, we all know people cut and stuff- see [Priority Queues](stacks-and-queues.md#priority-queues) to see how this is better handled.)\n\n![those lines tho](\u003c../../img/assets/image (54).png\u003e)\n\n### Popping\n\nTaking an item out of a stack or queue is called **popping.**\n\nStacks are **last in, first out (LIFO).** That means the last item that you put in will be the first item that gets popped.\n\nQueues are **first in, first out (FIFO).** That means that the first item that you put in will be the first item that gets popped.\n\n## Priority Queues\n\nLet's say you bought a VIP pass and get to cut to the front of the line for your favorite Disneyland ride! Well, a normal Queue won't be able to model this behavior since it puts everything in the back by default.\n\nA priority queue will solve this design need by introducing a new **priority** **tracking system** for each item in the queue! **If an item has a lower priority number, it will get to go first.**\n\n![gotta grab those fastpasses yEEt 🎟](\u003c../../img/assets/image (53).png\u003e)\n",
"lastmodified": "2023-01-03T01:48:32.704428808Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/comparables-and-comparators": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Comparables and Comparators\n\n## What is it?\n\nA **Comparable** is a **generic type** that allows standardized comparisons between objects.\n\nIn other words, anything that has a `compareTo()` method can be a Comparable!\n\nMany Java libraries already use Comparable without you knowing! Some of the more well-known ones are `Collection` and `String`.\n\n### CompareTo can't return anything you want!\n\nThere are some very specific properties CompareTo needs to have! Usually, we take them for granted but might forget about them when making our own.\n\n* If `x` and `y` are the **same object**, `y.compareTo(x)` must return **0.**\n* `x.compareTo(y)` must return the **negative** of `y.compareTo(x)`. (if one throws an error, the other must too!)\n* If `x` and `y` are the **same object**, `x.compareTo(z)` must **equal** `y.compareTo(z)` **for all z.**\n\n### Defining a Comparable subclass\n\n```java\npublic class MyComparable implements Comparable\u003cMyComparable\u003e {\n public int foo;\n ...\n\n /** Instance method that has nothing to do with comparable */\n public void doSomething() {\n ...\n }\n\n /** Comparable method used to compare objects of this type */\n public int compareTo(Object o) {\n MyComparable mc = (MyComparable) o;\n return ...\n }\n}\n```\n\n## **Comparators**\n\nComparators are used instead of higher order functions in order to provide a **callback** function to methods. One example of where it is used commonly is `Collections.sort`. You can pass in a comparator here to change how items are sorted- for example, you could sort `Person` objects by their `height` variable.\n\n**The interface is as follows:**\n\n```java\npublic interface Comparable\u003cT\u003e {\n int compare(T o1, T o2);\n}\n```\n\n### How is it different from Comparables???\n\nComparable is used to compare **itself** to **other objects**; a Comparator compares **two other objects but not itself.**\n\n",
"lastmodified": "2023-01-03T01:48:32.704428808Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/graphs": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Graphs\n\n## Introduction\n\nGraphs are simply a collection of **vertices** connected by **edges.** They're very similar to trees, but are much more versatile and don't require hierarchical relationships like trees do.\n\n![A very simple graph.](\u003c../img/assets/image (55).png\u003e)\n\nFor most purposes, we will be working with **simple graphs** that follow two rules:\n\n* There are **no loops** (a connection of a node to itself).\n* There are **no parallel edges** (two edges that connect the same two vertices).\n\n![Don't make these graphs pls. Keep life simple!](\u003c../img/assets/image (56).png\u003e)\n\n## Graph Properties\n\nGraphs can be described by some properties that they could have. Here are the important ones:\n\nA graph can be **directed** if edges are arrows and have a direction, or **undirected** if you can cross edges in any direction.\n\nA graph is **cyclic** if the edges form a loop, or **acyclic** if there are no loops (like in a tree).\n\n![Direction vs. Cycles](\u003c../img/assets/image (57).png\u003e)\n\nGraphs can have **edge labels** if edges are numbered (great for distances). They can also have **vertex weights** if vertices are numbered (great for priorities or costs).\n\n![Edge labels vs. Weights](\u003c../img/assets/image (58).png\u003e)\n\nGraphs are **connected** if all of the vertices are connected with edges, such that you can freely move from one vertex to any other vertex.\n\n![](\u003c../img/assets/image (59).png\u003e)\n\n## Graph Queries\n\nHere are some cool things you can do with graphs:\n\n* Is there a path between two vertices? (s-t path)\n* What is the shortest route between two vertices? (shortest s-t path)\n* Are there cycles? (cycle detection)\n* Can you visit each vertex/edge exactly once? (Euler tour / Hamilton tour)\n* Is a graph connected? (connectivity problem)\n* Is a vertex that disconnects the graph when removed? (single point of failure / biconnectivity)\n* Are two graphs isomorphic?\n* Can a graph be drawn with no crossing edges? (planarity)\n\n## More on Graphs\n\n[Depth First Search (DFS)](../algorithms/searching/depth-first-search-dfs.md), [Breadth First Search (BFS)](../algorithms/searching/breadth-first-search-bfs.md), [Minimum Spanning Trees](../algorithms/minimum-spanning-trees/), [Shortest Paths](../algorithms/shortest-paths/), [Dijkstra's Algorithm](../algorithms/shortest-paths/dijkstras-algorithm.md), [A\\* Search](../algorithms/shortest-paths/a-search.md), [Prim's Algorithm](../algorithms/minimum-spanning-trees/prims-algorithm.md), and [Kruskal's Algorithm](../algorithms/minimum-spanning-trees/kruskals-algorithm.md) all rely on graphs. Graphs are a super useful concept!!!\n",
"lastmodified": "2023-01-03T01:48:32.704428808Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/hashing": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Hashing and Hash Tables\n\n## Data Indexed Sets: Introduction\n\nSo far, we've explored a whole bunch of ways we can store items, but they aren't really optimized for general searching. What if we could get searching in $\\Theta(1)$ time??? Wouldn't that be nice!\n\nLet's try something: **putting all of our data in a massive array.** Let's say that we know all our data falls into the range from 0 to 10,000 and make an array of 10,000 length to hold stuff.\n\n![](\u003c../img/assets/image (86).png\u003e)\n\nHere, it doesn't matter what index each item is stored in- if we want to get \"eecs\" which is stored at key 3, it will be as instantly accessible as \"haas\" which is all the way in 9998.\n\nOf course, this has a **major design flaw** that you can probably see right away. **It takes way too much memory!**\n\n## Hash Codes\n\nLet's figure out a way to get around the issue of space, but still not lose our awesome constant-time property. One way we can do this is to represent each item with a **hash code** and store them into the index with that hash code.\n\nFor instance, let's use the **first letter of a word** as the hash code. We have just turned a nearly infinite space of possibilities into something that can be stored in just **26** **buckets.**\n\n![](\u003c../img/assets/image (87).png\u003e)\n\nWhile this solution is great, it still has another **major drawback**, which can be illustrated with this example:\n\n![](\u003c../img/assets/image (88).png\u003e)\n\nIn the worst case, this just turns back into a **linked list!** That means the runtime just went from O(1) to O(n), and that's no good.\n\n## Good Hash Codes\n\nIf we can somehow create a \"good\" hash code, we can prevent things like the example above from happening because there shouldn't be a clear pattern in what buckets different objects go to. More specifically, a good hash code:\n\n* Ensures that two objects that are **equal** have the **same hash code.**\n* Ensures that **no distinguishable pattern** can be made out of hash codes from different objects.\n* Returns a **wide variety** of hash codes (not just putting everything into a single bucket, for example).\n\nLuckily, Java already handles hash code generation for us using the `hashCode()` function in the Object class. This function returns an **integer** that can be used to create good hash tables.\n\n## Dynamic Resizing\n\nLet's add another feature to our hash table: **dynamic resizing.** This means that the number of buckets will increase proportionally to the number of items in the set.\n\nOne fairly simple way to do this with a numerical hash code is to mod the hash code by the number of buckets to get which bucket an item is stored in. For example, if a item has hash code `129382981` and we have `10` buckets, then we put it in bucket `1`, or `129382981 % 10`.\n\nIn order to do this, we'll choose a **load ratio** at which to resize. This load ratio is calculated as `N/M`, where N is the number of items and M is the number of buckets. For example, a load ratio of 2 will mean the table resizes when, on average, each bucket has 2 items in it.\n\nWhen resizing, we must **recompute all the hash codes** so that we can balance out all of the buckets again.\n\nThis has some cool runtime implications that are closely related to [Amortization](../asymptotics/amortization.md). Like what happened in the dynamically resizing array, resizing hash tables like this is also a $\\Theta(1)$ operation. Nice!\n\n## Java Hash Tables\n\nIn Java, hash tables are used in the data structures `HashSet` and `HashMap` which are the most popular implementation of sets and maps.\n\nThese two implementations provide **fantastic performance** and **don't require values to be comparable** like trees do.\n\nHowever, they have a drawback that must be considered: **objects cannot be modified after they are put into the hash table.** This is because mutating an object will change its hash code, which means that the object will be lost forever since its bucket doesn't match the current hash code!\n\nIf the built-
"lastmodified": "2023-01-03T01:48:32.704428808Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/abstract-data-types/union-find-disjoint-sets": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Union Find (Disjoint Sets)\n\n{% hint style=\"info\" %}\nThis is not a complete entry, because I feel like existing course materials already cover this in an extremely intuitive manner.\\\nSee[ lab 14](https://inst.eecs.berkeley.edu/\\~cs61b/sp20/materials/lab/lab14/index.html) for an guide on how to implement your own Union Find structure!\n{% endhint %}\n\nThe Union Find data structure is a way of representing a bunch of nodes that are connected to each other in subsets. It's used in [Kruskal's Algorithm](../algorithms/minimum-spanning-trees/kruskals-algorithm.md) among other things.\n\nUnion Find is named as such because it supports two functions, **find** (which returns the group that a value is contained in), and **union** (which connects two values to form a single group).\n\nUnion Find tracks each set with an ID, typically **the value of the root of each set.** In the sections below, we'll discuss how to add an item to a set, as well as figure out which set an existing item is in.\n\n## Union\n\nIn order to **join two values together,** we need to use the **union** function. Let's see what it does visually:\n\n![Calling union(1,2).](\u003c../img/assets/image (78).png\u003e)\n\nThere are lots of ways to represent this behavior. One possible method is to keep an **array of parent values** corresponding to each actual value. In the example above, for instance, we can choose 1 as our parent and make 2 fall under that. Let's see how this might work:\n\n![Parents list.](\u003c../img/assets/image (79).png\u003e)\n\nNow, let's say we call `union(3,2)`. We can just set the parent of 3 to 2, as to create a structure like this:\n\n![union(1,2) followed by union(3,2)](\u003c../img/assets/image (80).png\u003e)\n\nThis looks a lot like a tree!\n\nYou might have noticed that this looks like a **spindly tree** though, which is bad for runtime! Perhaps we can convert it to the equivalent of a bushy tree- the union function can be made much more efficient using tricks such as WeightedQuickUnion and Path Compression. Watch [this playlist](https://www.youtube.com/watch?v=JNa8BRRs8L4\\\u0026list=PL8FaHk7qbOD59HbdZE3x52KOhJJS54BlT\\\u0026index=1) for more information!\n\n## Find\n\nFirst, let's explore how to implement an efficient way to **find which set a value is in.** Using the union function from above, we can do this pretty easily with this simple algorithm:\n\n* If the parent is 0, simply return the value.\n* If the parent is not 0, return the result of calling the function on the parent value.\n\nIf we follow this algorithm on the example in the Union section, we can see that calling `find(3)` will go to `2`, then finally to `1` and return `1`.\n",
"lastmodified": "2023-01-03T01:48:32.704428808Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/minimax": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Minimax Algorithm\n\n## Game Trees\n\nThe Minimax algorithm is often used for making AI's for turn-based games. It relies on the use of a type of **game tree,** which maps out all of the possible moves that players can make.\n\nIn the tree, there are two types of nodes: **maximizing nodes** and **minimizing nodes.** The max-nodes represent **you**- you want to make your position as advantageous as possible (maximizing your score). The min-nodes represent **your opponent-** they want to make you do as poorly as possible (minimizing your score).\n\nThe scores themselves are generated using a **heuristic function** that assesses the current game state and returns a number based on which player has an advantage, and to what extent. **This heuristic is totally up to you to figure out and has very few constraints.** There are a couple rules, however:\n\n* Heuristic functions must return **positive values** if you're doing better than your opponent, and **negative values** if your opponent is doing better.\n* Heuristic functions must return the **maximum value** for a state in which you won, and the **minimum value** for a state in which your opponent won.\n\nIn most games, you and your opponent will take turns, so each layer will alternate node type, like this:\n\n![](\u003c../img/assets/image (99).png\u003e)\n\nIn most games, this tree will spiral out of control because there are far too many nodes to possibly analyze (maybe even an infinite number)! Therefore, we need to set a **depth** to stop searching and compute a heuristic. For example, if the depth is **3**, it'll look something like this:\n\n![](\u003c../img/assets/image (100).png\u003e)\n\nNow that the tree has bottomed out at the heuristic layer, we can start going back up to figure out which move we should make! The rules are simple: **min-nodes take the smallest of the values** while **max-nodes take the largest of the values.** Here's the first layer, for example:\n\n![](\u003c../img/assets/image (101).png\u003e)\n\nHere's the entire tree filled out:\n\n![](\u003c../img/assets/image (102).png\u003e)\n\nAnd here's the minimax algorithm in pseudocode format:\n\n```python\ndef minimax_value(s: MinimaxNode):\n if is_terminal(s):\n return s.value\n elif s.player == Maximizing:\n return max(minimax_value(c) for c in s.children)\n elif s.player == Minimizing:\n return min(minimax_value(c) for c in s.children)\n```\n\n## **Alpha-Beta Pruning**\n\nWe can make our tree **even more efficient** by simply ignoring all of the branches that will lead to results that will **never be chosen.** Here, we'll assume that **both players play optimally** (choose the best move for their particular node).\n\nIn the example above, we can see that the 7 on the right will **never need to be visited** because we **already know that 5 will be chosen.**\n\nIn order to do this, we'll introduce two additional parameters, **alpha** and **beta.** Here are the rules:\n\n* **Alpha** starts out as **negative infinity** and is set by **max nodes** to their current value.\n* **Beta** starts out as **positive infinity** and is set by **min nodes** to their current value.\n* A node **passes its alpha and beta values** onto its children.\n* If **alpha is greater than beta (**$\\alpha \\ge \\beta$**),** the branch will be **pruned** (no longer visited).\n\nHere are the step-by-step instructions on how to process a node:\n\n1. Copy the alpha and beta values from the parent node. (If no parent node exists, then initialize alpha to negative infinity and beta to positive infinity.\n2. For every branch:\n 1. Recursively process the branch.\n 2. Update the current alpha/beta value depending on the value of the branch after processing. (MaxNodes can only update alpha, and MinNodes can only update beta.)\n 3. If $\\alpha \\ge \\beta$**,** then prune the rest of the branches (stop this loop).\n3. Set the value of this node to the biggest (MaxNode) or smallest (MinNode) value seen.\n\nThe pseudocode for alpha-beta pruning is as follows:\n\n```python\n```\n\nThis
"lastmodified": "2023-01-03T01:48:32.708428787Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/minimum-spanning-trees/README": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "\n# Minimum Spanning Trees\n\n## Spanning Tree Definition\n\nA **spanning tree** T is a subgraph of a graph G where T:\n\n* Is connected (there's a path to every vertex)\n* Is acyclic (no cycles)\n* Includes every vertex (spanning property)\n\n**Notice:** the first two properties defines a tree structure, and the last property makes the tree spanning.\n\nA **minimum spanning tree** is a spanning tree with minimum total edge weight.\n\nExample: I want to connect an entire town with wiring and would like to find the optimal wiring connection that connects everyone but uses the least wire.\n\n## MST vs. Shortest Path Tree\n\nIn contrast to a shortest path tree, which is essentially the solution tree to running Dijkstras with root node = source vertex, a MST has no source. However, it is possible for the MST to be the same as the SPT.\n\nWe can think of the MST as a global property for the entire graph, as opposed to SPT which depends on which node is the source node.\n\nIf the edges of the graph are not unique, theres a chance that the MST is not unique.\n\n## Cuts Property\n\n* A **cut** is defined as assigning the nodes in a graph into two sets.\n* A **crossing edge** is an edge that connects two nodes that are in different sets\n* The smallest crossing edge is the crossing edge with smallest weight\n\nThe **Cut Property** states that the smallest crossing edge is always going to be in the MST, no matter how the cut is made.\n\n![](\u003c../../img/assets/image (109).png\u003e)\n",
"lastmodified": "2023-01-03T01:48:32.708428787Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/minimum-spanning-trees/kruskals-algorithm": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "\n# Kruskal's Algorithm\n\n{% hint style=\"warning\" %}\nBefore reading, review [Minimum Spanning Trees](./) and [Union Find (Disjoint Sets)](../../abstract-data-types/union-find-disjoint-sets.md) as they both make Kruskal's algorithm possible!\n{% endhint %}\n\n## Conceptual Overview\n\nKruskal's algorithm is another optimal way to construct a **minimum spanning tree**. It's benefits are that it is conceptually very simple, and easy to implement. The idea is that first we sort all the edges of the graph in order of increasing weight. Then, add the smallest edge to the MST we are constructing unless this creates a cycle in the MST. Repeat until V - 1 edges total.\n\n## Detailed Breakdown\n\nIn order to optimally check if adding an edge to our MST creates a cycle, we will use a **WeightedQuickUnion** object. (See [Union Find (Disjoint Sets)](../../abstract-data-types/union-find-disjoint-sets.md) for a recap on what this is.) This is used because checking if a cycle exists using a WeightedUnionFind object boils down to one `isConnected()` call, which we know takes $\\Theta(\\log(N))$.\n\nTo run the algorithm, we start by adding all the edges into a [PriorityQueue](../../abstract-data-types/collections/stacks-and-queues.md). This gives us our edges in sorted order. Now, we iterate through the PriorityQueue by removing the edge with highest priority, checking if adding it forms a cycle, and adding it to our MST if it doesn't form a cycle.\n\nLet's see an example of Kruskal's Algorithm in action!\n\nHere, we start with a simple graph and have sorted all of its edges into a priority queue.\n\n![](\u003c../../img/assets/image (103).png\u003e)\n\nSince the edge **DE** is the shortest, we'll add that to our UnionFind first. In the process, we'll **remove DE from the priority queue.**\n\n![](\u003c../../img/assets/image (104).png\u003e)\n\nWe'll do the same thing with the next shortest path, **DC.**\n\n![](\u003c../../img/assets/image (105).png\u003e)\n\nNow, let's move on to **AB.** Notice that this time, connecting A and B creates another **disjoint set!** Unlike Prim's Algorithm, Kruskal's Algorithm does not guarantee that a solution will form a tree structure until the very end.\n\n![](\u003c../../img/assets/image (106).png\u003e)\n\nNow, let's connect **BC.**\n\n![](\u003c../../img/assets/image (107).png\u003e)\n\nSince **CE** and **BD** would both form cycles if connected, **we are done 😄** Here's the final tree:\n\n![](\u003c../../img/assets/image (108).png\u003e)\n\n## PseudoCode\n\n```java\npublic class Kruskals() {\n\n public Kruskals() {\n PQ edges = new PriorityQueue\u003c\u003e();\n ArrayList\u003cEdge\u003e mst = new ArrayList\u003c\u003e();\n }\n\n public void doKruskals(Graph G) {\n for (e : G.edges()) {\n PQ.add(e);\n }\n WeightedQU uf = new WeightedQU(G.V());\n Edge e = PQ.removeSmallest();\n int v = e.from();\n int w = e.to();\n if (!uf.isConnected(v, w)) {\n uf.union(v, w);\n mst.add(e);\n }\n\n }\n}\n```\n\n## Runtime Analysis\n\nLeft as an exercise to the reader 😉\n\n{% hint style=\"info\" %}\nSomeone's been reading too much [LADR](https://www.springer.com/gp/book/9783319110790)...\\\n(The answer is $\\Theta(E\\log(E))$by the way. Try to convince yourself why!)\n{% endhint %}\n",
"lastmodified": "2023-01-03T01:48:32.708428787Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/minimum-spanning-trees/prims-algorithm": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "\n# Prim's Algorithm\n\n{% hint style=\"warning\" %}\nBefore reading, review [Minimum Spanning Trees](./README), as that is the foundation of Prim's algorithm!\n{% endhint %}\n\n## Conceptual Overview\n\nPrim's algorithm is an optimal way to construct a **minimum spanning tree**. It basically starts from an arbitrary vertex, then considers all its immediate neighbors and picks the edge with smallest weight to be part of the MST. **Note:** this creates a cut in the graph, where the two nodes in the MST being constructed are in one set, and every other vertex of the graph is in another set.\n\nNow, the edges taken into consideration include all immediate neighbors of every node in the MST. Add the edge that has the smallest weight to the MST. Repeat until every vertex has been visited. The result is an MST for the graph.\n\n## Detailed Breakdown\n\nThe way Prim's algorithm is usually implemented is via [PriorityQueue](../../abstract-data-types/collections/stacks-and-queues.md), `edgeTo` array, and` distTo` array. You will soon see its similarities to [Dijkstra's](../shortest-paths/dijkstras-algorithm.md).\n\nFirst, insert all vertices into the PriorityQueue, storing vertices in order of **distance from MST**. Then, remove vertex with highest priority in the PriorityQueue and relax its edges. In each of these iterations, the distTo and edgeTo arrays will be updated for each vertex v if the **weight of the edge is smaller than the current value in distTo\\[v]**. In other words, only update if the distance from the MST to the vertex is the best seen so far. This is a very important point, and is one of the subtleties that makes Prim's algorithm fundamentally different from Dijkstra's.\n\n## Useful Properties/Invariants\n\nThe MST under construction is **always connected.**\n\n## Pseudocode\n\n```java\npublic class Prims() {\n\n public Prims() {\n PQ = new PriorityQueue\u003c\u003e();\n edgeTo = new Edge[numVertices];\n distTo = new Dist[numVertices];\n marked = new boolean[numVertices];\n }\n\n public void doPrims() {\n PQ.add(sourceVertex, 0);\n for(v : allOtherVertices) {\n PQ.add(v, INFINITY);\n }\n while (!PQ.isEmpty()) {\n Vertex p = PQ.removeSmallest();\n marked[p] = true;\n relax(p);\n }\n }\n\n public void relax(Vertex p) {\n for (q : p.neighbors()) {\n if (marked[q]) { continue; }\n if (q.edgeWeight \u003c distTo[q]) {\n distTo[q] = q.edgeWeigth;\n edgeTo[q] = p;\n PQ.changePriority(q, distTo[q]);\n }\n }\n }\n}\n```\n\nLooking at this pseudocode, the resemblance to Dijkstra's makes them seem nearly identical. But hopefully you've read the conceptual overviews first, and you understand the remarkable subtlety that leads to two very fundamentally different algorithms.\n\n## Runtime Analysis\n\nThis is the same as for Dijkstra's Algorithm.\n\n**Unsimplified:**\n\n$\n\\theta(V * log(V) + V * log(V) + E * log(V))\n$\n\n**Simplified:**\n\n$\n\\theta(E * log(V))\n$\n\n**Explanation:**\n\n* each add operation to PQ takes log(V), and perform this V times\n* each removeFirst operation to PQ takes log(V) and perform this V times\n* each change priority operation to PQ takes log(V), perform this at most as many times as there are edges\n* everything else = O(1)\n* usually, there are more or equal edges compared to the number of vertices.\n\n## Demo\n\n[https://docs.google.com/presentation/d/1GPizbySYMsUhnXSXKvbqV4UhPCvrt750MiqPPgU-eCY/edit#slide=id.g9a60b2f52\\_0\\_0](https://docs.google.com/presentation/d/1GPizbySYMsUhnXSXKvbqV4UhPCvrt750MiqPPgU-eCY/edit#slide=id.g9a60b2f52\\_0\\_0)\n",
"lastmodified": "2023-01-03T01:48:32.708428787Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/searching/README": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Searching\n\nThis section will cover some ways to find values in a set.\n\n{% content-ref url=\"binary-search.md\" %}\n[binary-search.md](binary-search.md)\n{% endcontent-ref %}\n\n{% content-ref url=\"depth-first-search-dfs.md\" %}\n[depth-first-search-dfs.md](depth-first-search-dfs.md)\n{% endcontent-ref %}\n\n{% content-ref url=\"breadth-first-search-bfs.md\" %}\n[breadth-first-search-bfs.md](breadth-first-search-bfs.md)\n{% endcontent-ref %}\n\n",
"lastmodified": "2023-01-03T01:48:32.708428787Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/searching/binary-search": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Binary Search\n\nBinary search is a way of finding a specific node in a tree. It only works on [binary trees](../../abstract-data-types/binary-trees/) due to its helpful sorted property. It simply traverses the tree, moving left if the current node is too large or right if it is too small.\n\nBinary search runs in $\\Theta(\\log(n))$ time for bushy trees, which is also the number of layers in a tree.\n\n## The Algorithm\n\n```java\npublic BST find(BST T, Key sk) {\n if (T == null) {\n return null;\n }\n if (sk.equals(T.key)) {\n return T;\n } else if (sk \u003c T.key) {\n return find(T.left, sk);\n } else {\n return find(T.right, sk);\n }\n}\n```\n",
"lastmodified": "2023-01-03T01:48:32.708428787Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/searching/breadth-first-search-bfs": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Breadth First Search (BFS)\n\nBreadth First Search (BFS), like [Depth First Search (DFS)](depth-first-search-dfs.md), is a method of **traversing a graph.** BFS simply traverses in a different order, but otherwise is very similar to DFS.\n\nThe main difference is that BFS **visits all children before any subgraphs.** In a tree, we call this **level order.**\n\n![](\u003c../../img/assets/image (110).png\u003e)\n\nFor the example tree above, a level order traversal would go in this order: **D B F A C E G.**\n\n## Step by Step\n\n**Let's see how we might implement BFS.**\n\nSome data structures we will need are:\n\n* A graph to traverse.\n* A queue **Q** to keep track of which nodes need to be processed next.\n* A list of booleans **marked** to keep track of which nodes were already visited.\n* (Optional) **edgeTo** and **distTo** to keep track of information that might be useful for other applications (like [Dijkstra's Algorithm](../shortest-paths/dijkstras-algorithm.md)).\n\nFirst, let's start with a vertex in the graph by marking it and adding it to the queue.\n\n![](\u003c../../img/assets/image (111).png\u003e)\n\nThe next step is to **remove A from the queue** and **add its children** (B and C) **to the queue.** Also, we need to **mark all of the children.**\n\n![](\u003c../../img/assets/image (112).png\u003e)\n\nNext, we'll move onto the **next item on the queue** (B). We'll do the same thing that we did with A: remove B, mark all its children, and add its children to the queue. **Since C is already marked, we do not add it to the queue again.**\n\n![](\u003c../../img/assets/image (113).png\u003e)\n\nNow, we'll move on to the next item on the queue, C, and do the same thing. Again, we won't add C or A because they are both marked.\n\n![](\u003c../../img/assets/image (114).png\u003e)\n\nFinally, we'll visit the two remaining nodes in the queue, D and E. Since all of the nodes are marked now, there aren't any other nodes to visit.\n\n",
"lastmodified": "2023-01-03T01:48:32.712428766Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/searching/depth-first-search-dfs": {
"title": "",
"content": "# Depth First Search (DFS)\n\n## Depth First Traversal\n\nBefore we move on to searching, let's talk about **traversing. Traversal** is the act of **visiting nodes in a specific order.** This can be done either in trees or in graphs.\n\nFor trees in particular, there are **three main ways** to traverse.\n\n![The example tree we will use for traversal illustrations.](\u003c../../img/assets/image (89).png\u003e)\n\nThe first way is **inorder** traversal, which visits **all left children**, then **the node itself,** then **all right children.** The end result should be that the nodes were visited in **sorted order.**\n\nThe second way is **preorder** traversal, which visits **the node itself first,** then **all left children,** then **all right children.** This method is useful for applications such as printing a directory tree structure.\n\nThe third way is **postorder** traversal, which visits **all left children,** then **all right children,** then **finally the node itself.** This method is useful for when operations need to be done on all children before the result can be read in the node, for instance getting the sizes of all items in the folder.\n\nHere are some pseudocodey algorithms for tree traversals.\n\n```java\n// INORDER will print A B C D E F G\nvoid inOrder(Node x) {\n if (x == null) return;\n inOrder(x.left);\n print(x);\n inOrder(x.right);\n}\n\n// PREORDER will print D B A C F E G\nvoid preOrder(Node x) {\n if (x == null) return;\n print(x);\n preOrder(x.left);\n preOrder(x.right);\n}\n\n// PREORDER will print A C B E G F D\nvoid postOrder(Node x) {\n if (x == null) return;\n preOrder(x.left);\n preOrder(x.right);\n print(x);\n}\n```\n\n## Depth First Search in Graphs\n\nGraphs are a little more complicated to traverse due to the fact that they could have **cycles** in them, unlike trees. This means that we need to **keep track of all the nodes already visited** and add to that list whenever we encounter a new node.\n\nDepth First Search is great for determining if everything in a graph is connected.\n\nHere's an outline of how this might go:\n\n* Keep an array of 'marks' (true if node has been visited) and, optionally, an edgeTo array that will automatically keep track of how to get to each connected node from a source node\n* When each vertex is visited:\n * Mark the vertex\n * For each adjacent unmarked vertex:\n * Set edgeTo of that vertex equal to this current vertex\n * Call the recursive method on that vertex\n\nLike trees, DFS can be done **inorder, preorder, or postorder.** It's nearly identical behavior to trees, with the addition of the marks array.\n",
"lastmodified": "2023-01-03T01:48:32.712428766Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/searching/dijkstras": {
"title": "",
"content": "# Dijkstra's Algorithm \n\n## One sentence overview:\nVisit vertices in order of best-known distance from source; on visit relax every edge from the visited vertex.\n\n## Dijkstra's vs BFS big idea:\nBFS returns the shortest paths in an unweighted graph, where the shortest path is just defined to be the fewest number of edges traveled along a path. In Djikstras, we can generalize the breadth-first traversal to find the path with the lowest cost, where the cost is determined by different weights on the edges. Djikstras uses a PQueue to maintain the path with lowest cost from the starting node to every other node. \n\n## Important points: \n- always visits vertices in order of total distance from source\n- relaxation always fails on edges to visited vertices \n- guarantees to work optimally as long as edges are all non-negative\n- solution always a tree form, true for undirected graphs\n- can think of as union of shortest paths to all vertices \n- edges in solution tree always has V-1 edges, where V = #vertices b/c for each vertex, exactly one input source except the root \n\n## Key invariants:\n1. edgeTo[v] always contains best known predecessor for v\n2. distTo[v] contains best known distance from source to v\n3. PQ contains all unvisited vertices in order of distTo\n\n\n## PseudoCode:\n PQ.add(sourceVertex, 0)\n For v in allOtherVertices:\n\t PQ.add(v, infinity)\n While !PQ.isEmpty():\n\t P = PQ.removeSmallest\n\t relax(P)\n\t \n (relaxing edge p → q)\n relax(Vertex p):\n\t If distTo[p] + q \u003c distTo[q]:\n\t\t distTo[q] = distTo[p] + q\n\t\t edgeTo[q] = p\n\t\t PQ.changePriority(q, distTo[q])\n\n\t\t\n\n## Runtime:\n$O(V*log(V) + V*log(V) + E*log(V)) → O(E*log(V)) $\n- each add operation to PQ takes log(V), and perform this V times\n- each removeFirst operation to PQ takes log(V) and perform this V times \n- each change priority operation to PQ takes log(V), perform this as many times as there are edges\n- everything else = O(1) \n- usually # edges \u003e= # vertices \n\n\n# A* Algorithm\n- Literally just Dijkstras, but with an added heuristic function to consider. Motivation: can help bias our algorithm in the right direction so that it doesnt make a bunch of bad moves. \n- For each vertex instead of only comparing distTo[v], also have a heuristic evaluation, so visit vertices in order of d(goal, v) + h(v, goal)\n- Not all vertices get visited, algorithm only cares about finding the best path to the goal, and not any other vertex (thats how the heuristic will be designed)\n- heuristic must be both:\n * Admissible - heuristic of each vertex returns a cost that is \u003c= the true cost/distance i.e. h(A) \u003c= cost(A, goal)\n * Consistent - difference between heuristics of two vertices \u003c= true cost between them i.e. h(A) - h(B) \u003c= cost(A, B)\n- Demo:https://docs.google.com/presentation/d/177bRUTdCa60fjExdr9eO04NHm0MRfPtCzvEup1iMccM/edit#slide=id.g369665031c_0_350",
"lastmodified": "2023-01-03T01:48:32.712428766Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/shortest-paths/README": {
"title": "",
"content": "# Shortest Paths\n\nWe've seen that Breadth-First Search can help us find the shortest path in an unweighted graph, where the shortest path was just defined to be the fewest number of edges traveled along a path. In the following shortest-paths algorithms, we will discover how we can generalize the breadth-first traversal to find the path with the lowest total cost, where the cost is determined by different weights on the edges.\n",
"lastmodified": "2023-01-03T01:48:32.712428766Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/shortest-paths/a-search": {
"title": "",
"content": "\n# A\\* Search\n\n{% hint style=\"warning\" %}\nIn order to understand A\\*, you'll need to review [Dijkstra's Algorithm](dijkstras-algorithm.md) first! Come back after you're done with that 😉\n{% endhint %}\n\n## A\\* Algorithm\n\nThe A\\* Search Algorithm is **incredibly similar to Dijkstra's Algorithm** with one addition: a **heuristic function.**\n\nThis heuristic function calculates weights of a path **from a vertex to a goal vertex.** This way, we can help bias our algorithm in the right direction so that it doesnt make a bunch of bad moves.\n\nThis has an important implication: **not all vertices get visited.** The algorithm only cares about finding the best path to the goal, and not any other vertex (assuming we design our heuristic well).\n\nThe **order** that the vertices get visited is lowest **distance + heuristic**. This is basically the same as Dijkstra's, just with that added heuristic term.\n\n## What's a good heuristic?\n\nHeuristic functions can be really tricky to design, since there isn't much to go off of.\n\n**A good heuristic has these two properties:**\n\n* **Admissible** - heuristic of each vertex returns a cost that is \u003c= the true cost/distance i.e. h(A) \u003c= cost(A, goal)\n* **Consistent** - difference between heuristics of two vertices \u003c= true cost between them i.e. h(A) - h(B) \u003c= cost(A, B)\n\n## **Want more?**\n\n[Here's a cool demo!](https://docs.google.com/presentation/d/177bRUTdCa60fjExdr9eO04NHm0MRfPtCzvEup1iMccM/edit#slide=id.g369665031c\\_0\\_350)\n\n",
"lastmodified": "2023-01-03T01:48:32.712428766Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/algorithms/shortest-paths/dijkstras-algorithm": {
"title": "",
"content": "\n# Dijkstra's Algorithm\n\n{% hint style=\"warning\" %}\nBefore continuing, make sure you're comfortable with [Graphs](../../abstract-data-types/graphs.md), [Stacks and Queues](../../abstract-data-types/collections/stacks-and-queues.md), and [Shortest Paths](./).\n{% endhint %}\n\n## One sentence overview\n\nVisit vertices in order of best-known distance from source; on visit, relax every edge from the visited vertex.\n\n## Detailed Breakdown\n\nDjikstras uses a **PriorityQueue** to maintain the path with lowest cost from the starting node to every other node, an **edgeTo** array to keep track of the best known predecessor for each vertex, and a **distTo** array to keep track of the best known distance from the source vertex to every other vertex.\n\n**Relaxing** the edges of a vertex v just refers to the process of updating edgeTo\\[n] for each neighbor n to v.\n\nYou'll see in the pseudocode and diagrams below that succesful relaxation only occurs when the edge connecting the vertex being visited to one of its neighbors yields a smaller total distance than the current shortest path to that neighboring vertex that the algorithm has seen.\n\nNow, here's a demonstration on how it works! Let's start out with this graph:\n\n![](\u003c../../img/assets/image (92).png\u003e)\n\nWe'll start at node A and try to figure out the shortest path from A to each node. Since we have no idea how far each node is, we'll take the conservative guess that everything is infinitely far away 😎\n\nThe first thing we have to do is update A's adjacent nodes, which are **B** and **D**. Since there's only one known path to each, it shouldn't be too hard to see why we need to update the values below. One thing to note is that the priority queue **sorts the vertices by the distance it takes to get there.**\n\n![](\u003c../../img/assets/image (93).png\u003e)\n\nNow, we have a choice to move on to either **B** or **D**. Since B has a **shorter distance,** we'll move on to that first. When we move on, we have to **remove that value from the priority queue** and **update all of its neighbors.** Here, we see that going from **B to D** is **shorter** than **A to D**, so we have to **update distTo AND edgeTo of D** to reflect this new, shorter path. **This process** (updating each adjacent node) **is called relaxing the edges of a node.**\n\n![](\u003c../../img/assets/image (94).png\u003e)\n\nNow, let's move onto **D** since it has the next shortest path. Again, we **remove D from the priority queue** and **relax C** since we found a shorter path.\n\n![](\u003c../../img/assets/image (95).png\u003e)\n\nFinally, we'll move onto **C** as that has the next shortest path in the priority queue. This will reveal our final node, **E**.\n\n![](\u003c../../img/assets/image (96).png\u003e)\n\nSince **the priority queue is now empty,** our search is done! 😄 Here's what the final solution looks like **in a tree form**:\n\n![Dijkstra's Algorithm ALWAYS produces a solution in a tree format.](\u003c../../img/assets/image (98).png\u003e)\n\nIt's a very spindly tree indeed, but hopefully it demonstrates that the result is **acyclic**.\n\n## Properties of Dijkstra's Algorithm\n\n**Dijkstra's Algorithm has some invariants (things that must always be true):**\n\n1. edgeTo\\[v] always contains best known predecessor for v\n2. distTo\\[v] contains best known distance from source to v\n3. PQ contains all unvisited vertices in order of distTo\n\n**Additionally, there are some properties that are good to know:**\n\n* always visits vertices **in order of total distance from source**\n* relaxation always **fails on edges to visited vertices**\n* guarantees to work optimally **as long as** **edges are all non-negative**\n* solution always creates a **tree form.**\n* can think of as **union of shortest paths to all vertices**\n* **edges in solution tree always has V-1 edges**, where V = the number of vertices. This is because every vertex in the tree except the root should have **exactly one input.**\n\n## Pseudocode\n\n```java\npublic Class Djikstra() {\n\n
"lastmodified": "2023-01-03T01:48:32.712428766Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/asymptotics/amortization": {
"title": "",
"content": "# Amortization\n\n{% hint style=\"warning\" %}\nPlease read [Asymptotic Analysis Basics](asymptotics.md) first. If you don't, none of this will make any sense!\n{% endhint %}\n\n**Amortization** means **spreading out.**\n\nSometimes, an operation takes different amounts of time for different values of $n$. Rather than having to report runtimes for each different case, we can instead average all of them out and report the **amortized runtime.**\n\nThis is especially good for functions where most actions have a low cost, but a few have a high cost. We'll see an example of this further down the page!\n\n## A Case Study: Resizing Arrays\n\nAs you probably know, normal Java arrays don't resize. If we create a `new int[5]` then that array will always have a length of 5.\n\nBut what if we wanted to make an array resize itself every time it reaches capacity? (Like a `List`!) Let's see what happens when we **add one to the array size:**\n\nFirst, we have to make a new array with a new size:\n\n![Example Images](notes/cs61b/img/assets/0.png)\n![Example Images](notes/images/github-actions.png)\n\nThen, we have to copy over all of the old elements over:\n\n![](\u003c../img/assets/image (17).png\u003e)\n\nFinally, we can add in the new element!\n\n![](\u003c../img/assets/image (19).png\u003e)\n\n**Let's analyze the runtime of this operation.**\n\n* A single resizing will take $\\Theta(n)$ time**.**\n* Adding a single element will take $\\Theta(1)$ time**.**\n* Together, a single operation will take $\\Theta(n+1)$ time, which simplifies into $\\Theta(n)$ .\n* Since we're doing a n-operation n times, **the end result is a resizing function that is**$\\Theta(n^2)$. **We can do better with the power of amortization!**\n\n### **What if we doubled the size instead of adding one?**\n\n* A single resizing will take $\\Theta(2n)$ time \\_\\*\\*\\_which simplifies into $\\Theta(n)$ time.\n * We do this every time the array hits a power of 2 (2, 4, 8, 16, 32 ...).\n* Adding a single element will take $\\Theta(1)$ time.\n * We do this every time we add a new element, so in all we add n elements. Therefore, this is an\n * $\\Theta(n)$operation.\n\n**Therefore, the unsimplified function is:** $\\Theta(n + (2 + 4 + 8 ... +2^i))$ where $2^i$ is the largest power of two less than n. This might not seem clear on its own, so let's rewrite it:\n\n$\n\\theta(n + (\\frac{n}{2} + \\frac{n}{4} + ... + 8 + 4 + 2))\n$\n\nIntuitively, this looks like this:\n\n![](\u003c../img/assets/image (39).png\u003e)\n\nMathematically, it looks like this:\n\n$\nn + n\\sum_{n=1}^{n}(\\frac{1}{2})^n\n$\n\nWhich simplifies to $2n$if you recall your power series properties . **Therefore, this approach is** $\\Theta(n)$ **!!**\n\n![](\u003c../img/assets/image (116).png\u003e)\n\n\n\n\n\n",
"lastmodified": "2023-01-03T01:48:32.712428766Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/asymptotics/asymptotics": {
"title": "",
"content": "# Asymptotic Analysis Basics\n\n{% hint style=\"warning\" %}\nThis concept is a big reason why a strong math background is helpful for computer science, even when it's not obvious that there are connections! Make sure you're comfortable with Calculus concepts up to [power series](http://tutorial.math.lamar.edu/Classes/CalcII/PowerSeries.aspx).\n{% endhint %}\n\n## An Abstract Introduction to Asymptotic Analysis\n\nThe term **asymptotics,** or **asymptotic analysis,** refers to the idea of **analyzing functions when their inputs get really big.** This is like the **asymptotes** you might remember learning in math classes, where functions approach a value when they get very large inputs.\n\n![](\u003c../img/assets/image (13).png\u003e)\n\nHere, we can see that $y= \\dfrac{x^3}{x^2 + 1}$ looks basically identical to $y = x$ when x gets really big. Asymptotics is all about reducing functions to their eventual behaviors exactly like this!\n\n## That's cool, but how is it useful?\n\nGraphs and functions are great and all, but at this point it's still a mystery as to how we can use these concepts for more practical uses. Now, we'll see how we can **represent programs as mathematical functions** so that we can do cool things like:\n\n* **Figure out how much time or space a program will use**\n* **Objectively tell how one program is better than another program**\n* **Choose the optimal data structures for a specific purpose**\n\nAs you can see, this concept is **absolutely fundamental** to ensuring that you write **efficient algorithms** and choose the **correct data structures.** With the power of asymptotics, you can figure out if a program will take 100 seconds or 100 years to run without actually running it!\n\n## How to Measure Programs\n\nIn order to convert your `public static void Main(String[] args)` or whatever into `y = log(x)`, we need to figure out what `x` and `y` even represent!\n\n**TLDR:** It depends, but the three most common measurements are **time, space,** and **complexity**.\n\n**Time** is almost always useful to minimize because it could mean the difference between a program being able to run on a smartphone and needing a supercomputer. Time usually increases with the **number of operations** being run. Loops and recursion will increase this metric substantially. On Linux, the `time` command can be used for measuring this.\n\n**Space** is also often nice to reduce, but has become a smaller concern now that we can get terabytes (or even petabytes) of storage pretty easily! Usually, the things that take up lots of space are **big lists** and **a very large number of individual objects.** Reducing the size of lists to hold only what you need will be very helpful for this metric!\n\nThere is another common metric, which is known as **complexity** or **computational cost.** This is a less concrete concept compared to time or space, and cannot be measured easily; however, it is highly generalized and usually easier to think about. For complexity, we can simply assign basic operations (like println, adding, absolute value) a complexity of **1** and add up how many basic operation calls there are in a program.\n\n## Simplifying Functions\n\nSince we **only care about the general shape of the function,** we can keep things as simple as possible! Here are the main rules:\n\n* **Only keep the** **fastest growing term.** For example, $log(n) + n$ can be simplified to just $n$since $n$ grows faster out of the two terms.\n* **Remove all constants.** For example, $5log(3n)$ can just be simplified to $log(n)$since constants don't change the overall shape of a function.\n* **Remove all other variables.** If a function is really $log(n + m)$ but we only care about n, then we can simply it into $log(n)$.\n\nThere are two cases where we can't remove other variables and constants though, and they are:\n\n* A polynomial term $n^c$(because $n^2$grows slower than $n^3$, for example), and\n* An exponential term $c^n$(because $2^n$grows slower than $3^n$, for example).\n\n## The Big Bounds\n\nThere are **three**
"lastmodified": "2023-01-03T01:48:32.712428766Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/asymptotics/asymptotics-practice": {
"title": "",
"content": "# Asymptotics Practice\n\n{% hint style=\"warning\" %}\nMake sure to review [Asymptotic Analysis Basics](asymptotics.md) before proceeding with these problems.\n{% endhint %}\n\n## Introduction\n\nAsymptotics is a very intuition-based concept that often doesn't have a set algorithm for computing. The best way to get good at analyzing programs is to practice!\n\nWith that said, here are some problems of increasing difficulty for you to enjoy 😊\n\n{% hint style=\"info\" %}\nFor all of the below problems, assume that all undefined functions have a constant O(1) complexity.\n{% endhint %}\n\n## Loops\n\n{% tabs %}\n{% tab title=\"Question 1\" %}\nWhat runtime does this function have?\n\n```java\nvoid throwHalfOfMyItems(int n) {\n for (int i = 0; i \u003c n; i += 1) {\n if (i % 2 == 0)\n throwItem(n);\n }\n}\n```\n{% endtab %}\n\n{% tab title=\"Q1 Answer\" %}\n$\n\\Theta(n)\n$\n\n**Explanation:** The method `throwItem()` runs `n/2` times. Using the simplification rules, we can extract the constant `1/2` to simply get `n`.\n\n![Keep the change, ya filthy animal.](\u003c../img/assets/image (40).png\u003e)\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Question 2a\" %}\nWhat runtime does this function have?\n\n```java\nvoid lootShulkerBoxes(int n) {\n for (int box = n; box \u003e 0; box -= 1) {\n for (int stack = 0; stack \u003c n; stack += 1) {\n for (int i = 0; i \u003c 64; i += 1) {\n lootItem(i * stack * box);\n }\n }\n } \n}\n```\n{% endtab %}\n\n{% tab title=\"Q2a Answer\" %}\n$\n\\Theta(n^2)\n$\n\n**Explanation:** There are **three** nested loops in this problem. Whenever there are nested loops whose runtimes are independent of each other, we need to **multiply** the runtimes in each loop.\\\nSo, we get: $\\Theta(n * n * 64)$ which simplifies into `n^2`\n\n![That's a lot of items to loot...](\u003c../img/assets/image (41).png\u003e)\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Question 2b\" %}\nI've tweaked the previous problem a little 😁 Try to spot the difference and see if it changes the runtime at all!\n\n```java\nvoid lootShulkerBoxes(int n, int stacksToLoot) {\n for (int box = n; box \u003e 0; box -= 1) {\n for (int stack = stacksToLoot; stack \u003e 0; stack -= 1) {\n for (int i = 0; i \u003c 64; i += 1) {\n lootItem(i * stack * box);\n }\n }\n } \n}\n```\n{% endtab %}\n\n{% tab title=\"Q2b Answer\" %}\n$\n\\Theta(n)\n$\n\n**Explanation:** Even though `stacksToLoot` is a user input, we're only concerned about finding the runtime for `n` so `stacksToLoot` can be treated like a constant! Therefore, we now have $\\Theta(n * s* 64)$ where `s = stacksToLoot` which simplifies into `n`.\n\n![ok now this is getting a bit overboard](\u003c../img/assets/image (42).png\u003e)\n{% endtab %}\n{% endtabs %}\n\n## Recursion\n\nThe following two problems are inspired by [this worksheet](https://inst.eecs.berkeley.edu/\\~cs61b/sp20/materials/disc/discussion8.pdf).\n\n{% tabs %}\n{% tab title=\"Question 3\" %}\nTREEEEEEEEE recursion 🌳🌲🌴\n\n```java\nvoid plantJungleSaplings(int n) {\n if (n \u003e 0) {\n for (int i = 0; i \u003c 4; i += 1) {\n plantJungleSaplings(n - 1);\n }\n }\n}\n```\n{% endtab %}\n\n{% tab title=\"Q3 Answer\" %}\n$\n\\Theta(4^n)\n$\n\n**Explanation:** This tree recursion creates a tree with `n` layers. Each layer you go down, the number of calls multiplies by 4!\n\n![Tree diagram for method calls.](\u003c../img/assets/image (48).png\u003e)\n\nThis means that the number of calls in total will look like this:\n\n$\n\\sum_{i=1}^{n}4^i\n$\n\nAnd if you remember your power series, you'll know that this sum is equal to $4^{n+1}-1$ which simplifies into the final answer.\n\n![an image that makes you long for TreeCapacitator](\u003c../img/assets/image (49).png\u003e)\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Question 4\" %}\nLet's replace the 4 in the previous problem w
"lastmodified": "2023-01-03T01:48:32.712428766Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/misc-topics/exceptions": {
"title": "",
"content": "# Exceptions\n\n## Basics\n\nAn **exception** occurs when something unintended occurs and the interpreter must exit.\n\nWhile this might sound like a bad thing, we can often throw our own exceptions to handle known errors or edge cases more gracefully.\n\n### Exceptions in Java\n\nIn Java, there are two types of exceptions: **checked** and **unchecked.**\n\n**Checked** exceptions are handled during compile time, and are included in the method declaration. As an example:\n\n```java\npublic void openFile() throws IOException {\n ...\n}\n```\n\n* All children that override this method must also throw the same exceptions.\n\n**Unchecked** exceptions are not handled during compile time, and thus are thrown during runtime. All `Error` or `RuntimeException` types are unchecked; all other exceptions are checked. Some examples of unchecked exceptions are dividing by zero (`ArithmeticException`), or accessing an index that doesn't exist (`IndexOutOfBoundsException`).\n\n![Some of the more common Exception types in Java.](\u003c../img/assets/image (4).png\u003e)\n\n## Creating Custom Exceptions\n\nWe can use the `throw` keyword to create exceptions with custom error messages as follows:\n\n```java\npublic void divide(int a, int b) {\n if (b == 0) {\n throw new Exception(\"Error Message\");\n } else {\n return a / b;\n }\n}\n```\n\nThis is often used within a `try catch` block, as such:\n\n```java\npublic void divide2() {\n int a = 0;\n try {\n return 10 / 0;\n } catch(Exception e) {\n System.out.println(\"oops!\");\n }\n }\n```\n\nAn alternate to custom exceptions is to simply handle exception cases. For example, we can add a check to make sure a number is not zero before running a division operation.\n\n## Try/Catch/Finally Example\n\nLet's check your understanding of exception handling!\n\n```java\nstatic String tryCatchFinally() {\n try {\n System.out.println(\"trying\");\n throw new Exception();\n } catch (Exception e) {\n System.out.println(\"catching\");\n return \"done catch\";\n } finally {\n System.out.println(\"finally\");\n }\n }\n```\n\n{% tabs %}\n{% tab title=\"Q1\" %}\nWhat will be printed (and in what order) when `tryCatchFinally()` is run?\n{% endtab %}\n\n{% tab title=\"Q1 Answer\" %}\nFirst, `trying` will be printed.\n\nSince an Exception is thrown, the catch block will run next, so `catching` is printed next.\n\nSince finally blocks _always_ run regardless of result, `finally` is printed last.\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Q2\" %}\nSuppose the same code were run, but without the `catch` block. What would this code do?\n\n```java\nstatic String tryFinally() {\n try {\n System.out.println(\"trying\");\n throw new Exception();\n } finally {\n System.out.println(\"finally\");\n }\n}\n```\n{% endtab %}\n\n{% tab title=\"Q2 Answer\" %}\nIf the try block throws an uncaught Exception (i.e. if catch block does not exist or catch block does not handle the type of Exception that is thrown in the try block), Java halts execution of the try block, **executes the finally block**, then raises a runtime error.\\\n\\\nSo, the following sequence would occur:\\\n1\\. `trying` is printed.\\\n2\\. `finally` is printed.\\\n3\\. The program exits with a `RuntimeException`.\n{% endtab %}\n{% endtabs %}\n",
"lastmodified": "2023-01-03T01:48:32.944427554Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/misc-topics/modular-arithmetic": {
"title": "",
"content": "# Modular Arithmetic and Bit Manipulation\n\n{% hint style=\"warning\" %}\nMake sure you're comfortable working with binary numbers (adding, subtracting, converting to decimal) before continuing.\n{% endhint %}\n\n## Integer Types\n\nThis is an excerpt from the chart in [Java Objects](../oop/objects.md). Go there to review primitive types first!\n\n| Type | Bits | Signed | Literals |\n| ----- | ---- | ------ | ----------------------------- |\n| byte | 8 | yes | 3, (int)17 |\n| short | 16 | yes | None - must cast from int |\n| char | 16 | no | 'a', '\\n' |\n| int | 32 | yes | 123, 0100 (octal), 0xff (hex) |\n| long | 64 | yes | 123L, 0100L, 0xffL |\n\n## Signed Numbers\n\nA type is **signed** if it can be **positive** **or** **negative.** Unsigned types can _only_ be positive.\n\nIn signed types, the **first bit** is reserved for determining the sign of the number (0 is positive, 1 is negative). This means that there is one fewer bit for the actual number. For example, ints only have **31** bits for the number.\n\n### Reading negative numbers\n\nLet's say you are given a number like `10100`and want to convert it to decimal. We know that the 1 in the front means it's a negative number! However, we can't just discard that 1 and read the rest like a positive number. Instead, we have to **flip all the bits** and then **add one** to the result. So, `10100` flipped will become `01011`. Adding one will result in `01100`, which is the correct answer (12).\n\n**Why do we have to do this?** Read on to the next section to find out!\n\n## Two's Complement\n\n**Two's Complement** is a a method of storing negative numbers in a way that supports proper arithmetic. Here's how it works:\n\n1. Start with a binary number we want to negate, like `0101`, which is 5.\n2. Flip all the bits to make `1010`.\n3. Add one to make `1011`.\n\nAlthough it makes negative numbers harder to read, the benefits are much more significant- it allows addition and subtraction to work between positive and negative numbers.\n\nIf you want to see firsthand why simply flipping the signed bit doesn't work, try out some problems in [this worksheet](https://d1b10bmlvqabco.cloudfront.net/attach/k5eevxebzpj25b/jcaul3qcivh6kh/k8g51ayfl9ui/GuerillaSection2.pdf) ([solutions](https://d1b10bmlvqabco.cloudfront.net/attach/k5eevxebzpj25b/jcaul3qcivh6kh/k8g53zthgevk/GuerillaSection2Sols.pdf)).\n\n## Modular Arithmetic\n\nSince primitive types have a fixed number of bits, it is possible to **overflow** them if we add numbers that are too large. For example, if we add `01000000`(a byte) with itself, we'd need 9 bits to store the result!\n\nThis will cause lots of issues, so we use **modular arithmetic** to **wrap around to the largest negative version** and keep the number in bounds. For example, `(byte)128 == (byte)(127+1) == (byte)(-128)`**.**\n\n## Bit Operations\n\n**Mask: \u0026**\n\n* `A \u0026 B` will only keep the bits that are 1 in A **AND** B\n* Example: `00101100 \u0026 10100111 == 00100100`\n\n**Set: |**\n\n* `A | B` will keep the bits that are 1 in A **OR** B\n* Example: `00101100 | 10100111 == 10101111`\n\n**Flip: ^**\n\n* `A ^ B` will keep the bits that are 1 in A **XOR** B\n* In other words, 1 if bits are unequal in A and B, 0 otherwise\n* Example: `00101100 ^ 10100111 == 10001011`\n\n**Flip all: \\~**\n\n* `~A` will flip all the bits from 1 to 0 or 0 to 1 in A\n* Example: `~10100111 == 01011000`\n\n**Shift Left: \u003c\u003c**\n\n* `A \u003c\u003c n` will shift all bits left n places\n* All newly introduced bits are 0\n* Example: `10101101 \u003c\u003c 3 == 01001000`\n* `x \u003c\u003c n` is equal to x \\* 2^n\n\n**Arithmetic Right: \u003e\u003e**\n\n* `A \u003e\u003e n` will shift all bits **except for the signed bit** right n times\n* Newly introduced bits are the same as the signed bit\n* Example: `10101101 \u003e\u003e 3 == 11110101`\n\n**Logical Right: \u003e\u003e\u003e**\n\n* `A \u003e\u003e\u003e n` will shift ALL bits right n times
"lastmodified": "2023-01-03T01:48:32.948427532Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/misc-topics/more-resources": {
"title": "",
"content": "# More Resources\n\nHere are some more cool things to look at!\n\n* [Big O Cheat Sheet ](https://www.bigocheatsheet.com/)- complexities of sorting and common data structure operations\n* [Toptal Sorting Algorithm Animations ](https://www.toptal.com/developers/sorting-algorithms)- animations, pseudocode, and property summaries\n* [Josh Hug's 61B Playlist](https://www.youtube.com/channel/UC7FzTMO4rKvlqIyU5vwzFKQ/playlists) - concise video lectures for most 61B topics\n* [Balanced Search Demos](https://inst.eecs.berkeley.edu/\\~cs61b/sp20/materials/lectures/lect29/) - play around with balanced search structures and see how they work\n",
"lastmodified": "2023-01-03T01:48:32.948427532Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/oop/access-control": {
"title": "",
"content": "# Access Control\n\n## What is Access Control?\n\nIn Java, we can specify the **level of access** certain variables and methods have. With this power, we can show or hide these variables to other classes and references on demand!\n\nThere are **4** modifier levels that get progressively more open:\n\n* **Private:** Only this class can see it.\n* **Package Protected (the default level):** All classes in the **same package** can see it.\n* **Protected: Subclasses** (that inherit from the parent) can also see it.\n* **Public:** All classes in the program can see it.\n\n![A chart comparing the different access modifiers. The black bar is the default (\"package protected\").](\u003c../img/assets/image (5).png\u003e)\n\n## Why do we need access control?\n\nAccess control works really well with other OOP concepts to help structure programs better and make them easier to understand. Here are some of the major benefits:\n\n* Access control is **self documenting.** Usually, there's a reason for making certain variables private and others public, and no more needs to be said for that to be understood.\n* **It's safe to change private methods without worrying about breaking things.** If a method is private, we know that the only references are within the same class, so we can edit them however we want without making other classes error as well.\n* **Private/protected variables don't need to be understood by users.** If someone needs to use your program, they don't need to learn how to use any private methods since those will be hidden to them.\n\n## Practice\n\nLet's see how access control can be used to hide variables in different situations:\n\n```java\npackage P;\npublic class A {\n int def; // Variable with default access\n protected int prot; // Variable with protected access\n private int priv; // Variable with private access\n \n static class NestedA { ... }\n}\n\npublic class B extends A { ... }\n\n===================\npackage Q;\npublic class C extends P.A { ... }\n\n```\n\n{% tabs %}\n{% tab title=\"Question 1\" %}\nWhich variables can be accessed in B?\n{% endtab %}\n\n{% tab title=\"Answer\" %}\n`def` and `prot` since B is in the same package as A.\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Question 2\" %}\nWhich variables can be accessed in C?\n{% endtab %}\n\n{% tab title=\"Answer\" %}\n`prot` only, since C is in a different package but extends A.\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Question 3\" %}\nWhich variables can be accessed in NestedA?\n{% endtab %}\n\n{% tab title=\"Answer\" %}\nNone of them, because NestedA is static and cannot reference any non-static variables.\n{% endtab %}\n{% endtabs %}\n",
"lastmodified": "2023-01-03T01:48:32.948427532Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/oop/dynamic-method-selection": {
"title": "",
"content": "\n# Dynamic Method Selection\n\n{% hint style=\"warning\" %}\nThis is a **very tricky topic**. Make sure you are comfortable with [inheritance](inheritance.md) and [access control ](access-control.md)before proceeding!\n{% endhint %}\n\nInheritance is great and all, but it does have some issues. One of the biggest issues lies in overriding: **if two methods have exactly the same name and signature, which one do we call?**\n\nIn a standard use case, this is a pretty simple answer: whichever one is in the class we want! Let's look at some basic examples.\n\n```java\npublic class Dog {\n public void eat() { ... } // A\n}\n\npublic class Shiba extends Dog {\n @Override\n public void eat() { ... } // C\n}\n```\n\n{% tabs %}\n{% tab title=\"Question 1\" %}\nWhich method is called when we run**:**\n\n```java\nDog rarePupper = new Dog();\nrarePupper.eat();\n```\n{% endtab %}\n\n{% tab title=\"Q1 Answer\" %}\nIt's **A** :dog: Dog doesn't know anything about `Shiba` or any other classes, so we can just look at the Dog.\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Question 2\" %}\nWhat about when we call:\n\n```java\nShiba doge = new Shiba();\nrarePupper.eat();\n```\n{% endtab %}\n\n{% tab title=\"Q2 Answer\" %}\nThis calls **C**! This works intuitively because `Shiba` overrides `Dog` so all `Shibas` will use C instead of A.\n\n![](\u003c../img/assets/image (8).png\u003e)\n{% endtab %}\n{% endtabs %}\n\n## Things Get Wonky: Mismatched Types\n\nThere's an interesting case that actually works in Java:\n\n```java\nDog confuzzled = new Shiba();\n```\n\nWhat??? Shouldn't this error because `Dog` is incompatible with `Shiba`?\n\nIt turns out that **subclasses can be assigned to superclasses.** In other words, `Parent p = new Child()` works fine. This is really useful for things like [Interfaces](inheritance.md#interfaces) and generic [Collections](../abstract-data-types/collections/) because we might only care about using generic methods, and not the specific implementation that users chose to provide.\n\nHowever, **it is important to note that it doesn't work the other way.** `Child c = new Parent()` will error because the child might have new methods that don't exist in the parent.\n\n**Let's see how this makes inheritance really tricky:**\n\n```java\n/** The following problems are inspired by Spring 2020 Exam Prep 5. */\n\npublic class Dog {\n public void playWith(Dog d) { ... } // D\n}\n\npublic class Shiba extends Dog {\n @Override\n public void playWith(Dog d) { ... } // E\n public void playWith(Shiba s) { ... } // F\n}\n```\n\n{% tabs %}\n{% tab title=\"Question 3\" %}\nWhich method(s) run when we call:\n\n```java\nDog rarePupper = new Shiba();\nrarePupper.playWith(rarePupper); // aww rarePupper is lonely :(\n```\n{% endtab %}\n\n{% tab title=\"Q3 Answer\" %}\n**E** is called! What happens is that the **dynamic type** is chosen to **select the method from,** but the **static type** is used to **select the parameters.** `rarePupper`'s **** dynamic type is `Shiba` but its static type is `Dog` so `Shiba.playWith(Dog)` is chosen as the method.\n\n![rarePupper in action](\u003c../img/assets/image (10).png\u003e)\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Question 4\" %}\nWhich is called when we run**:**\n\n```java\nDog rarePupper = new Shiba();\nShiba doge = new Shiba();\nrarePupper.playWith(doge); // rarePupper is happy :) borks all around\n```\n{% endtab %}\n\n{% tab title=\"Q4 Answer\" %}\n**E** is called again! Bet ya didn't see that coming 😎\n\n**Why is it not F? I thought doge and rarePupper were both** `Shiba`**?**\\\n****When the compiler chooses a method, it **always** starts at the **static method.** Then, it keeps going down the inheritance tree until it hits the **dynamic method.** Since F has a **different signature** than D, it isn't an **overriding method** and thus the compiler won't see it. But E is (since it has the same signature as D), so that is why it is chosen instead.\n\n![bork bork bork :DDD](\u003c../img/assets/image (11).png\u003e)\n{% end
"lastmodified": "2023-01-03T01:48:32.948427532Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/oop/generics": {
"title": "",
"content": "# Generic Types\n\nSometimes, we want things to support **any type**, including user defined types that we don't know about! For example, it would make sense that we don't care what type we make a `List` out of, since it's just a whole bunch of objects put together.\n\nThe Java solution is **generics!** Generic types are denoted by a `\u003c\u003e` and can be appended to **methods and classes.** Here's an example with classes:\n\n```java\n/**\n * Creates a type SomeClass that takes * in a generic SomeType. SomeType can * be named anything.\n*/\npublic class SomeClass\u003cSomeType\u003e {\n private SomeType someThing;\n\n public void someMethod(SomeType stuff) {\n doStuff(stuff);\n }\n}\n\n...\n/** Creates a new instance of SomeClass, setting SomeType to String.\n We don't need to put the type on the right since it's already\n defined on the left. */\nSomeClass\u003cString\u003e aClass = new SomeClass\u003c\u003e();\n```\n\nIn this example, `SomeType` is a **Generic Type Variable** that is not a real type, but can still be used inside the class as normal.\n\nOn the other hand, `String` is an **Actual Type Argument** that replaces `SomeType` during runtime. Now, every time `SomeType` is used in `SomeClass` Java treats it exactly like a `String`.\n\n## Generic Subtypes\n\nLike in _\\*\\*_[Dynamic Method Selection](dynamic-method-selection.md), adding inheritance makes things tricky! Let's look at an example:\n\n```java\nList\u003cString\u003e LS = new ArrayList\u003cString\u003e();\nList\u003cObject\u003e LO = LS; // Line 3\nLO.add(42); // Line 4\nString s = LS.get(0); // Line 5\n```\n\n{% tabs %}\n{% tab title=\"Question 1\" %}\nWill **line 3** error?\n{% endtab %}\n\n{% tab title=\"Q1 Answer\" %}\n**No**, line 3 is valid and will not error! This is because Object is a **superclass** of String. Generics work in a very similar way to the [inheritance rules](inheritance.md).\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Question 2\" %}\nWill **line 4** error?\n{% endtab %}\n\n{% tab title=\"Q2 Answer\" %}\n**No**, line 4 is valid and will not error! This is because LO is a **list of Objects** and integers are a **subtype** of Object, as all things are.\n{% endtab %}\n{% endtabs %}\n\n{% tabs %}\n{% tab title=\"Question 3\" %}\nWill **line 5** error?\n{% endtab %}\n\n{% tab title=\"Q3 Answer\" %}\n**Yes,** line 5 will error! This is because we put 42 into LO, which is an integer. Since LO is pointing to the same object as LS, 42 is also in LS! That means we are trying to assign a String equal to an integer.\n{% endtab %}\n{% endtabs %}\n\n{% hint style=\"info\" %}\nArrays have slightly different behavior than this and will throw an `ArrayStoreException` if types are mismatched in any way.\n{% endhint %}\n\n## Type Bounds\n\nSometimes, we want to **put constraints** on what kinds of types can be passed into a generic type.\n\nOne way of doing is is to specify that a generic type must fit within a **type bound**: here, T must be some subtype of a specified type `Number`.\n\nWe can also do it the other way and specify that a type can be a **supertype** of a specified type. Both of these examples are shown below:\n\n```java\nclass SomeClass\u003cT extends Number\u003e {\n // A method that takes a type parameter T and takes any SUPERCLASS\n // of T as a list generic type.\n static \u003cT\u003e void doSomething(List\u003c? super T\u003e L) { ... }\n}\n```\n\n## Limitations of Generic Types\n\nThe biggest limitation is that **primitive types cannot be used as generic types.** For example, `List\u003cint\u003e` is invalid and will not work!\n\nOne workaround to this is to use the reference-type counterparts to primitives, such as `Integer`, `Boolean`, `Character` and so on. However, converting between these types and primitive types, which is called **autoboxing,** has significant performance penalties that must be taken into consideration.\n\nAnother limitation is that **instanceof** does not work properly with generic types. For instance, `new List\u003cX\u003e() insta
"lastmodified": "2023-01-03T01:48:32.948427532Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/oop/inheritance": {
"title": "",
"content": "# Inheritance\n\n## What is inheritance?\n\nEssentially, it's a way of putting similar objects together to **generalize behavior.** Inheritance is best used with relating **subtypes** to larger categories. For example, an :tangerine:orange **is a** fruit (so it's a **subtype** of fruit).\n\nLet's say that a supermarket named _Jrader Toe's_ asks us to simulate fruits for them in an online system. We could do it like this:\n\n![The naive approach.](../img/assets/image.png)\n\nNow, every fruit would need some of the same properties- like cost, weight, and name! So we would need to do something like:\n\n```java\npublic class Orange {\n private String name = \"Orange\";\n private int cost;\n ...\n public Orange(int cost, ...) {\n this.cost = cost;\n ...\n }\n // lots of methods\n public String getName() { ...\n```\n\nThis would be _really annoying_ to do for every single fruit. And they're all the same properties for every fruit so it would also be incredibly inefficient code-wise. **Inheritance gives a much better solution!**\n\nLet's make a **Fruit** class and have all of our fruits **inherit from** that class.\n\n![uwu inheritance is cool and good](\u003c../img/assets/image (1).png\u003e)\n\nThis does amazing things because we can just create one single Fruit class that has all of the properties we need, and simply make our specific fruits inherit those properties. (Side note: making multiple things inherit from one generic interface like this is called **polymorphism.**)\n\n```java\npublic class Fruit {\n private String name;\n private int cost;\n ...\n public Orange(String name, int cost, ...) {\n this.name = name;\n this.cost = cost;\n ...\n }\n // lots of methods\n public String getName() { ...\n}\n\n// Now for a very simple Orange method!\npublic class Orange extends Fruit {\n public Orange(int cost,...) {\n super(\"Orange\", cost, ...);\n }\n}\n```\n\nWith only those 4 lines, :tangerine:Orange now has all of the same methods and properties that Fruit has!\n\n## Implementation Inheritance (\"Extends\")\n\nYou may have noticed the `extends` keyword being used to specify that an object **inherits** from another object. This is called **implementation inheritance** since an object takes all of the behaviors from its parent and can use them like its own.\n\nWhen `extends` is used, these are the things that are inherited:\n\n* All instance and static variables that are **not private** (see [Access Control](access-control.md) for more information)\n* All non-private methods\n* All nested classes\n\nThese are **not** inherited:\n\n* Any **private** variables and methods\n* All constructors\n\n{% hint style=\"info\" %}\n**Quick sidenote!**\\\n****All objects automatically extend the `Object` class whether you like it or not. See [References, Objects, and Types in Java](objects.md) **** for more about this behavior.\n{% endhint %}\n\n### Constructor magic 🏗\n\nWhen an object `extends` another object, its constructor will **automatically call the parent's constructor.** However, this does have some limitations:\n\n* It will only call the **default** (no-argument) constructor in the parent.\n* Calling the constructor is the **first thing that is done** in the child constructor.\n\nBut what if we want to call another constructor? That's where the `super` keyword comes in! When `super` is called, Java will know to **not** call the default constructor anymore. Here's an example:\n\n```java\npublic class Parent {\n public Parent() {\n System.out.println(\"Default constructor\");\n }\n public Parent(String say) {\n System.out.println(say);\n }\n void doStuff() { ... }\n}\n\n// Child inherits doStuff(), but not the constructors.\npublic class Child extends Parent {\n public Child() {\n System.out.println(\"Child\")\n }\n public Child(String say) {\n super(say);\n }\n}\n \npublic static void Main(String[] args) {\n Child c1 = new Child(); // will print \"Default const
"lastmodified": "2023-01-03T01:48:32.948427532Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/oop/objects": {
"title": "",
"content": "# Java Objects\n\nThere are two main categories of objects in Java: **Primitive Types** and **Reference Types.** This page will give a brief overview of both, and close off with some info about the mystical **Object** class.\n\n## Primitive Types\n\n**Primitive types** are built in to Java and have **fixed memory sizes.** Different types require different amounts of memory.\n\nIf you remember [environment diagrams](http://albertwu.org/cs61a/notes/environments), you may recall that some variables are put straight into the boxes, while others have an arrow pointing to them. The reason for this is that it actually denotes primitive vs. reference types! **Primitive types go straight in the box** because they aren't mutable (i.e. you can't change the objects contained in the box since they're just constant literals like numbers).\n\n**There are 8 primitive types in Java.** Here's a table of their properties! (If you don't know what \"signed\" means, go to [Modular Arithmetic and Bit Manipulation](../misc-topics/modular-arithmetic.md).)\n\n| Type | Bits | Signed | Default | Examples |\n| ------- | ---- | ------ | ------- | ----------------------------- |\n| boolean | 1 | no | false | true, false |\n| byte | 8 | yes | 0 | 3, (int)17 |\n| short | 16 | yes | 0 | None - must cast from int |\n| char | 16 | no | \\u0000 | 'a', '\\n' |\n| int | 32 | yes | 0 | 123, 0100 (octal), 0xff (hex) |\n| long | 64 | yes | 0 | 123L, 0100L, 0xffL |\n| float | 32 | yes | 0.0 | 1.23f, -1.23e10f, .001f |\n| double | 64 | yes | 0.0 | 1.23e256d, 1e1d, 1.2e-10d |\n\n{% hint style=\"info\" %}\n**A quick aside on Strings 🧵**\\\nYou may have noticed that strings are not on this list. That is because unlike in Python, they aren't a primitive type! Under the hood, Strings are a reference type that are very similar to a char array.\n{% endhint %}\n\n## Type Conversion\n\nJava will automatically convert between primitive types if **no information is lost** (\nfrom byte to int).\n\nConversion in the other direction (from a larger to smaller container) requires an explicit cast (e.g., `(char) int`). The compiler will treat a cast object as though its static type is the cast type, but this will only work if the cast type is the same as or a parent of the dynamic type. However, relative to the assigned static type, the cast type could be a child of the static type or a parent of the static type.\n\n**Assignment statements are an exception to this**: `aByte = 10` is fine even though 10 is an int literal. This is because arithmetic operations (+, \\*, ...) automatically promote operands (e.g., `'A' + 2` is equivalent to `(int)'A' + 2`)\n\nHowever, **this doesn't work if you are trying to add a larger type to a smaller type** (e.g., `aByte = aByte + 1` since operands become an int type which cannot be set equal to a byte type. **But += works**!\n\n## Reference Types\n\nA **reference type** refers to basically anything that's not primitive 😅\n\nThis includes **user-defined objects** as well as many common Java built-in types such as **arrays, strings, and** [**collections**](../abstract-data-types/collections/)**.**\n\nHere are some major differences that set them apart from primitive types:\n\n* Reference types can take an **arbitrary amount of memory.** Unlike primitives which have a fixed memory for each type, objects like arrays can expand to hold lots of things inside it.\n* Reference types are referred to using **addresses.** When you say something like `int[] arr = new int[5]`, `arr` only stores a 64-bit **memory address** which **points** to the real object, a 5-length integer array. Again, think back to the arrow in environment diagrams, and how those work.\n* By default, reference types can be set to **null** which is represented as an **address of all zeroes.** Or, the **new** keyword can be used to set it to a specific address.\n* Re
"lastmodified": "2023-01-03T01:48:32.952427512Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/cs61b/sorting/sorting-basics": {
"title": "",
"content": "# Sorting\n\n{% hint style=\"info\" %}\nFor more information about specific sorting algorithms covered in 61B, see my [guide on sorting](https://docs.google.com/document/d/1dUfzdh5V3okrwFbB9o0PgtEBaLHyCqJFwpQWyQ53IeU/edit) that covers all of the sorts in far greater detail 🙂\n{% endhint %}\n\n## Why sort?\n\n* It makes searching for a specific value much faster (e.g. binary search). Typically, searching through an unsorted list requires a full scan ($\\Theta(N)$ runtime).\n* It's easy to see if two items in list are equal: just compare to see if any neighboring values are the same.\n\n## Properties of a Sorting Algorithm\n\nA sorting algorithm changes a sequence based on a **total order.** A total order is:\n\n* **Total:** All items can be compared with one another\n* **Reflexive:** An item can be compared to itself\n* **Antisymmetric:** x \u003c= y AND y \u003c= x IFF y == x\n* **Transitive:** If x \u003c= y and y \u003c= z, then x must be \u003c= z\n\nA sorting algorithm could be **stable** if it does not change relative order of equivalent entries. For example, if Bob and I both owned Toyota Corollas, and the list of cars were sorted by model, if Bob's car came before mine originally it must also come before mine in the sorted list after a stable sort.\n\n\n\n## Sorting Algorithm Classifications\n\n* **Internal sort:** Keeps all data in primary memory\n* vs. **External sort:** Processes data in batches, then merges them together at the end\n* **Comparison-based sort:** The only thing we know about keys are their relative orders\n* **Radix sort:** Uses information other than keys\n* **Insertion sort:** Insert items at their appropriate positions one at a time\n* **Selection sort:** Chooses items and places them in order\n\n## Sorting in Java\n\nJava automatically chooses the best sorting algorithm for a given list if you call the `Arrays.sort` method.\n\n```java\nString[] x = new String[] {\"Vat\", \"Bat\", \"Cat\"};\n\nArrays.sort(x); // mutates x into Bat, Cat, Vat\nArrays.sort(x, Collections.reverseOrder()); // mutates x into Vat, Cat, Bat\nArrays.sort(x, 0, 2) // sorts the first two elements, leaving the rest unchanged (Cat, Vat, Bat)\n```\n\n## Inversions\n\nInversions are used as a measure for how sorted a list is. For every two elements that are swapped compared to a sorted list, we add one inversion.\n\n* As an example, if `1 2 3 4 5` is a sorted list, `1 4 3 2 5` would have one inversion (`4` and `2` are swapped).\n* 0 inversions mean a list is perfectly sorted.\n* In the worst case, a reversed list will have $(N \\cdot (N-1))/2$ inversions.\n\n## The Guide to Sorting Algorithms\n\n[A comprehensive guide to sorting algorithms, now with memes!](https://docs.google.com/document/d/1dUfzdh5V3okrwFbB9o0PgtEBaLHyCqJFwpQWyQ53IeU/edit)\n",
"lastmodified": "2023-01-03T01:48:32.952427512Z",
"tags": null
},
"/example/": {
"title": "Example Site",
"content": "\n# Introduction\n\n## Ferre hinnitibus erat accipitrem dixi Troiae tollens\n\nLorem markdownum, a quoque nutu est *quodcumque mandasset* veluti. Passim\ninportuna totidemque nympha fert; repetens pendent, poenarum guttura sed vacet\nnon, mortali undas. Omnis pharetramque gramen portentificisque membris servatum\nnovabis fallit de nubibus atque silvas mihi. **Dixit repetitaque Quid**; verrit\nlonga; sententia [mandat](http://pastor-ad.io/questussilvas) quascumque nescio\nsolebat [litore](http://lacrimas-ab.net/); noctes. *Hostem haerentem* circuit\n[plenaque tamen](http://www.sine.io/in).\n\n- Pedum ne indigenae finire invergens carpebat\n- Velit posses summoque\n- De fumos illa foret\n\n## Est simul fameque tauri qua ad\n\nLocum nullus nisi vomentes. Ab Persea sermone vela, miratur aratro; eandem\nArgolicas gener.\n\n## Me sol\n\nNec dis certa fuit socer, Nonacria **dies** manet tacitaque sibi? Sucis est\niactata Castrumque iudex, et iactato quoque terraeque es tandem et maternos\nvittis. Lumina litus bene poenamque animos callem ne tuas in leones illam dea\ncadunt genus, et pleno nunc in quod. Anumque crescentesque sanguinis\n[progenies](http://www.late.net/alimentavirides) nuribus rustica tinguet. Pater\nomnes liquido creditis noctem.\n\n if (mirrored(icmp_dvd_pim, 3, smbMirroredHard) != lion(clickImportQueue,\n viralItunesBalancing, bankruptcy_file_pptp)) {\n file += ip_cybercrime_suffix;\n }\n if (runtimeSmartRom == netMarketingWord) {\n virusBalancingWin *= scriptPromptBespoke + raster(post_drive,\n windowsSli);\n cd = address_hertz_trojan;\n soap_ccd.pcbServerGigahertz(asp_hardware_isa, offlinePeopleware, nui);\n } else {\n megabyte.api = modem_flowchart - web + syntaxHalftoneAddress;\n }\n if (3 \u003c mebibyteNetworkAnimated) {\n pharming_regular_error *= jsp_ribbon + algorithm * recycleMediaKindle(\n dvrSyntax, cdma);\n adf_sla *= hoverCropDrive;\n templateNtfs = -1 - vertical;\n } else {\n expressionCompressionVariable.bootMulti = white_eup_javascript(\n table_suffix);\n guidPpiPram.tracerouteLinux += rtfTerabyteQuicktime(1,\n managementRosetta(webcamActivex), 740874);\n }\n var virusTweetSsl = nullGigo;\n\n## Trepident sitimque\n\nSentiet et ferali errorem fessam, coercet superbus, Ascaniumque in pennis\nmediis; dolor? Vidit imi **Aeacon** perfida propositos adde, tua Somni Fluctibus\nerrante lustrat non.\n\nTamen inde, vos videt e flammis Scythica parantem rupisque pectora umbras. Haec\nficta canistris repercusso simul ego aris Dixit! Esse Fama trepidare hunc\ncrescendo vigor ululasse vertice *exspatiantur* celer tepidique petita aversata\noculis iussa est me ferro.\n",
"lastmodified": "2023-01-05T06:42:56.243187075Z",
"tags": null
},
"/example/collapsed/": {
"title": "",
"content": "\nHello World",
"lastmodified": "2023-01-05T06:46:52.921570456Z",
"tags": null
},
"/example/collapsed/3rd-level/": {
"title": "",
"content": "# 3rd Level of Menu\n\nNefas discordemque domino montes numen tum humili nexilibusque exit, Iove. Quae\nmiror esse, scelerisque Melaneus viribus. Miseri laurus. Hoc est proposita me\nante aliquid, aura inponere candidioribus quidque accendit bella, sumpta.\nIntravit quam erat figentem hunc, motus de fontes parvo tempestate.\n\n```c\n iscsi_virus = pitch(json_in_on(eupViral),\n northbridge_services_troubleshooting, personal(\n firmware_rw.trash_rw_crm.device(interactive_gopher_personal,\n software, -1), megabit, ergonomicsSoftware(cmyk_usb_panel,\n mips_whitelist_duplex, cpa)));\n if (5) {\n managementNetwork += dma - boolean;\n kilohertz_token = 2;\n honeypot_affiliate_ergonomics = fiber;\n }\n mouseNorthbridge = byte(nybble_xmp_modem.horse_subnet(\n analogThroughputService * graphicPoint, drop(daw_bit, dnsIntranet),\n gateway_ospf), repository.domain_key.mouse(serverData(fileNetwork,\n trim_duplex_file), cellTapeDirect, token_tooltip_mashup(\n ripcordingMashup)));\n module_it = honeypot_driver(client_cold_dvr(593902, ripping_frequency) +\n coreLog.joystick(componentUdpLink), windows_expansion_touchscreen);\n bashGigabit.external.reality(2, server_hardware_codec.flops.ebookSampling(\n ciscNavigationBacklink, table + cleanDriver), indexProtocolIsp);\n```",
"lastmodified": "2023-01-05T06:45:27.266216591Z",
"tags": null
},
"/example/collapsed/3rd-level/4th-level": {
"title": "",
"content": "# 4th Level of Menu\n\n## Caesorum illa tu sentit micat vestes papyriferi\n\nInde aderam facti; Theseus vis de tauri illa peream. Oculos **uberaque** non\nregisque vobis cursuque, opus venit quam vulnera. Et maiora necemque, lege modo;\ngestanda nitidi, vero? Dum ne pectoraque testantur.\n\nVenasque repulsa Samos qui, exspectatum eram animosque hinc, [aut\nmanes](http://www.creveratnon.net/apricaaetheriis), Assyrii. Cupiens auctoribus\npariter rubet, profana magni super nocens. Vos ius sibilat inpar turba visae\niusto! Sedes ante dum superest **extrema**.\n",
"lastmodified": "2023-01-05T06:31:25.827295646Z",
"tags": null
},
"/example/hidden": {
"title": "",
"content": "\n# This page is hidden in menu\n\n# Quondam non pater est dignior ille Eurotas\n\n## Latent te facies\n\nLorem markdownum arma ignoscas vocavit quoque ille texit mandata mentis ultimus,\nfrementes, qui in vel. Hippotades Peleus [pennas\nconscia](http://gratia.net/tot-qua.php) cuiquam Caeneus quas.\n\n- Pater demittere evincitque reddunt\n- Maxime adhuc pressit huc Danaas quid freta\n- Soror ego\n- Luctus linguam saxa ultroque prior Tatiumque inquit\n- Saepe liquitur subita superata dederat Anius sudor\n\n## Cum honorum Latona\n\nO fallor [in sustinui\niussorum](http://www.spectataharundine.org/aquas-relinquit.html) equidem.\nNymphae operi oris alii fronde parens dumque, in auro ait mox ingenti proxima\niamdudum maius?\n\n reality(burnDocking(apache_nanometer),\n pad.property_data_programming.sectorBrowserPpga(dataMask, 37,\n recycleRup));\n intellectualVaporwareUser += -5 * 4;\n traceroute_key_upnp /= lag_optical(android.smb(thyristorTftp));\n surge_host_golden = mca_compact_device(dual_dpi_opengl, 33,\n commerce_add_ppc);\n if (lun_ipv) {\n verticalExtranet(1, thumbnail_ttl, 3);\n bar_graphics_jpeg(chipset - sector_xmp_beta);\n }\n\n## Fronde cetera dextrae sequens pennis voce muneris\n\nActa cretus diem restet utque; move integer, oscula non inspirat, noctisque\nscelus! Nantemque in suas vobis quamvis, et labori!\n\n var runtimeDiskCompiler = home - array_ad_software;\n if (internic \u003e disk) {\n emoticonLockCron += 37 + bps - 4;\n wan_ansi_honeypot.cardGigaflops = artificialStorageCgi;\n simplex -= downloadAccess;\n }\n var volumeHardeningAndroid = pixel + tftp + onProcessorUnmount;\n sector(memory(firewire + interlaced, wired));",
"lastmodified": "2023-01-05T06:31:25.827295646Z",
"tags": null
},
"/example/table-of-contents/": {
"title": "Table of Contents",
"content": "\n# Ubi loqui\n\n## Mentem genus facietque salire tempus bracchia\n\nLorem markdownum partu paterno Achillem. Habent amne generosi aderant ad pellem\nnec erat sustinet merces columque haec et, dixit minus nutrit accipiam subibis\nsubdidit. Temeraria servatum agros qui sed fulva facta. Primum ultima, dedit,\nsuo quisque linguae medentes fixo: tum petis.\n\n## Rapit vocant si hunc siste adspice\n\nOra precari Patraeque Neptunia, dixit Danae [Cithaeron\narmaque](http://mersis-an.org/litoristum) maxima in **nati Coniugis** templis\nfluidove. Effugit usus nec ingreditur agmen *ac manus* conlato. Nullis vagis\nnequiquam vultibus aliquos altera *suum venis* teneas fretum. Armos [remotis\nhoc](http://tutum.io/me) sine ferrea iuncta quam!\n\n## Locus fuit caecis\n\nNefas discordemque domino montes numen tum humili nexilibusque exit, Iove. Quae\nmiror esse, scelerisque Melaneus viribus. Miseri laurus. Hoc est proposita me\nante aliquid, aura inponere candidioribus quidque accendit bella, sumpta.\nIntravit quam erat figentem hunc, motus de fontes parvo tempestate.\n\n iscsi_virus = pitch(json_in_on(eupViral),\n northbridge_services_troubleshooting, personal(\n firmware_rw.trash_rw_crm.device(interactive_gopher_personal,\n software, -1), megabit, ergonomicsSoftware(cmyk_usb_panel,\n mips_whitelist_duplex, cpa)));\n if (5) {\n managementNetwork += dma - boolean;\n kilohertz_token = 2;\n honeypot_affiliate_ergonomics = fiber;\n }\n mouseNorthbridge = byte(nybble_xmp_modem.horse_subnet(\n analogThroughputService * graphicPoint, drop(daw_bit, dnsIntranet),\n gateway_ospf), repository.domain_key.mouse(serverData(fileNetwork,\n trim_duplex_file), cellTapeDirect, token_tooltip_mashup(\n ripcordingMashup)));\n module_it = honeypot_driver(client_cold_dvr(593902, ripping_frequency) +\n coreLog.joystick(componentUdpLink), windows_expansion_touchscreen);\n bashGigabit.external.reality(2, server_hardware_codec.flops.ebookSampling(\n ciscNavigationBacklink, table + cleanDriver), indexProtocolIsp);\n\n## Placabilis coactis nega ingemuit ignoscat nimia non\n\nFrontis turba. Oculi gravis est Delphice; *inque praedaque* sanguine manu non.\n\n if (ad_api) {\n zif += usb.tiffAvatarRate(subnet, digital_rt) + exploitDrive;\n gigaflops(2 - bluetooth, edi_asp_memory.gopher(queryCursor, laptop),\n panel_point_firmware);\n spyware_bash.statePopApplet = express_netbios_digital(\n insertion_troubleshooting.brouter(recordFolderUs), 65);\n }\n recursionCoreRay = -5;\n if (hub == non) {\n portBoxVirus = soundWeb(recursive_card(rwTechnologyLeopard),\n font_radcab, guidCmsScalable + reciprocalMatrixPim);\n left.bug = screenshot;\n } else {\n tooltipOpacity = raw_process_permalink(webcamFontUser, -1);\n executable_router += tape;\n }\n if (tft) {\n bandwidthWeb *= social_page;\n } else {\n regular += 611883;\n thumbnail /= system_lag_keyboard;\n }\n\n## Caesorum illa tu sentit micat vestes papyriferi\n\nInde aderam facti; Theseus vis de tauri illa peream. Oculos **uberaque** non\nregisque vobis cursuque, opus venit quam vulnera. Et maiora necemque, lege modo;\ngestanda nitidi, vero? Dum ne pectoraque testantur.\n\nVenasque repulsa Samos qui, exspectatum eram animosque hinc, [aut\nmanes](http://www.creveratnon.net/apricaaetheriis), Assyrii. Cupiens auctoribus\npariter rubet, profana magni super nocens. Vos ius sibilat inpar turba visae\niusto! Sedes ante dum superest **extrema**.\n",
"lastmodified": "2023-01-05T06:31:25.827295646Z",
"tags": null
},
"/example/table-of-contents/with-toc": {
"title": "With ToC",
"content": "# Caput vino delphine in tamen vias\n\n## Cognita laeva illo fracta\n\nLorem markdownum pavent auras, surgit nunc cingentibus libet **Laomedonque que**\nest. Pastor [An](http://est.org/ire.aspx) arbor filia foedat, ne [fugit\naliter](http://www.indiciumturbam.org/moramquid.php), per. Helicona illas et\ncallida neptem est *Oresitrophos* caput, dentibus est venit. Tenet reddite\n[famuli](http://www.antro-et.net/) praesentem fortibus, quaeque vis foret si\nfrondes *gelidos* gravidae circumtulit [inpulit armenta\nnativum](http://incurvasustulit.io/illi-virtute.html).\n\n1. Te at cruciabere vides rubentis manebo\n2. Maturuit in praetemptat ruborem ignara postquam habitasse\n3. Subitarum supplevit quoque fontesque venabula spretis modo\n4. Montis tot est mali quasque gravis\n5. Quinquennem domus arsit ipse\n6. Pellem turis pugnabant locavit\n\n## Natus quaerere\n\nPectora et sine mulcere, coniuge dum tincta incurvae. Quis iam; est dextra\nPeneosque, metuis a verba, primo. Illa sed colloque suis: magno: gramen, aera\nexcutiunt concipit.\n\n\u003e Phrygiae petendo suisque extimuit, super, pars quod audet! Turba negarem.\n\u003e Fuerat attonitus; et dextra retinet sidera ulnas undas instimulat vacuae\n\u003e generis? *Agnus* dabat et ignotis dextera, sic tibi pacis **feriente at mora**\n\u003e euhoeque *comites hostem* vestras Phineus. Vultuque sanguine dominoque [metuit\n\u003e risi](http://iuvat.org/eundem.php) fama vergit summaque meus clarissimus\n\u003e artesque tinguebat successor nominis cervice caelicolae.\n\n## Limitibus misere sit\n\nAurea non fata repertis praerupit feruntur simul, meae hosti lentaque *citius\nlevibus*, cum sede dixit, Phaethon texta. *Albentibus summos* multifidasque\niungitur loquendi an pectore, mihi ursaque omnia adfata, aeno parvumque in animi\nperlucentes. Epytus agis ait vixque clamat ornum adversam spondet, quid sceptra\nipsum **est**. Reseret nec; saeva suo passu debentia linguam terga et aures et\ncervix [de](http://www.amnem.io/pervenit.aspx) ubera. Coercet gelidumque manus,\ndoluit volvitur induta?\n\n## Enim sua\n\nIuvenilior filia inlustre templa quidem herbis permittat trahens huic. In\ncruribus proceres sole crescitque *fata*, quos quos; merui maris se non tamen\nin, mea.\n\n## Germana aves pignus tecta\n\nMortalia rudibusque caelum cognosceret tantum aquis redito felicior texit, nec,\naris parvo acre. Me parum contulerant multi tenentem, gratissime suis; vultum tu\noccupat deficeret corpora, sonum. E Actaea inplevit Phinea concepit nomenque\npotest sanguine captam nulla et, in duxisses campis non; mercede. Dicere cur\nLeucothoen obitum?\n\nPostibus mittam est *nubibus principium pluma*, exsecratur facta et. Iunge\nMnemonidas pallamque pars; vere restitit alis flumina quae **quoque**, est\nignara infestus Pyrrha. Di ducis terris maculatum At sede praemia manes\nnullaque!\n",
"lastmodified": "2023-01-05T06:31:25.831295598Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/example/table-of-contents/without-toc": {
"title": "Without ToC",
"content": "\n# At me ipso nepotibus nunc celebratior genus\n\n## Tanto oblite\n\nLorem markdownum pectora novis patenti igne sua opus aurae feras materiaque\nillic demersit imago et aristas questaque posset. Vomit quoque suo inhaesuro\nclara. Esse cumque, per referri triste. Ut exponit solisque communis in tendens\nvincetis agisque iamque huic bene ante vetat omina Thebae rates. Aeacus servat\nadmonitu concidit, ad resimas vultus et rugas vultu **dignamque** Siphnon.\n\nQuam iugulum regia simulacra, plus meruit humo pecorumque haesit, ab discedunt\ndixit: ritu pharetramque. Exul Laurenti orantem modo, per densum missisque labor\nmanibus non colla unum, obiectat. Tu pervia collo, fessus quae Cretenque Myconon\ncrate! Tegumenque quae invisi sudore per vocari quaque plus ventis fluidos. Nodo\nperque, fugisse pectora sorores.\n\n## Summe promissa supple vadit lenius\n\nQuibus largis latebris aethera versato est, ait sentiat faciemque. Aequata alis\nnec Caeneus exululat inclite corpus est, ire **tibi** ostendens et tibi. Rigent\net vires dique possent lumina; **eadem** dixit poma funeribus paret et felix\nreddebant ventis utile lignum.\n\n1. Remansit notam Stygia feroxque\n2. Et dabit materna\n3. Vipereas Phrygiaeque umbram sollicito cruore conlucere suus\n4. Quarum Elis corniger\n5. Nec ieiunia dixit\n\nVertitur mos ortu ramosam contudit dumque; placabat ac lumen. Coniunx Amoris\nspatium poenamque cavernis Thebae Pleiadasque ponunt, rapiare cum quae parum\nnimium rima.\n\n## Quidem resupinus inducto solebat una facinus quae\n\nCredulitas iniqua praepetibus paruit prospexit, voce poena, sub rupit sinuatur,\nquin suum ventorumque arcadiae priori. Soporiferam erat formamque, fecit,\ninvergens, nymphae mutat fessas ait finge.\n\n1. Baculum mandataque ne addere capiti violentior\n2. Altera duas quam hoc ille tenues inquit\n3. Sicula sidereus latrantis domoque ratae polluit comites\n4. Possit oro clausura namque se nunc iuvenisque\n5. Faciem posuit\n6. Quodque cum ponunt novercae nata vestrae aratra\n\nIte extrema Phrygiis, patre dentibus, tonso perculit, enim blanda, manibus fide\nquos caput armis, posse! Nocendo fas Alcyonae lacertis structa ferarum manus\nfulmen dubius, saxa caelum effuge extremis fixum tumor adfecit **bella**,\npotentes? Dum nec insidiosa tempora tegit\n[spirarunt](http://mihiferre.net/iuvenes-peto.html). Per lupi pars foliis,\nporreximus humum negant sunt subposuere Sidone steterant auro. Memoraverit sine:\nferrum idem Orion caelum heres gerebat fixis?\n",
"lastmodified": "2023-01-05T06:31:25.831295598Z",
"tags": null
},
"/features/": {
"title": "",
"content": "",
2023-01-05 01:58:53 -05:00
"lastmodified": "2023-01-05T06:46:04.145945884Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/features/buttons": {
"title": "",
"content": "# Buttons\n\nButtons are styled links that can lead to local page or external link.\n\n## Example\n\n```tpl\n{{\u003c/* button relref=\"/\" [class=\"...\"] */\u003e}}Get Home{{\u003c/* /button */\u003e}}\n{{\u003c/* button href=\"https://github.com/alex-shpak/hugo-book\" */\u003e}}Contribute{{\u003c/* /button */\u003e}}\n```\n\n{{\u003c button relref=\"/\" \u003e}}Get Home{{\u003c /button \u003e}}\n{{\u003c button href=\"https://github.com/alex-shpak/hugo-book\" \u003e}}Contribute{{\u003c /button \u003e}}\n",
"lastmodified": "2023-01-05T06:31:25.831295598Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/features/callouts": {
"title": "Callouts",
"content": "\n## Callout support\n\nAmethyst supports the same Admonition-callout syntax as Obsidian.\n\nThis includes\n- 12 Distinct callout types (each with several aliases)\n- Collapsable callouts\n\nSee [documentation on supported types and syntax here](https://help.obsidian.md/How+to/Use+callouts#Types).\n\n## Showcase\n\n\u003e [!EXAMPLE] Examples\n\u003e\n\u003e Aliases: example\n\n\u003e [!note] Notes\n\u003e\n\u003e Aliases: note\n\n\u003e [!abstract] Summaries \n\u003e\n\u003e Aliases: abstract, summary, tldr\n\n\u003e [!info] Info \n\u003e\n\u003e Aliases: info, todo\n\n\u003e [!tip] Hint \n\u003e\n\u003e Aliases: tip, hint, important\n\n\u003e [!success] Success \n\u003e\n\u003e Aliases: success, check, done\n\n\u003e [!question] Question \n\u003e\n\u003e Aliases: question, help, faq\n\n\u003e [!warning] Warning \n\u003e\n\u003e Aliases: warning, caution, attention\n\n\u003e [!failure] Failure \n\u003e\n\u003e Aliases: failure, fail, missing\n\n\u003e [!danger] Error\n\u003e\n\u003e Aliases: danger, error\n\n\u003e [!bug] Bug\n\u003e\n\u003e Aliases: bug\n\n\u003e [!quote] Quote\n\u003e\n\u003e Aliases: quote, cite\n",
"lastmodified": "2023-01-05T20:50:35.878992838Z",
2023-01-05 01:58:53 -05:00
"tags": null
},
"/features/columns": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Columns\n\nColumns help organize shorter pieces of content horizontally for readability.\n\n\n```html\n{{\u003c/* columns */\u003e}} \u003c!-- begin columns block --\u003e\n# Left Content\nLorem markdownum insigne...\n\n\u003c---\u003e \u003c!-- magic separator, between columns --\u003e\n\n# Mid Content\nLorem markdownum insigne...\n\n\u003c---\u003e \u003c!-- magic separator, between columns --\u003e\n\n# Right Content\nLorem markdownum insigne...\n{{\u003c/* /columns */\u003e}}\n```\n\n## Example\n\n{{\u003c columns \u003e}}\n## Left Content\nLorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat\nstringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa\nprotulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes.\nMiseratus fonte Ditis conubia.\n\n\u003c---\u003e\n\n## Mid Content\nLorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat\nstringit, frustra Saturnius uteroque inter!\n\n\u003c---\u003e\n\n## Right Content\nLorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat\nstringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa\nprotulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes.\nMiseratus fonte Ditis conubia.\n{{\u003c /columns \u003e}}\n",
"lastmodified": "2023-01-05T06:31:25.831295598Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/features/details": {
"title": "",
2023-01-05 01:58:53 -05:00
"content": "# Details\n\nDetails shortcode is a helper for `details` html5 element. It is going to replace `expand` shortcode.\n\n## Example\n```tpl\n{{\u003c/* details \"Title\" [open] */\u003e}}\n## Markdown content\nLorem markdownum insigne...\n{{\u003c/* /details */\u003e}}\n```\n```tpl\n{{\u003c/* details title=\"Title\" open=true */\u003e}}\n## Markdown content\nLorem markdownum insigne...\n{{\u003c/* /details */\u003e}}\n```\n\n{{\u003c details \"Title\" open \u003e}}\n## Markdown content\nLorem markdownum insigne...\n{{\u003c /details \u003e}}\n",
"lastmodified": "2023-01-05T06:31:25.831295598Z",
"tags": null
},
2023-01-05 01:58:53 -05:00
"/features/expand": {
"title": "",
"content": "# Expand\n\nExpand shortcode can help to decrease clutter on screen by hiding part of text. Expand content by clicking on it.\n\n## Example\n### Default\n\n```tpl\n{{\u003c/* expand */\u003e}}\n## Markdown content\nLorem markdownum insigne...\n{{\u003c/* /expand */\u003e}}\n```\n\n{{\u003c expand \u003e}}\n## Markdown content\nLorem markdownum insigne...\n{{\u003c /expand \u003e}}\n\n### With Custom Label\n\n```tpl\n{{\u003c/* expand \"Custom Label\" \"...\" */\u003e}}\n## Markdown content\nLorem markdownum insigne...\n{{\u003c/* /expand */\u003e}}\n```\n\n{{\u003c expand \"Custom Label\" \"...\" \u003e}}\n## Markdown content\nLorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat\nstringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa\nprotulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes.\nMiseratus fonte Ditis conubia.\n{{\u003c /expand \u003e}}\n",
"lastmodified": "2023-01-05T06:31:25.831295598Z",
"tags": null
},
"/features/languages": {
"title": "Chinese, Japanese, Korean Support (测试)",
"content": "\n## Chinese, Japanese, Korean Support\n几乎在我们意识到之前我们已经离开了地面。\n\n우리가 그것을 알기도 전에 우리는 땅을 떠났습니다.\n\n私たちがそれを知るほぼ前に、私たちは地面を離れていました。\n\n## RTL\nMore information on configuring RTL languages like Arabic in the [config](setup/config.md) page.\n",
"lastmodified": "2023-01-05T07:07:59.452468939Z",
2023-01-05 01:58:53 -05:00
"tags": null
},
"/features/latex": {
"title": "LaTeX",
"content": "\nBlock math works with two dollar signs `$$...$$`\n\n$$f(x) = \\int_{-\\infty}^\\infty\n f\\hat(\\xi),e^{2 \\pi i \\xi x}\n \\,d\\xi$$\n\t\nInline math also works with single dollar signs `$...$`. For example, Euler's identity but inline: $e^{i\\pi} = -1$\n\nAligned equations work quite well:\n\n$$\n\\begin{aligned}\na \u0026= b + c \\\\ \u0026= e + f \\\\\n\\end{aligned}\n$$\n\nAnd matrices\n\n$$\n\\begin{bmatrix}\n1 \u0026 2 \u0026 3 \\\\\na \u0026 b \u0026 c\n\\end{bmatrix}\n$$",
"lastmodified": "2023-01-05T06:49:47.80008656Z",
"tags": null
},
"/features/mermaid": {
"title": "",
"content": "# Mermaid Chart\n\n[MermaidJS](https://mermaid-js.github.io/) is library for generating svg charts and diagrams from text.\n\n{{\u003c hint info \u003e}}\n**Override Mermaid Initialization Config**\n\nTo override the [initialization config](https://mermaid-js.github.io/mermaid/#/Setup) for Mermaid,\ncreate a `mermaid.json` file in your `assets` folder!\n{{\u003c /hint \u003e}}\n\n## Example\n\n{{\u003c columns \u003e}}\n```tpl\n{{\u003c/*/* mermaid [class=\"text-center\"]*/*/\u003e}}\nstateDiagram-v2\n State1: The state with a note\n note right of State1\n Important information! You can write\n notes.\n end note\n State1 --\u003e State2\n note left of State2 : This is the note to the left.\n{{\u003c/*/* /mermaid */*/\u003e}}\n```\n\n\u003c---\u003e\n\n{{\u003c mermaid \u003e}}\nstateDiagram-v2\n State1: The state with a note\n note right of State1\n Important information! You can write\n notes.\n end note\n State1 --\u003e State2\n note left of State2 : This is the note to the left.\n{{\u003c /mermaid \u003e}}\n\n{{\u003c /columns \u003e}}\n",
"lastmodified": "2023-01-05T06:31:25.831295598Z",
"tags": null
},
"/features/section/": {
"title": "",
"content": "\n# Section\n\nSection renders pages in section as definition list, using title and description.\n\n## Example\n\n```tpl\n{{\u003c/* section */\u003e}}\n```\n\n{{\u003csection\u003e}}\n",
"lastmodified": "2023-01-05T06:31:25.83529555Z",
"tags": null
},
"/features/section/first-page": {
"title": "",
"content": "# First page\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \n\n\u003c!--more--\u003e\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n",
"lastmodified": "2023-01-05T06:31:25.83529555Z",
"tags": null
},
"/features/section/second-page": {
"title": "",
"content": "# Second Page\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n\n\u003c!--more--\u003e\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n\n",
"lastmodified": "2023-01-05T06:31:25.83529555Z",
"tags": null
},
"/features/tabs": {
"title": "",
"content": "# Tabs\n\nTabs let you organize content by context, for example installation instructions for each supported platform.\n\n```tpl\n{{\u003c/* tabs \"uniqueid\" */\u003e}}\n{{\u003c/* tab \"MacOS\" */\u003e}} # MacOS Content {{\u003c/* /tab */\u003e}}\n{{\u003c/* tab \"Linux\" */\u003e}} # Linux Content {{\u003c/* /tab */\u003e}}\n{{\u003c/* tab \"Windows\" */\u003e}} # Windows Content {{\u003c/* /tab */\u003e}}\n{{\u003c/* /tabs */\u003e}}\n```\n\n## Example\n\n{{\u003c tabs \"uniqueid\" \u003e}}\n{{\u003c tab \"MacOS\" \u003e}}\n# MacOS\n\nThis is tab **MacOS** content.\n\nLorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat\nstringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa\nprotulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes.\nMiseratus fonte Ditis conubia.\n{{\u003c /tab \u003e}}\n\n{{\u003c tab \"Linux\" \u003e}}\n\n# Linux\n\nThis is tab **Linux** content.\n\nLorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat\nstringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa\nprotulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes.\nMiseratus fonte Ditis conubia.\n{{\u003c /tab \u003e}}\n\n{{\u003c tab \"Windows\" \u003e}}\n\n# Windows\n\nThis is tab **Windows** content.\n\nLorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat\nstringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa\nprotulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes.\nMiseratus fonte Ditis conubia.\n{{\u003c /tab \u003e}}\n{{\u003c /tabs \u003e}}\n",
"lastmodified": "2023-01-05T06:31:25.83529555Z",
"tags": null
},
"/setup/": {
"title": "",
"content": "",
"lastmodified": "2023-01-05T07:00:05.641797687Z",
"tags": null
},
"/setup/config": {
"title": "Customization",
"content": "\n# Configuration\nAmethyst is designed to be extremely configurable. You can find the bulk of the configuration scattered throughout the repository depending on how in-depth you'd like to get.\n\nThe majority of configuration can be found under `config.yaml`. An example, with descriptions for each setting, can be found [here](https://github.com/64bitpandas/amethyst/blob/main/config.yaml).\n\n### Code Block Titles\nTo add code block titles with Amethyst:\n\n1. Ensure that code block titles are enabled in the configuration:\n\n ```yaml {title=\"data/config.yaml\", linenos=false}\n enableCodeBlockTitle: true\n ```\n\n2. Add the `title` attribute to the desired [code block\n fence](https://gohugo.io/content-management/syntax-highlighting/#highlighting-in-code-fences):\n\n ```markdown {linenos=false}\n ```yaml {title=\"data/config.yaml\"}\n enableCodeBlockTitle: true # example from step 1\n ```\n ```\n\n**Note** that if `{title=\u003cmy-title\u003e}` is included, and code block titles are not\nenabled, no errors will occur, and the title attribute will be ignored.\n\n### HTML Favicons\nIf you would like to customize the favicons, you \ncan add them to the `data/config.yaml` file. The **default** without any set \n`favicon` key is:\n\n```html {title=\"layouts/partials/head.html\", linenostart=15}\n\u003clink rel=\"shortcut icon\" href=\"icon.png\" type=\"image/png\"\u003e\n```\n\nThe default can be overridden by defining a value to the `favicon` key in your \n`data/config.yaml` file. For example, here is a `List[Dictionary]` example format, which is\nequivalent to the default:\n\n```yaml {title=\"data/config.yaml\", linenos=false}\nfavicon:\n - { rel: \"shortcut icon\", href: \"icon.png\", type: \"image/png\" }\n# - { ... } # Repeat for each additional favicon you want to add\n```\n\nIn this format, the keys are identical to their HTML representations.\n\nIf you plan to add multiple favicons generated by a website (see list below), it\nmay be easier to define it as HTML. Here is an example which appends the \n**Apple touch icon** to Amethyst's default favicon:\n\n```yaml {title=\"data/config.yaml\", linenos=false}\nfavicon: |\n \u003clink rel=\"shortcut icon\" href=\"icon.png\" type=\"image/png\"\u003e\n \u003clink rel=\"apple-touch-icon\" sizes=\"180x180\" href=\"/apple-touch-icon.png\"\u003e\n```\n\nThis second favicon will now be used as a web page icon when someone adds your \nwebpage to the home screen of their Apple device. If you are interested in more \ninformation about the current and past standards of favicons, you can read \n[this article](https://www.emergeinteractive.com/insights/detail/the-essentials-of-favicons/).\n\n**Note** that all generated favicon paths, defined by the `href` \nattribute, are relative to the `static/` directory.\n\n### Graph View\nTo customize the Interactive Graph view, you can poke around `data/graphConfig.yaml`. The default configuration, with descriptions, can be found [here](https://github.com/64bitpandas/amethyst/blob/main/data/graphConfig.yaml).\n\n### Language Support\n[Chinese, Japanese, and Korean support](features/language.md) comes out of the box with Amethyst.\n\nWant to support languages that read from right-to-left (like Arabic)? Hugo (and by proxy, Amethyst) supports this natively.\n\nFollow the steps [Hugo provides here](https://gohugo.io/content-management/multilingual/#configure-languages) and modify your `config.yaml`\n\nFor example:\n\n```yaml\ndefaultContentLanguage: ar\nlanguages:\n ar:\n languagedirection: rtl\n title: مدونتي\n weight: 2\n```\n\n# Custom Styles\nWant to go even more in-depth? You can add custom CSS styling in `assets/_custom.scss`. If you'd like to target specific parts of the site, you can add ids and classes to the HTML partials in `/layouts/partials`. \n\n### Changing the Color Scheme\nThe default color schemes for light mode and dark mode are located in `assets/_colors.scss`. You can replace the values for existing color variables for drop-in edits, or create new varia
"lastmodified": "2023-01-05T20:27:26.526242587Z",
"tags": null
},
"/setup/custom-Domain": {
"title": "Custom Domain",
"content": "\n### Registrar\nThis step is only applicable if you are using a **custom domain**! If you are using a `\u003cYOUR-USERNAME\u003e.github.io` domain, you can skip this step.\n\nFor this last bit to take effect, you also need to create a CNAME record with the DNS provider you register your domain with (i.e. NameCheap, Google Domains).\n\nGitHub has some [documentation on this](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/managing-a-custom-domain-for-your-github-pages-site), but the tldr; is to\n\n1. Go to your forked repository (`github.com/\u003cYOUR-GITHUB-USERNAME\u003e/amethyst`) settings page and go to the Pages tab. Under \"Custom domain\", type your custom domain, then click **Save**.\n2. Go to your DNS Provider and create a CNAME record that points from your domain to `\u003cYOUR-GITHUB-USERNAME.github.io.` (yes, with the trailing period).\n\n\t![Example Configuration for Quartz](/setup/images/google-domains.png)*Example Configuration for Quartz*\n3. Wait 30 minutes to an hour for the network changes to kick in.\n4. Done!",
"lastmodified": "2023-01-05T20:49:06.807929818Z",
"tags": null
},
"/setup/editing": {
"title": "Editing Content",
"content": "\n## Editing \nAmethyst runs on top of [Hugo](https://gohugo.io/) so all notes are written in [Markdown](https://www.markdownguide.org/getting-started/).\n\n### Folder Structure\nHere's a rough overview of what's what.\n\n**All notes you want to publish should go in the `/content` folder.** To make edits, you can open any of the files and make changes directly and save it. You can organize content into any subfolder you'd like.\n\n**To edit the main home page, open `/content/_index.md`.**\n\nTo create a link between notes in your garden, just create a normal link using Markdown pointing to the document in question. Please note that **all links should be relative to the root `/content` path**. \n\n```markdown\nFor example, I want to link this current document to `setup/config.md`.\n[A link to the config page](setup/config.md)\n```\n\nSimilarly, you can put local images anywhere in the `/content` folder.\n\n```markdown\nExample image (source is in content/setup/images/example.png)\n![Example Image](/content/setup/images/example.png)\n```\n\nYou can also use wikilinks if that is what you are more comfortable with!\n\n### Front Matter\nHugo is picky when it comes to metadata for files. Make sure that your title is double-quoted and that you have a title defined at the top of your file in the front matter like so. You can also add tags here as well.\n\n```yaml\n---\ntitle: \"Example Title\"\ntags:\n- example-tag\n---\n\nRest of your content here...\n```\n\nYou can specify additional params in the front matter of individual pages:\n\n```toml\n# Set type to 'docs' if you want to render page outside of configured section or if you render section other than 'docs'\ntype = 'docs'\n\n# Set page weight to re-arrange items in file-tree menu (if BookMenuBundle not set)\nweight = 10\n\n# (Optional) Set to 'true' to mark page as flat section in file-tree menu (if BookMenuBundle not set)\nbookFlatSection = false\n\n# (Optional) Set to hide nested sections or pages at that level. Works only with file-tree menu mode\nbookCollapseSection = true\n\n# (Optional) Set true to hide page or section from side menu (if BookMenuBundle not set)\nbookHidden = false\n\n# (Optional) Set 'false' to hide ToC from page\nbookToC = true\n\n# (Optional) If you have enabled BookComments for the site, you can disable it for specific pages.\nbookComments = true\n\n# (Optional) Set to 'false' to exclude page from search index.\nbookSearchExclude = true\n\n# (Optional) Set explicit href attribute for this page in a menu (if BookMenuBundle not set)\nbookHref = ''\n```\n\n\n### Obsidian\nAmethyst is built especially for use with [Obsidian](http://obsidian.md/) as a text editor. \n\nSee below for more information:\n\n\u003e 🔗 Step 3: [How to setup your Obsidian Vault to work with Amethyst](setup/obsidian.md)\n\n## Previewing Changes\nThis step is purely optional and mostly for those who want to see the published version of their digital garden locally before opening it up to the internet. This is *highly recommended* but not required.\n\n\u003e 👀 Step 4: [Preview Changes](setup/preview%20changes.md)\n\nFor those who like to live life more on the edge, viewing the garden through Obsidian gets you pretty close to the real thing.\n\n## Publishing Changes\nAfter you've finished editing your notes, you can publish them to the internet!\n\n\u003e 🌍 Step 5: [Hosting Amethyst online!](setup/hosting.md)\n\nHaving problems? Check out our [FAQ and Troubleshooting guide](setup/troubleshooting.md).\n",
"lastmodified": "2023-01-05T20:35:30.496683846Z",
"tags": null
},
"/setup/hosting": {
"title": "Deploying Amethyst to the Web",
"content": "\n## Hosting on GitHub Pages\nAmethyst is designed to be effortless to deploy. If you forked and cloned Amethyst directly from the repository, everything should already be good to go! Follow the steps below.\n\n### Enable GitHub Actions\nBy default, GitHub disables workflows from running automatically on Forked Repostories. Head to the 'Actions' tab of your forked repository and Enable Workflows to setup deploying your site!\n\n![Enable GitHub Actions](/setup/images/github-actions.png)*Enable GitHub Actions*\n\n### Enable GitHub Pages\n\nHead to the 'Settings' tab of your forked repository and go to the 'Pages' tab.\n\n1. (IMPORTANT) Set the source to deploy from `master` (and not `hugo`) using `/ (root)`\n2. Set a custom domain here if you have one!\n\n![Enable GitHub Pages](/setup/images/github-pages.png)*Enable GitHub Pages*\n\n### Pushing Changes\nTo see your changes on the internet, we need to push it them to GitHub. Amethyst is a `git` repository so updating it is the same workflow as you would follow as if it were just a regular software project.\n\n```shell\n# Navigate to Amethyst folder\ncd \u003cpath-to-amethyst\u003e\n\n# Commit all changes\ngit add .\ngit commit -m \"message describing changes\"\n\n# Push to GitHub to update site\ngit push origin main\n```\n\nNote: we specifically push to the `main` branch here. Our GitHub action automatically runs everytime a push to is detected to that branch and then updates the `deploy` branch for redeployment.\n\n### Setting up the Site\nNow let's get this site up and running. Never hosted a site before? No problem. Have a fancy custom domain you already own or want to use a subdomain? That's easy too.\n\n\u003e Don't want to use GitHub Pages? Continue following the instructions below, and simply point your hosting solution to serve the `deploy` branch with no additional build steps required.\n\nHere, we take advantage of GitHub's free page hosting to deploy our site. Change `baseURL` in `/config.toml`. \n\nMake sure that your `baseURL` has a trailing `/`!\n\n[Reference `config.yaml` here](https://github.com/64bitpandas/amethyst/blob/main/config.yaml)\n\n```yaml\nbaseURL: \"https://\u003cYOUR-DOMAIN\u003e/\"\n```\n\nIf you are using this under a subdomain (e.g. `\u003cYOUR-GITHUB-USERNAME\u003e.github.io/amethyst/`), include the trailing `/`. **You need to do this especially if you are using GitHub!**\n\n```yaml\nbaseURL: \"https://\u003cYOUR-GITHUB-USERNAME\u003e.github.io/amethyst/\"\n```\n\nChange `cname` in `/.github/workflows/deploy.yaml`. Again, if you don't have a custom domain to use, you can use `\u003cYOUR-USERNAME\u003e.github.io`.\n\nPlease note that the `cname` field should *not* have any path `e.g. end with /amethyst` or have a trailing `/`.\n\n[Reference `deploy.yaml` here](https://github.com/64bitpandas/amethyst/blob/main/.github/workflows/deploy.yaml)\n\n```yaml {title=\".github/workflows/deploy.yaml\"}\n- name: Deploy \n uses: peaceiris/actions-gh-pages@v3 \n with: \n\tgithub_token: ${{ secrets.GITHUB_TOKEN }} # this can stay as is, GitHub fills this in for us!\n\tpublish_dir: ./public \n\tpublish_branch: deploy\n\tcname: \u003cYOUR-DOMAIN\u003e\n```\n\nHave a custom domain? [Learn how to set it up with Amethyst ](setup/custom%20Domain.md).\n\n### Ignoring Files\nOnly want to publish a subset of all of your notes? Don't worry, Amethyst makes this a simple two-step process.\n\n❌ [Excluding pages from being published](setup/ignore%20notes.md)\n\n---\n\nNow that your site is live, let's figure out how to make Amethyst really *yours*!\n\n\u003e Step 6: 🎨 [Customizing Amethyst](setup/config.md)\n\nHaving problems? Checkout our [FAQ and Troubleshooting guide](setup/troubleshooting.md).\n",
"lastmodified": "2023-01-05T20:47:32.15292783Z",
"tags": null
},
"/setup/ignore-notes": {
"title": "Ignoring Notes",
"content": "\nEdit `ignoreFiles` in `config.yaml` to include paths you'd like to exclude from being rendered.\n\n```toml\n...\nignoreFiles: [ \n \"/content/templates/*\", \n \"/content/private/*\", \n \"\u003cyour path here\u003e\"\n]\n```\n\n`ignoreFiles` supports the use of Regular Expressions (RegEx) so you can ignore patterns as well (e.g. ignoring all `.png`s by doing `\\\\.png$`).\nTo ignore a specific file, you can also add the tag `draft: true` to the frontmatter of a note.\n\n```markdown\n---\ntitle: Some Private Note\ndraft: true\n---\n...\n```\n\nMore details in [Hugo's documentation](https://gohugo.io/getting-started/configuration/#ignore-content-and-data-files-when-rendering).\n\n### Global Ignore\nHowever, just adding to the `ignoreFiles` will only prevent the page from being access through Amethyst. If you want to prevent the file from being pushed to GitHub (for example if you have a public repository), you need to also add the path to the `.gitignore` file at the root of the repository.",
"lastmodified": "2023-01-05T20:49:37.047611498Z",
"tags": null
},
"/setup/obsidian": {
"title": "Obsidian Vault Integration",
"content": "\n## Setup\nObsidian is the preferred way to use Amethyst. You can either create a new Obsidian Vault or link one that your already have.\n\n### New Vault\nIf you don't have an existing Vault, [download Obsidian](https://obsidian.md/) and create a new Vault in the `/content` folder that you created and cloned during the [setup](setup/setup.md) step.\n\n### Linking an existing Vault (simple)\nThe easiest way to use an existing Vault is to copy all of your files (directory and hierarchies intact) into the `/content` folder.\n\n### Linking an existing Vault (using git)\nIf you're editing in an existing vault and don't want to have to keep copying your files over, one solution is to create a new Git repository for just the notes you want to publish.\n\nThen, in both your vault and in Amethyst, run the following command, replacing the link with one to your new repository:\n```bash\ngit submodule add https://github.com/\u003cYOUR_USERNAME\u003e/\u003cREPO_NAME\u003e content\n```\n\n## Settings\nNow that you've added your notes to Amethyst, let's fix some settings so that they play well.\n\n1. Under Options \u003e Files and Links, set the New link format to always use Absolute Path in Vault.\n2. Go to Settings \u003e Files \u0026 Links \u003e Turn \"on\" automatically update internal links.\n\n![Obsidian Settings](/setup/images/obsidian-settings.png)*Obsidian Settings*\n\n## Templates\nInserting front matter everytime you want to create a new Note gets annoying really quickly. Luckily, Obsidian supports templates which makes inserting new content really easily.\n\n**If you decide to overwrite the `/content` folder completely, don't remove the `/content/templates` folder!**\n\nHead over to Options \u003e Core Plugins and enable the Templates plugin. Then go to Options \u003e Hotkeys and set a hotkey for 'Insert Template' (I recommend `[cmd]+T`). That way, when you create a new note, you can just press the hotkey for a new template and be ready to go!\n\n\u003e 👀 Step 4: [Preview Changes](setup/preview%20changes.md)",
"lastmodified": "2023-01-05T20:45:54.033965179Z",
"tags": null
},
"/setup/preview-changes": {
"title": "Preview Changes",
"content": "\nIf you'd like to preview what your site looks like before deploying it to the internet, the following\ninstructions guide you through installing the proper dependencies to run it locally.\n\n\n## Install `hugo-obsidian`\nThis step will generate the list of backlinks for Hugo to parse. Ensure you have [Go](https://golang.org/doc/install) (\u003e= 1.16) installed.\n\n```bash\n# Install and link `hugo-obsidian` locally\ngo install github.com/jackyzha0/hugo-obsidian@latest\n```\n\nIf you are running into an error saying that `command not found: hugo-obsidian`, make sure you set your `GOPATH` correctly! This will allow your terminal to correctly recognize hugo-obsidian as an executable.\n\nAfterwards, start the Hugo server as shown above and your local backlinks and interactive graph should be populated!\n\n## Installing Hugo\nHugo is the static site generator that powers Amethyst. [Install Hugo with \"extended\" Sass/SCSS version](https://gohugo.io/getting-started/installing/) first. Then,\n\n```bash\n# Navigate to your local Amethyst folder\ncd \u003clocation-of-your-local-amethyst\u003e\n\n# Start local server\nmake serve\n\n# View your site in a browser at http://localhost:1313/\n```\n\nNow that you are happy with how your Amethyst instance looks, let's get it hosted!\n\n\u003e 🌍 Step 5: [Hosting Amethyst online!](setup/hosting.md)\n",
"lastmodified": "2023-01-05T20:47:19.829057952Z",
"tags": null
},
"/setup/search": {
"title": "Search",
"content": "\nAmethyst supports two modes of searching through content.\n\n## Full-text\nFull-text search is the default in Amethyst. It produces results that *exactly* match the search query. This is easier to setup but usually produces lower quality matches.\n\n```yaml {title=\"data/config.yaml\"}\n# the default option\nenableSemanticSearch: false\n```\n\n## Natural Language\nNatural language search is powered by [Operand](https://beta.operand.ai/). It understands language like a person does and finds results that best match user intent. In this sense, it is closer to how Google Search works.\n\nNatural language search tends to produce higher quality results than full-text search.\n\nHere's how to set it up.\n\n1. Login or Register for a new Operand account. Click the verification link sent to your email, and you'll be redirected to the dashboard. (Note) You do not need to enter a credit card to create an account, or get started with the Operand API. The first $10 of usage each month is free. To learn more, see pricing. If you go over your free quota, we'll (politely) reach out and ask you to configure billing.\n2. Create your first index. On the dashboard, under \"Indexes\", enter the name and description of your index, and click \"Create Index\". Note down the ID of the index (obtained by clicking on the index name in the list of indexes), as you'll need it in the next step. IDs are unique to each index, and look something like `uqv1duxxbdxu`.\n3. Click into the index you've created. Under \"Index Something\", select \"SITEMAP\" from the dropdown and click \"Add Source\".\n4. For the \"Sitemap.xml URL\", put your deployed site's base URL followed by `sitemap.xml`. For example, for `amethyst.bencuan.me`, put `https://amethyst.bencuan.me/sitemap.xml`. Leave the URL Regex empty. \n5. Get your API key. On the dashboard, under \"API Keys\", you can manage your API keys. If you don't already have an API key, click \"Create API Key\". You'll need this for the next step.\n6. Open `data/config.yaml`. Set `enableSemanticSearch` to `true`, `operandApiKey` to your copied key, and `operandIndexId` to the ID of the index we created from earlier..\n\n```yaml {title=\"data/config.yaml\"}\n# the default option\nsearch:\n enableSemanticSearch: true\n operandApiKey: \"jp9k5hudse2a828z98kxd6z3payi8u90rnjf\"\n operandIndexId: \"s0kf3bd6tldw\"\n```\n7. Push your changes to the site and wait for it to deploy.\n8. Check the Operand dashboard and wait for your site to index. Enjoy natural language search powered by Operand!\n",
"lastmodified": "2023-01-05T20:48:38.320229929Z",
"tags": null
},
"/setup/setup": {
"title": "Setup",
"content": "\n## Getting Started\nSetting up Amethyst requires a basic understanding of `git`. If you are unfamiliar, [this resource](https://resources.nwplus.io/2-beginner/how-to-git-github.html) is a great place to start!\n\n### Forking\n\u003e A fork is a copy of a repository. Forking a repository allows you to freely experiment with changes without affecting the original project.\n\nNavigate to the GitHub repository for the Amethyst project:\n\n📁 [Amethyst Repository](https://github.com/64bitpandas/amethyst)\n\nThen, Fork the repository into your own GitHub account. If you don't have an account, you can make on for free [here](https://github.com/join). More details about forking a repo can be found on [GitHub's documentation](https://docs.github.com/en/get-started/quickstart/fork-a-repo).\n\n### Cloning\nAfter you've made a fork of the repository, you need to download the files locally onto your machine. Ensure you have `git`, then type the following command replacing `YOUR-USERNAME` with your GitHub username.\n\n```shell\ngit clone https://github.com/YOUR-USERNAME/amethyst\n```\n\n## Editing\nGreat! Now you have everything you need to start editing. If you're ready to start writing content already, check out the recommended flow for editing notes:\n\n\u003e ✏️ Step 2: [Editing Notes in Amethyst](setup/editing.md)\n\nHaving problems? Checkout our [FAQ and Troubleshooting guide](setup/troubleshooting.md).\n",
"lastmodified": "2023-01-05T20:29:17.588919796Z",
"tags": null
},
"/setup/troubleshooting": {
"title": "Troubleshooting and FAQ",
"content": "\nStill having trouble? Here are a list of common questions and problems people encounter when installing Amethyst.\n\n### Does Amethyst have Latex support?\nYes! See [LaTeX](features/latex.md) for a brief demo.\n\n### Can I use \\\u003cObsidian Plugin\\\u003e in Amethyst?\nUnless it produces direct Markdown output in the file, no. There currently is no way to bundle plugin code with Amethyst.\n\nThe easiest way would be to add your own HTML partial that supports the functionality you are looking for.\n\n### My GitHub pages is just showing the README\nMake sure you set the source to deploy from the `deploy` branch (and not `main`) using `/ (root)`! See more in the [hosting](/setup/hosting) guide\n\n### Some of my pages have 'January 1, 0001' as the last modified date\nThis is a problem caused by `git` treating files as case-insensitive by default and some of your posts probably have capitalized file names. You can turn this off in your Amethyst by running this command.\n\n```shell\n# in the root folder (same folder as config.toml)\ngit config core.ignorecase true\n\n# or globally (not recommended)\ngit config --global core.ignorecase true\n```\n\n### Can I publish only a subset of my pages?\nYes! Amethyst makes selective publishing really easy. Heres a guide on [excluding pages from being published](setup/ignore%20notes.md).\n\n### Can I host this myself and not on GitHub Pages?\nYes! All built files can be found under `/public` in the `master` branch. More details under [hosting](setup/hosting.md).\n\n### `command not found: hugo-obsidian`\nMake sure you set your `GOPATH` correctly! This will allow your terminal to correctly recognize `hugo-obsidian` as an executable.\n\n```shell\n# Add the following 2 lines to your ~/.bash_profile\nexport GOPATH=/Users/$USER/go\nexport PATH=$GOPATH/bin:$PATH\n\n# In your current terminal, to reload the session\nsource ~/.bash_profile\n```\n\n### How come my notes aren't being rendered?\nYou probably forgot to include front matter in your Markdown files. You can either setup [Obsidian](setup/obsidian.md) to do this for you or you need to manually define it. More details in [the 'how to edit' guide](setup/editing.md).\n\n### My custom domain isn't working!\nWalk through the steps in [the hosting guide](setup/hosting.md) again. Make sure you wait 30 min to 1 hour for changes to take effect.\n\n### How do I setup Google Analytics?\nYou can edit it in `config.toml` and either use a V3 (UA-) or V4 (G-) tag.\n\n### How do I change the content on the home page?\nTo edit the main home page, open `/content/_index.md`.\n\n### How do I change the colours?\nYou can change the theme by editing `assets/custom.scss`. More details on customization and themeing can be found in the [customization guide](setup/config.md).\n\n### How do I add images?\nYou can put images anywhere in the `/content` folder.\n\n```markdown\nExample image (source is in content/setup/images/example.png)\n![Example Image](/content/setup/images/example.png)\n```\n\n### My Interactive Graph and Backlinks aren't up to date\nBy default, the `linkIndex.json` (which Amethyst needs to generate the Interactive Graph and Backlinks) are not regenerated locally. To set that up, see the guide on [local editing](setup/editing.md)\n\n### Can I use React/Vue/some other framework?\nNot out of the box. You could probably make it work by editing `/layouts/_default/single.html` but that's not what Amethyst is designed to work with. 99% of things you are trying to do with those frameworks you can accomplish perfectly fine using just vanilla HTML/CSS/JS.\n\n## Still Stuck?\nAmethyst isn't perfect! If you're still having troubles, file an issue in the GitHub repo with as much information as you can reasonably provide. Alternatively, [send me a message](https://bencuan.me/contact) using your preferred communication method!\n\n🐛 [Submit an Issue](https://github.com/64bitpandas/amethyst/issues)",
"lastmodified": "2023-01-05T07:07:33.520765851Z",
"tags": null
},
"/setup/updating": {
"title": "Updating",
"content": "\nHaven't updated Amethyst in a while and want all the cool new optimizations? On Unix/Mac systems you can run the following command for a one-line update! This command will show you a log summary of all commits since you last updated, press `q` to acknowledge this. Then, it will show you each change in turn and press `y` to accept the patch or `n` to reject it. Usually you should press `y` for most of these unless it conflicts with existing changes you've made! \n\n```shell\nmake update\n```\n\nOr, if you don't want the interactive parts and just want to force update your local garden (this assumed that you are okay with some of your personalizations been overriden!)\n\n```shell\nmake update-force\n```\n\nOr, manually checkout the changes yourself.\n\n\u003e [!warning] Warning!\n\u003e\n\u003e If you customized the files in `data/`, or anything inside `layouts/`, your customization may be overwritten!\n\u003e Make sure you have a copy of these changes if you don't want to lose them.\n\n\n```shell\n# add Amethyst as a remote host\ngit remote add upstream git@github.com:64bitpandas/amethyst.git\n\n# index and fetch changes\ngit fetch upstream\ngit checkout -p upstream/hugo -- layouts .github Makefile assets/js assets/styles/base.scss assets/styles/darkmode.scss data \n```\n",
"lastmodified": "2023-01-05T20:50:13.64322657Z",
"tags": null
}
}