Crash Course by Example

  • Bubble Sort
function BubbleSort!(a::Array)
    for i in collect(1:length(a)-1)
        for j in collect(1:length(a)-i)
            if a[j] > a[j+1]
                a[j], a[j+1] = a[j+1], a[j]
            end
        end
    end 
    return a   
end

data = floor.(rand(10)*10)
BubbleSort!(data)
  • Roots of a Polynomia
    • This example is find all values that solve the equaiton
    • ... indicates that this function will accept comma separated parameters with an unspecified number of parameters.
# The first method
using Roots

function polynomiaGenerator(a...)
    n = length(a) - 1
    poly = function(x)
        return sum([a[i+1]*x^i for i in 0:n])
    end
    return poly
end

@time begin
    polynomia = polynomiaGenerator(1, 3, -10)
    zeroVals = find_zeros(polynomia, -10, 10)    
end
println("Zeros of the function f(x): ", zeroVals)

# The second method
function polynomiaGenerator2(a...)
    f(x) = sum([a[i+1]*x^i for i in 0:length(a)-1])
    return f
end

@time begin
    polynomia2 = polynomiaGenerator2(1, 3, -10)
    zeroVals = find_zeros(polynomia2, -10, 10)    
end
  • Markov Chain
    • Transition probability matrix : describes the probability of transitioning to state from current state
      • i.e. The state is Rain today and the state is Fine next day, the is the probability of the next day is Fine when today is Rain.
      • Thus
    • Stationary distribution
using LinearAlgebra, StatsBase


P = [0.5 0.4 0.1;
    0.3 0.2 0.5;
    0.5 0.3 0.2];

# First way
piProb1 = (P^100)[1,:]

# Second way
A = vcat((P'-I)[1:2, :], ones(3)')
b = [0 0 1]'
piProb2 = A\b

# Third way
eigVecs = eigvecs(copy(P'))
highestVec = eigVecs[:, findmax(abs.(eigvals(P)))[2]]
piProb3 = Array{Float64}(highestVec)/norm(highestVec,1)

# Fourth way
numInState = zeros(Int,3)
state = 1
N = 10^7
for _ in 1:N
    numInState[state] += 1
    global state = sample(1:3, weights(P[state,:]))
end
piProb4 = numInState/N

display([piProb1 piProb2 piProb3 piProb4])
  • Web Interfacing, JSON, and String Processing
using HTTP, JSON

data = HTTP.request("GET",
"https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt")
shakespeare = String(data.body)
shakespeareWords = split(shakespeare)

# jsonWords = HTTP.request("GET",
# "https://raw.githubusercontent.com/"*
# "h-Klok/StatsWithJuliaBook/master/data/jsonCode.json")
jsonWords = """
{
  "words": [ "heaven","hell","man","woman","boy","girl","king","queen",
    "prince","sir","love","hate","knife","english","england","god"],
  "numToShow": 5
}
""";
parseJsonDict = JSON.parse(jsonWords)

keywords = Array{String}(parseJsonDict["words"])
numberToShow = parseJsonDict["numToShow"]
wordCount = Dict([(x, count(w -> lowercase(w) == lowercase(x), shakespeareWords)) for x in keywords])

sortedWordCount = sort(collect(wordCount), by=last, rev=true)
display(sortedWordCount[1:numberToShow])

results matching ""

    No results matching ""