Posts

Showing posts from January, 2023

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

Dynamic Programming - Parts      PART 1 - Memoization     P ART 2 - Tabulation Dynamic Programming with Fibonacci Example Recursion: Slow because time complexity is O(2^n) func fibR (x int ) int {     if x <= 2 {         return 1     }     return fibR (x- 1 ) + fibR (x- 2 ) } Dynamic Way Example Recursion with Stored Value:  // Fast because it removes duplicate processes by checking map. // Tail recursion-ish // Results are hitchhiking each recursive call func fibR2 (x int , y map [ int ] int ) int {     if _ , ok := y[x]; ok {         return y[x]     }     if x <= 2 {         return 1     }     y[x] = fibR2 (x- 1 , y) + fibR2 (x- 2 , y)     return y[x] }

59. Go - goto

Goto statement allows label jumping. goto only works on labels within the same function bracket scope. package main import "fmt" func main () { /* local variable definition */ var a int = 10 /* do loop execution */ LOOP : for a < 20 { if a == 15 { /* skip the iteration */ a = a + 1 goto LOOP } fmt . Printf ( "value of a: %d\n" , a ) a ++ } } OUTPUT: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19

4. Algorithms - Bogo Sort

Bogo sort is a randomizing algorithm that shuffles an array and then checks whether it is sorted. package main import (     "fmt"     "math/rand"     "time" ) // isSorted checks whether a list is sorted by comparing first and next value. func isSorted (list [] int ) bool {     for i , _ := range list {         if i != ( len (list) - 1 ) {             if list[i] > list[i+ 1 ] {                 return false             }         }     }     return true } // bogoSort shuffles a list. func bogoSort (list *[] int ) {     rand. Shuffle ( len (*list), func (i, j int ) {         (*list)[i], (*list)[j] = (*list)[j], (*list)[i]     }) } func main () {     rand. Seed (time. Now (). UnixNano ())     x := [] int { 4 , 1 , 7 , 5 , 8 }     tries := 0     for {         tries++         fmt. Println (tries)         bogoSort (&x)         fmt. Println (x)         if isSorted (x) {             break         }     }     fmt. Println (x) }

3. Algorithms - Selection Sort

