In the past two days, I looked at the github of a certain master and found out that he is more interested in algorithms. I saw one of the step counting algorithms for calculating numbers. I thought it was interesting, so I implemented one myself.
Algorithm description and implementation principle
Given an integer number, count how many moves can reach the goal. For example, a number 4 can have the following moves
In fact, the following conclusion can be drawn through the above combination.
1. First list all combinations whose items are 1
2. From left to right, the combinations whose items are 1
3. Recurse the above set, find the index of 1 in the item, and then calculate the values of the 2 items from the left. The result is recursive operation
4. Exclude situations 1 and 2
The following three tool functions are provided:
//Output the value of the array
function print(arg){
for(var i = 0; i < arg.length; i ){
console.log(arg[i]);
}
}
// Check whether it is a forward or reverse move
function hasRepeat(src, dist){
If (dist.length != 2) return false;
for(var i = 0, len = src.length; i < len ; i ){
If(dist.length == src[i].length){
If(dist[0] == src[i][1]){
return true;
}
}
}
Return false;
}
The implementation of the algorithm is posted below:
//Run
countSteps(4);
// Output the following content
/*
[ 1, 3 ]
[ 4 ]
[ 1, 1, 2 ]
[ 2, 2 ]
[ 1, 1, 1, 1 ]
There are a total of: 5 types of walking
*/
Summary
This algorithm can actually be applied to certain types of games. When the distance between two objects is constant, all possibilities can be processed. Of course, it can also be applied to other places. Although most front-end engineers are not familiar with the algorithm. There is relatively little practice, but it still has value. Algorithms are actually used in many UI details. I will post more articles about algorithms when I have time in the future. Welcome to give me more valuable opinions.