A generic algorithm for Monte Carlo simulation of proton transport