File size: 1,340 Bytes
ca165c7 |
1 2 3 4 5 6 7 8 9 10 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 |
import csv
import numpy as np
import random # Import the random module
def change_fourth_occurrence(matrix):
for col in range(len(matrix[0])):
count = 1
for row in range(1, len(matrix)):
if matrix[row][col] == matrix[row - 1][col]:
count += 1
else:
count = 1
if count == 4:
current_number = matrix[row][col]
# Generate a random number within the range [current_number-1, current_number+1]
next_number = random.choice([current_number - 1, current_number + 1])
matrix[row][col] = next_number
count = 1
# Post-processing: Ensure there are no negative numbers in the matrix
matrix[matrix < 0] = 0
# Read the matrix from CSV
input_matrix = []
with open('matrix2.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
input_matrix.append([int(num) for num in row])
# Convert the matrix to a NumPy array for easy column indexing
input_matrix = np.array(input_matrix)
# Call the function to modify the matrix
change_fourth_occurrence(input_matrix)
# Write the modified matrix back to CSV
with open('matrix5.csv', 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(input_matrix)
|