refactor algorithm code