In Excel, there is a nice feature where if you enter 1, 2, 3 in three consecutive cells and then select the cells and drag down, it automatically fills in the rest of the cells as 4, 5, 6, 7, etc. It is also able to match more patterns. For example, if I did 2, 4, 6, 8, it would recognize I am adding 2 and then suggest 10, 12, 14, etc.
How does Excel know which numbers? Do they hardcode the different cases (i.e. adding some constant, subtracting some constant, multiplying by some constant) or is there some algorithm that can automatically predict this for you? (This question should be language-agnostic, but if it helps, I want to do this in jQuery)
Th开发者_如何转开发anks!
I'm pretty sure it's a simple thing to do. Excel probably checks, when a user enters three numbers, the delta between each consecutive number. If they are the same both times, it will use that delta to predict the next number.
If you want to do this more generically than Excel does (only addition or subtraction of constant values), have a look at some interpolation algorithms from numerical methods point of view. This wikibook article is an ok tutorial.
In Excel, it only works with additions and substractions (that I know of, I just tried with multiplications and the results don't follow the same pattern as the originals).
Knowing that, I think it would be easy to calculate the difference between the first two cell, then check the difference between cell 2 and cell 3 to see if it's the same. You can then apply that transformation to the cells you want to predict.
*Example*
Cell1: 2
Cell2: 5
Cell3: 8
if(cell2 - cell1 == cell3 - cell2)
cell4 = cell3 + (cell2-cell1); //Cell4 will now be 11 since it increments by steps of 3
You could then use a for loop that would copy the value you want to all selected cells (if you want to make the next ten cells follow the pattern, use a for or a while loop that will update the value of those 10 cells)
精彩评论