Skip to content

Instantly share code, notes, and snippets.

@spceaza
Created February 2, 2018 06:01
Show Gist options
  • Save spceaza/17d1d0922f7cf698e5be586c0b1dffbc to your computer and use it in GitHub Desktop.
Save spceaza/17d1d0922f7cf698e5be586c0b1dffbc to your computer and use it in GitHub Desktop.
data = matrix(nrow = 20, ncol = 5, byrow = T,
c(8,8,0,9,6,
7,1,1,1,0,
2,1,7,2,0,
6,6,6,6,4,
1,1,1,1,0,
3,2,1,3,0,
7,6,6,2,2,
9,3,1,3,1,
0,0,0,0,4,
2,2,2,2,0,
3,3,3,3,0,
5,5,5,5,0,
8,1,9,3,3,
8,0,9,6,5,
7,7,7,7,0,
9,9,9,9,4,
7,7,5,6,1,
6,8,5,5,3,
9,8,8,1,5,
5,5,3,1,0))
f = function(values, number) {
result = values[number[1] + 1]
result = result + values[number[2] + 1]
result = result + values[number[3] + 1]
result = result + values[number[4] + 1]
result
}
error_calc = function(values) {
result = sum(apply(data, 1, function(x) abs(f(values, x[1:4]) - x[5])))
result
}
initial_values = floor(runif(10, 0, 10))
error = error_calc(initial_values)
iterations = 0
while (error > 0) {
new_values = initial_values
new_values[ceiling(runif(1, 0, 10))] = floor(runif(1, 0, 10))
new_error = error_calc(new_values)
if(new_error <= error) {
error = new_error
initial_values = new_values
}
iterations = iterations + 1
}
tmp = sapply(0:9, function(x) paste(x, "=", initial_values[x + 1]) )
unknown = c(2, 5, 8, 1)
result = f(initial_values, unknown)
print(paste("Solution found in", iterations, "iterations:"))
for(i in tmp) print(i)
print(paste(paste(unknown, collapse = ""), " = ", result, sep = ""))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment