Se considera un tablon bidimensional cun lini si m coloane. Realizați un program care interschimbă coloana x cu coloana y, unde x siy sunt cinte /// vă rog. (Limbaj c++, clasa 9)
Răspunsuri la întrebare
Răspuns:
#include <iostream>
#include <random>
#include <chrono>
static int **creazaTablouBiDimensional(int numarLinii, int numarColoane)
{
unsigned seed = std::chrono::steady_clock::now().time_since_epoch().count();
std::default_random_engine randomEngine(seed);
std::uniform_int_distribution<int> uniformDistribution(1, 10);
int **tablouBiDimensional = new int *[numarLinii] {};
for (int i = 0; i < numarLinii; i++)
{
tablouBiDimensional[i] = new int[numarColoane];
for (int j = 0; j < numarColoane; j++)
tablouBiDimensional[i][j] = uniformDistribution(randomEngine);
}
return tablouBiDimensional;
}
static void afiseazaMatrice(int **tablouBiDimensional, int numarLinii, int numarColoane)
{
for (int i = 0; i < numarLinii; i++)
{
for (int j = 0; j < numarColoane; j++)
std::cout << tablouBiDimensional[i][j] << " ";
std::cout << "\n";
}
}
static void interschimbareValori(int **tablouBiDimensional, int numarLinii, int valCol1, int valCol2)
{
valCol1--;
valCol2--;
for (int i = 0; i < numarLinii; i++)
{
int numarTemp{};
numarTemp = tablouBiDimensional[i][valCol1];
tablouBiDimensional[i][valCol1] = tablouBiDimensional[i][valCol2];
tablouBiDimensional[i][valCol2] = numarTemp;
}
}
static void elibereazaMemoria(int **tablouBiDimensional, int numarLinii)
{
for (int i = 0; i < numarLinii; i++)
delete[] tablouBiDimensional[i];
delete[] tablouBiDimensional;
tablouBiDimensional = nullptr;
}
int main()
{
int numarLinii{}, numarColoane{};
std::cout << "Introdu numarul de linii >> ";
std::cin >> numarLinii;
std::cout << "Introdu numarul de coloane >> ";
std::cin >> numarColoane;
int **tablouBiDimensional = creazaTablouBiDimensional(numarLinii, numarColoane);
std::cout << "Matricea inainte de interschimbare:\n";
afiseazaMatrice(tablouBiDimensional, numarLinii, numarColoane);
int valCol1{}, valCol2{};
std::cout << "Introdu numerele coloanelor pe care vrei sa le interschimbi (de ex 1 3) >> ";
std::cin >> valCol1 >> valCol2;
if (valCol1 > numarColoane || valCol2 > numarColoane || valCol1 < 0 || valCol2 < 0)
exit(EXIT_FAILURE);
interschimbareValori(tablouBiDimensional, numarLinii, valCol1, valCol2);
std::cout << "Dupa interschimbare:\n";
afiseazaMatrice(tablouBiDimensional, numarLinii, numarColoane);
elibereazaMemoria(tablouBiDimensional, numarLinii);
return 0;
}
Explicație: