Loops are essential functions in any language. In this tutorial I will show you an example in python, the importance of the loops. In fact, you can use this knowledge for simple game development.

First of all we create a 2D array. In this example, you can use a 2D array in any dimension. Just look at my 2D array.

arr = [(11,12,13,14,15,16,17,18,19,20),
(21,22,23,24,25,26,27,28,29,30),
(31,32,33,34,35,36,37,38,39,40),
(41,42,43,44,45,46,47,48,49,50),
(51,52,53,54,55,56,57,58,59,60),
(61,62,63,64,65,66,67,68,69,70),
(71,72,73,74,75,76,77,78,79,80),
(81,82,83,84,85,86,87,88,89,90),
(91,92,93,94,95,96,97,98,99,100)]

In this we take two user inputs. Actually, two integers. Aim of this example is, by looking at the position of those two numbers within the array, detecting the next set of numbers. However, I developed this code to detect consecutive numbers.

For example, if your two numbers are 63 and 54. Then next numbers will be 45, 36, 27 and 18.
if your two numbers are 51 and 52. Then next will be 53,54,55,56,57,58,59 and 60.

Step 1: Take two user inputs.

num1 = input(“Enter Number1: “)
num2 = input(“Enter Number2: “)

Step2: Find the current position of the two inputs.

for i in range(len(arr)):
for j in range(len(arr[i])):
if(arr[i][j] == num1):
num1Row = i
num1Col = j

if(arr[i][j] == num2):
num2Row = i
num2Col = j

Step3: A function to see whether the numbers has a flow

def p_trend(y,x):
if (y == x +1 or y == x or y == x-1):
return True
else:
return False

Step4: If those two numbers has a flow ……….
if (p_trend(num1Row,num2Row)== True and p_trend(num1Col,num2Col)== True):
………………………………….
………………………………….

Step5: Using loops find the next positions of the array.




Download the complete code here.

Linear Trend Detection in a 2D Array in Python

Leave a Reply

Your email address will not be published. Required fields are marked *