Skip to content

Instantly share code, notes, and snippets.

#Stop following command execution if command before failed
set -e
#Remove previous bucket if exists
delete_previous_version_if_exists() {
#We either delete local folder and bucket object or just a bucket
rm -r ./your-choosen-folder &&
gsutil -m rm -r gs://your-production-project/your-choosen-folder ||
gsutil -m rm -r gs://your-production-project/your-choosen-folder
}
@Albertbol
Albertbol / generatePopulation.js
Last active March 7, 2021 10:15
Generate population
const phraseToGuess = 'random phrase'
const populationSize = 200
const population = []
// Demo function to pick random latin basic UTF-8 characters
// you can see full table here:
// https://www.w3schools.com/charsets/ref_utf_basic_latin.asp
newChar() {
let c = Math.floor(Math.random() * 59) + 63
if (c === 63) c = 32 // change "?" to " " space
@Albertbol
Albertbol / fitnessLevel.js
Last active March 7, 2021 17:39
Calculate fitness level
const pow = 10
fitnessLevel(randomPhrase) {
let fitnessLevel = 0
for (let i = 0; i < this.phraseToGuess.length; i++) {
// Compare letters
if (this.phraseToGuess[i] === randomPhrase[i]) {
fitnessLevel++
}
}
normalization() {
let powSum = 0
population.forEach((p, i) => {
powSum += population[i].powRate
})
population.forEach((p, i) => {
population[i].powRate = p.powRate / powSum
})
}
DNAchanges() {
population.forEach((_, index) => {
const a = selection()
const b = selection()
let child = crossover(a.randomPhrase, b.randomPhrase)
child = mutate(child)
population[index].randomPhrase = child
})
}
selection() {
let index = 0
let random = Math.random()
while (random > 0) {
random = random - population[index].powRate
index++
}
index-- // index++ jumped to the next phrase
return population[index]
}
crossover(a, b) {
const midpoint = Math.floor(Math.random() * (phraseToGuess.length - 2)) + 1
let crossed = ''
for (let i = 0; i < phraseToGuess.length; i++) {
if (i <= midpoint) {
crossed += a[i]
} else {
crossed += b[i]
}
}
const mutationRate = 0.01
mutate(child) {
const chars = child.split('')
for (let i = 0; i < chars.length; i++) {
if (Math.random() <= mutationRate) {
chars[i] = newChar()
}
}
return chars.join('')
}
class GeneticAlgorithm {
constructor(phraseToGuess, populationSize, mutationRate, pow) {
this.phraseToGuess = phraseToGuess
this.populationSize = populationSize
this.mutationRate = mutationRate
this.pow = pow
this.population = []
this.foundIndex = -1
this.cycle = 0
this.rateSum = 0
module.exports = class Matrix {
static randomNormalized() {
let r = 0
const v = 4
for (let i = v; i > 0; i--) {
r += Math.random()
}
return r / v
}