Selection sort sorts an array by finding the lowest value element and appending it to an empty array. The algorithm will shrink the unsorted array and repeat the process recursively until all unsorted elements are used up. package main func selectionSort (list *[] int ) {     sorted := make ([] int , 0 , len (*list))     unSorted := *list     for i := 0 ; i < len (*list); i++ {         min := unSorted[ 0 ]         index := 0         for i , e := range unSorted {             if e <= min {                 min = e                 index = i             }         }         sorted = append (sorted, (unSorted)[index])         if index == 0 {             unSorted = unSorted[ 1 :]         } else if index == ( len (*list) - 1 ) {             unSorted = unSorted[:index]         } else {             unSorted = append (unSorted[ 0 :index], unSorted[index+ 1 :]...)         }     }     * list = sorted } /*func main() {     x := []int{4, 6, 3, 2, 9, 7, 3, 5}     fmt.Print

2. Algorithms - Quick Sort

Quicksort, sorts an array recursively by picking a pivot point (usually the middle element). Then creating two subArrays left and right of the pivot. Left would contain elements in array that is less than pivot, and right is greater. subArrays are put into quicksort again with base statement returning an array with length of 1 or 0. package main //import "fmt" func quickSort (list [] int ) [] int {     if len (list) <= 1 {         return list     }     pivot := make ([] int , 1 )     pivot[ 0 ] = list[ 0 ]     leftList := [] int {}     rightList := [] int {}     for i := 1 ; i < len (list); i++ {         if list[i] > pivot[ 0 ] {             rightList = append (rightList, list[i])         } else {             leftList = append (leftList, list[i])         }     }     leftSublist := quickSort (leftList)     rightSublist := quickSort (rightList)     answer := [] int {}     answer = append (leftSublist, pivot...)     answer = append (answer, rightSubl

1. Algorithms - Merge Sort

Merge Sort Code: using merge sort and merge method recursively to sort/merge an unsorted list package main import (     "fmt" ) func mergeSort (list [] int ) [] int {     // If list only have 1 number or none, return it.     if len (list) < 2 {         return list     }     // Split recursion     left := mergeSort (list[: len (list)/ 2 ])     right := mergeSort (list[ len (list)/ 2 :])     return merge (left, right) } func merge (left, right [] int ) [] int {     answer := [] int {}     leftCount := 0     rightCount := 0     for leftCount < len (left) && rightCount < len (right) {         if left[leftCount] < right[rightCount] {             answer = append (answer, left[leftCount])             leftCount++         } else {             answer = append (answer, right[rightCount])             rightCount++         }     }     for ; leftCount < len (left); leftCount++ {         answer = append (answer, left[leftCount])     }     for ; r

58. Go - Break/Return

Break : break out of a loop, but continue the code below the loop break is used to immediately terminate a for loop, a while loop or a switch statement. You can not break from an if block. Return : break out of loop and out of method or whole block {} and return the value to caller. return is used the terminate a method (and possibly return a value).

57. Go - Scopes

Package Level Scope: - declaring variables outside main function. - variables are accessible within other scripts within same package (folder) Block Level Scope: - declaring variables inside function curly braces Exported and NotExported Names: - Lower case variables/names are not accessible outside of package. - Upper case variables/names are exported names and can be accessed outside of package. Return Function with inner closure scope: package main import "fmt" func printerr () func () int {     x := 0     return func () int {         x++         return x     } } func main () {     test1 := printerr ()     fmt. Println ( test1 ())     test2 := printerr ()     fmt. Println ( test2 ())     fmt. Println ( "TWO" )     fmt. Println ( test2 ())     fmt. Println ( test2 ())     fmt. Println ( test2 ())     fmt. Println ( test2 ())     fmt. Println ( "ONE" )     fmt. Println ( test1 ()) } // test1 is a printerr function with its own scope of x variab

1. FreeCodeCamp - Algorithms and Data Structures

Image
Algorithm: a set of instructions to finish a task Types of searches: Simple/Sequential/Linear  [ O (n) ] - searching through one record at a time in order, in a linear fashion.  - searching first to last Code: package main import "fmt" // linear search searches a list for the target and returns the index in the list if found func linear_search (list [] int , target int ) ( int , bool ) {     for i := 0 ; i < len (list); i++ {         if list[i] == target {             return i, true         }     }     return 0 , false } func main () {     list := [] int { 1 , 412 , 41 , 561 , 612 , 513 , 51 , 421 , 1 , 31 , 31 , 51 , 51 , 351 , 51 , 51 , 2421 , 41 , 4124 }     x , found := linear_search (list, 22 )     if found {         fmt. Println ( "INDEX:" , x)     } else {         fmt. Println ( "NO VALUES FOUND." )     } } Binary Search [ O (log n) ] Data List (Input) -> Index Position of Target (Output) or Does not Exist Return (Output) - Requir

2. Github - Version Control with Git

Committing Process: Modifying (modify files) -> Staging (picking which modified file to commit) -> Committing 1. Create repository in Github. 2. In Directory of code project, git init // creates a hidden folder to track changes. 3. Adding files to the staging process (process that is before committing). Use "git add <FILENAME>" OR "git add ." 4. Committing files, updating version control stuff, Use git commit -m "MESSAGE" // -m, is attaching a message. 5. Pushing to Github - Use code provided by GitHub to remote add local directory to GitHub repository. - Use push code to push to GitHub repository - git remote add origin <githubRepoLink> // link origin branch to the github repo     - need setup before using "git push" shortcut     - git push --set-upstream origin master - git push origin master // pushes the origin(localname) to the master branch in github 6. Updating future changes and pushing, - git status // checks status of

56. Go - Exported Names

When wanting to use variables or functions or types outside of a package, the name must start with a capital letter. Example: func TestFunc() {     do something }

55. Go - Benchmarking

Benchmarking benchmarks codes to measure its performance. Time to complete. Same format and setup as testing and example testing. Requires: - source code - test code Source Code: to benchmark package main func sayRandom () string {     return "Random" } Test Code: package main import "testing" //import "fmt" /*func TestSayRandom(t *testing.T) {     x := sayRandom()     if x != "Random" {         t.Error("ERROR: Test Failed. Got:", x, "Expected: Random")     } }*/ /*func ExampleRandom() {     fmt.Println(sayRandom())     // Output: Random }*/ func BenchmarkSayRandom (b *testing.B) {     for i := 0 ; i < b.N; i++ {         sayRandom ()     } } // requires func format, BenchmarkXxx(b *testing.B) {} // must have for loop, using b.N as the limit // run test by using,  go test -bench . // to do all benchmarks OR go test -bench SayRandom // to do specific benchmark Benchmark Results = nanoseconds/operation

54. Go - Example Testing

Example testing is like Unit Testing but for example codes in documentations. Requires: - main/source code - testing code that tests a function from source code. Run example test: go test Main Code Example: package main func combineString (a, b string ) string {     x := a + b     return x } Test Code Example: // correct output of function = "applebox" package main import "fmt" func ExampleCombineString () {     fmt. Println ( combineString ( "apple" , "box" ))     // Output: applebox } // the output comment block is a valid syntax for testing the example function. // Must have "Output:" // Anything to the right or below the output comment will be checked for validity (if test fails, it is because output of function does not match the one in the comment block. Test Code Example:  // correct output of function = "applebox" // output comment wants "apple box" package main import "fmt" func ExampleC

53. Go - Unit Testing

Unit testing is a way to test "units" of a program code. Units are small sections. Requires : - program code - testing code Testing Code requirements: - import "testing" - Testing function must start with "TestXxx" and arguments must be (t *testing.T) // t.Log(), logs errors into default output (this is stdout by default, can change) // t.Fail(), marks the function as failed. // t.Error("TEST STRING"), is a t.Log() followed by a t.Fail() // t.Errorf(), format version Running Tests: go test Program Code Example: package main import "fmt" func main () {     x := "testing string"     fmt. Println ( reverseString (x)) } func reverseString (x string ) string {     var answer string     for i := len (x) - 1 ; i >= 0 ; i-- {         answer += string (x[i])     }     return answer } Testing Code Example: package main import "testing" func TestReverseString (t *testing.T) {     x := reverseString ( "tes

52. Go - Type Assertions for Interfaces

Assertion allows accessing exact types from an interface. Using parenthesis and the type inside. Example: package main import "fmt" func main () {     var jar interface {} = 2000     x := jar.( int )     fmt. Println (x)     y , err := jar.( string )     if err {         fmt. Println ( "STRING FOUND: " , y)     } else {         fmt. Println ( "STRING NOT FOUND" )     } } // using double variables allow checking if the type exists in an interface. // if true, else