Namachane na szybko i bez optymalizacji dla 1 wiersza. Ważne byś zrozumiał co się tu dzieje...
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
#include <fstream>
#include <array>
constexpr static size_t MAX_COLS = 320;
constexpr static size_t MAX_ROWS = 200;
constexpr static int CONTRAST_VALUE = 128;
using values_t = std::array<std::array<int, MAX_COLS>, MAX_ROWS>;
void readDataFromFile(const std::string& fileName, values_t& data) {
std::ifstream file("dane.txt");
if(!file) {
std::cerr << "Błąd otwarcia pliku: " << fileName << '\n';
exit(EXIT_FAILURE);
}
int value;
for(auto rowIdx = 0U; rowIdx < MAX_ROWS; ++rowIdx) {
for(auto colIdx = 0U; colIdx < MAX_COLS; ++colIdx) {
file >> value;
data[rowIdx][colIdx] = value;
}
}
}
int checkContrast(int valueSrc, int valueDst) {
return abs(valueSrc - valueDst) > CONTRAST_VALUE ? 1 : 0;
}
int checkNeighbors(const values_t& data, size_t rowIdx, size_t colIdx) {
int checkCoords[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for(int i = 0; i < 4; ++i) {
auto currentRowIdx = static_cast<int>(rowIdx) + checkCoords[i][0];
auto currentColIdx = static_cast<int>(colIdx) + checkCoords[i][1];
if((currentRowIdx < 0) || (currentColIdx < 0)
|| (currentRowIdx == MAX_ROWS) || (currentColIdx == MAX_COLS)) {
continue;
}
if(checkContrast(data[rowIdx][colIdx], data[currentRowIdx][currentColIdx])) {
return 1;
}
}
return 0;
}
int main() {
values_t data{};
readDataFromFile("data.txt", data);
size_t counter{};
for(auto rowIdx = 0U; rowIdx < MAX_ROWS; ++rowIdx) {
for(auto colIdx = 0U; colIdx < MAX_COLS; ++colIdx) {
counter += checkNeighbors(data, rowIdx, colIdx);
}
}
std::cout << "Wartości kontastujących jest: " << counter << '\n';
}