- Home /
How can I code a pattern detector in an array of integers?
I have an array of integers:
var theArray = int[10,10] ;
This 10x10 array is randomly populated with integers: 1, 2 or 3.
I would like to loop through this array and detect the following patterns: "1 2 3" and "1 2 1", either horizontally or vertically.
What's the most efficient and cleanest way of achieving that? Using strings? Calculations?
Here is the sample code you can use if you wish:
for (var x: int = 0 ; x < 10 ; x++) {
for (var y : int = 0 ; y < 10 ; y++) {
// theArray[x,y] = ...
}
}
I'd start off by finding all the values of the first value (looking for integers rather than strings), then have a method to check neighbors in each direction, then continue in that direction until the length of the pattern your searching for is correct.
If it's true you'll be able to return the start location point of the pattern and the direction it's headed, you can also store the length or add the output to a list of what was found.
Bear in $$anonymous$$d though it could start getting confusing if you've already found a pattern which is a palindrome, "1 2 1" will end up being listed twice.
Hi there, thanks for your response. It gave me some good ideas. Feel free to submit it as an answer. Thanks
if the arrays are sorted, then perhaps http://en.wikipedia.org/wiki/Binary_search_algorithm would work ? starts off @ center and depending on if the center value is higher, lower, it just either checks the left or right side of the array and starts at that sides center..
Hi, thanks for your suggestion. But in this case, it wouldn't work because this array can't be sorted. Thanks
Answer by SirCrazyNugget · Mar 09, 2014 at 03:33 PM
I'd start off by finding all the values of the first value (looking for integers rather than strings), then have a method to check neighbors in each direction, then continue in that direction until the length of the pattern your searching for is correct.
If it's true you'll be able to return the start location point of the pattern and the direction it's headed, you can also store the length or add the output to a list of what was found.
Bear in mind though it could start getting confusing if you've already found a pattern which is a palindrome, "1 2 1" will end up being listed twice.
(Glad it helps)