Skip to content

Instantly share code, notes, and snippets.

@jaye-ross
Created July 7, 2016 04:07
Show Gist options
  • Select an option

  • Save jaye-ross/bb09048643e4241cc241bc27e38fd000 to your computer and use it in GitHub Desktop.

Select an option

Save jaye-ross/bb09048643e4241cc241bc27e38fd000 to your computer and use it in GitHub Desktop.
f = function(weights,n){
p = double(length(weights))
position = sample(1:length(weights),1)
p[position] = p[position] + 1
for(i in 2:n){
# determine candidate new position
move = sample(c(-1,1),1)
new_position = position + move
if(new_position == 0 || new_position == length(weights)+1){
p[position] = p[position] + 1
next
}
# decide if you should move
if(weights[position] < weights[new_position]){
position = new_position
p[position] = p[position] + 1
next
}
if(weights[position] > weights[new_position]){
should_move = (runif(1) < weights[new_position]/weights[position])
if(should_move) position = new_position
p[position] = p[position] + 1
next
}
}
print(weights)
print(p)
print(p/sum(p))
print(weights/sum(weights))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment