Checking the numbers in an array and then comparing their values - c++

Where do i fix the code in a way so that, i can check if the numbers in any row has equal values (e.g : if the matrix is 3*3 then for instance for the first row every number is 1)
#include <iostream>
using namespace std;
int main ()
{
int n;
cout<< "Kvadrat husnegtiin iremb:" <<endl ;
cin>> n;
int A[n][n];
for (int i = 0 ; i < n ; ++i )
{
for (int j = 0 ; j < n; ++j )
{
cout<< "["<< i<< "]"<< "["<< j<< "]"<< " Element"<< endl;
cin>> A[i][j] ;
}
}
for ( int i = 0 ; i < n ; ++i )
{
int B1 = A [i] [0] ;
for ( int j = 0 ; j < n; ++j )
{
if (B1 == A [i] [j] )
{
cout<< i<< "Baina"<< endl;
}
}
}
}

You can use a flag to check if there's a different value in your loop.
In example :
for (int i = 0; i < n; ++i)
{
int B1 = A[i][0];
bool IsDifferent = false;
for (int j = 0; !IsDifferent && j < n; ++j)
{
if (B1 != A[i][j]) //Notice the inverted condition
{
IsDifferent = true;
}
}
if (!IsDifferent)
cout << "Line " << i << " has equal values." << endl;
}

for ( int i = 0 ; i < n ; ++i ) {
bool all_equal = true;
for ( int j = 1 ; all_equal && j < n; ++j ) {
all_equal = A[i][j] == A[i][0];
}
if ( all_equal )
cout << "row " << i << " has equal values" << endl;
}

Related

Selection sort not grabbing last element in array

void ProcessSort(int studentIDs[], string studentNames[], int num)
{
for (int i = 0; i < num - 1; i++)
{
int mindex = 0;
//DO6: finish the inner loop
// Hint: it should start from i+1 and go until num-1
// if studentNames[j] is greater than studentNames[mindex]
// then store j in mindex
for (int j = i+1; j < num - 1; j++) {
if (studentNames[mindex] < studentNames[j]) {
mindex = j;
}
}
//DO7: Swap student names
SwapNames(studentNames[mindex], studentNames[i]);
//DO8: Swap student IDs'
SwapIDs(studentIDs[mindex], studentIDs[i]);
}
cout << "Class List sorted by name." << endl;
}
Selection sort seems not to grab last element in array. There are two parallel arrays, one with names and one with ids, but it seems to be that the last name in the student names array isnt registered with the sort. Any help would be greatly appreciated.
The body of the outer loop should look at least like
int mindex = i;
//DO6: finish the inner loop
// Hint: it should start from i+1 and go until num-1
// if studentNames[j] is greater than studentNames[mindex]
// then store j in mindex
for (int j = i+1; j < num; j++) {
if (studentNames[mindex] < studentNames[j]) {
mindex = j;
}
}
This condition
if (studentNames[mindex] < studentNames[j]) {
provides sorting in the descending order.
Here is a demonstrative program.
#include <iostream>
#include <string>
#include <utility>
void ProcessSort( int studentIDs[], std::string studentNames[], size_t n )
{
for ( size_t i = 0; i < n; i++)
{
size_t mindex = i;
//DO6: finish the inner loop
// Hint: it should start from i+1 and go until num-1
// if studentNames[j] is greater than studentNames[mindex]
// then store j in mindex
for ( size_t j = i + 1; j < n; j++ )
{
if ( studentNames[mindex] < studentNames[j] ) mindex = j;
}
//DO7: Swap student names
if ( i != mindex )
{
std::swap( studentNames[mindex], studentNames[i] );
//DO8: Swap student IDs'
std::swap( studentIDs[mindex], studentIDs[i] );
}
}
}
int main()
{
int studentIDs[] = { 495, 520, 550, 666 };
std::string studentNames[] = { "Kyle", "Liam", "Bill", "Michael" };
const size_t N = sizeof( studentIDs ) / sizeof( *studentIDs );
for ( size_t i = 0; i < N; i++ )
{
std::cout << "( " << studentNames[i] << ", " << studentIDs[i] << " ) ";
}
std::cout << std::endl;
ProcessSort( studentIDs, studentNames, N );
for ( size_t i = 0; i < N; i++ )
{
std::cout << "( " << studentNames[i] << ", " << studentIDs[i] << " ) ";
}
std::cout << std::endl;
return 0;
}
Its output is
( Kyle, 495 ) ( Liam, 520 ) ( Bill, 550 ) ( Michael, 666 )
( Michael, 666 ) ( Liam, 520 ) ( Kyle, 495 ) ( Bill, 550 )

Sort a matrix by the sum of the rows

I have to sort the matrix by the sum of the rows, the smallets sum has to be first and the the bigger and at the end has to be the biggest sum.
I have done this but I can't finish it:
#include <iostream>
using namespace std;
int main ()
{
int **matrix;
int i, j, count, row, col, sum, temp;
cout << "\n Enter the number of rows and columns";
cin >> row >> col;
matrix = new int *[row];
for (count = 0; count < row; count++)
matrix[count] = new int[col];
cout << "\nNow enter the element for the matrix.";
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
cout << "\nRow " << (i + 1) << " Col " << (j + 1) << " :";
cin >> *(*(matrix + i) + j);
}
}
for (i = 0; i < row; i++)
{
sum = 0;
for (j = 0; j < col; j++)
sum = sum + matrix[i][j];
cout << sum << endl;
}
for (int count = 0; count < row; count++)
delete[]matrix[count];
delete[]matrix;
matrix = 0;
return 0;
}
You can use standard algorithms std::sort and std::accumulate. Below there is a demonstrative program that shows how these algorithms can be used together.
#include <iostream>
#include <algorithm>
#include <numeric>
#include <cstdlib>
#include <ctime>
int main()
{
const size_t M = 3, N = 5;
std::srand( ( unsigned int )std::time( nullptr ) );
int **matrix = new int *[M];
for ( size_t i = 0; i < M; i++ ) matrix[i] = new int[N];
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) matrix[i][j] = std::rand() % ( M * N );
}
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) std::cout << matrix[i][j] << ' ';
std::cout << '\n';
}
std::cout << '\n';
auto sort_by_sum = [N]( const auto &left, const auto &right )
{
return std::accumulate( left, left + N, 0ll ) <
std::accumulate( right, right + N, 0ll );
};
std::sort( matrix, matrix + M, sort_by_sum );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) std::cout << matrix[i][j] << ' ';
std::cout << '\n';
}
std::cout << '\n';
return 0;
}
The program output might look like
11 2 4 14 0
9 7 9 4 14
10 7 5 0 7
10 7 5 0 7
11 2 4 14 0
9 7 9 4 14

Bubble sort logical error?

I am trying to do a bubble sort, but I don't know what's happening in my code. I am a noob so sorry if the code I wrote seems obvious ^.^
main() {
int a[5], i, j, smallest, temp;
cout << "Enter 5 numbers: " << endl;
for ( i = 0; i <= 4; i++ ) {
cin >> a[i];
}
for ( i = 0; i <=4; i++ ) {
smallest = a[i];
for ( j = 1; j <= 4; j++ ) {
if ( smallest > a[j] ) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
cout << endl << endl;
for ( i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
system("pause");
}
Any answer will be highly appreciated. Thanks!
Your bubblesort almost appears to be a selection sort. Bubblesort looks at pairs of items and swaps them if necessary. Selection sort looks for the lowest item in the rest of the array, and then swaps.
#include <iostream>
#include <utility>
using std::cin;
using std::cout;
using std::endl;
using std::swap;
void bubblesort(int a[5])
{
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < 4; i++)
{
if (a[i] > a[i + 1])
{
swap(a[i], a[i + 1]);
swapped = true;
}
}
}
}
void selectionSort(int a[5])
{
for (int i = 0; i < 4; i++)
{
int smallest = i;
for (int j = smallest; j < 5; j++)
{
if (a[smallest] > a[j])
{
smallest = j;
}
}
if (smallest != i)
{
swap(a[i], a[smallest]);
}
}
}
int main(int argc, char* argv[])
{
int a[5];
cout << "Enter 5 numbers: " << endl;
for (int i = 0; i < 5; i++ )
{
cin >> a[i];
}
//selectionSort(a);
bubblesort(a);
cout << endl << endl;
for (int i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
}

c++ read each 3 elements in array

I am working on a project and i want to print in order each 3 elements of a string array.So if the string is "cadgfacbda" i want to be printed in the console :
**"cad gfa cbd a"**
This is the code :
string str("cadgfacbda");
for(int i = 0 ; i < 3 ; i++)
{
for(int j = i ; j < str.size() ; j +=3 )
{
cout << str[j]<<" ";
}
cout<<endl;
}
But what i get is :
c g c a
a f b
d a d
Code in one loop only:
string str("cadgfacbda");
for(int i = 0 ; i < str.size() ; i++) {
if(i && i%3==0)
cout<<" ";
cout << str[i];
}
cout<<endl;
I think it should go something like this:
string str("cadgfacbda");
for(int i = 0 ; i < str.size() ; i++)
{
cout << str[j]<<" ";
if( i % 3 == 0 )
cout<<endl;
}
This ofcourse assumes you need new line after every three elements. If you just need spaces then you can try this instead:
string str("cadgfacbda");
for(int i = 0 ; i < str.size() ; i++)
{
cout << str[j];
if( i % 3 == 0 )
cout<<" ";
}
int main()
{
typedef std::string::size_type size_type;
std::string str("cadgfacbda");
const size_type STEP_SIZE = 3;
for(size_type i = 0 ; i < str.size() ; i+=STEP_SIZE)
{
std::cout << str.substr(i, STEP_SIZE) << " ";
}
std::cout << std::endl;
return 0;
}
#include<stdio.h>
#include<string.h>
#include<string>
int main()
{
string str("cadgfacbda");
char arr[]=str.to_char();
for(int i=1;i<=strlen(arr);i++)
{
printf("%c",arr[i-1]);
if(i%3==0)
{
printf(" ");
}
}
}
This should work too:
int main()
{
std::string str = "cadgfacbda";
for (int i = 0; i < str.length()-3; i++)
{
for (int j = 0; j < 3; ++j)
{
if ((3 * i + j) < str.length())
std::cout << str[3 * i + j];
}
std::cout << " ";
}
return 0;
}
This should work :
string str("cadgfacbda");
for(int i = 0 ; i < str.size() ; i++)
{
if(i % 3 == 0 && i != 0) cout << " ";
cout << str[i];
}
cout << endl;
A bit late I suppose but you could just substring.
std::string str("cadgfacbda");
for (std::size_t i = 0; i < str.size(); i += 3) {
std::cout << str.substr(i, 3) << " ";
}
This saves you a ton of code and is imo more readable.
Live example

Incorrect Result from Selection Sort Algorithm

#include <iostream>
using namespace std;
// Selection Sort function.
// Parameter 'a' is the size of the array.
void ss(int AR[] , int a) {
int small;
for (int i = 0 ; i <a ; i++) {
small = AR[i];
for (int j = i+1 ; j <a ; j++) {
if (AR[j]< small) {
int k = AR[j];
AR[j] = AR[i];
AR[i] = k;
}
}
}
}
int main() {
cout << "Enter the size of Your Aray";
int a;
cin >> a;
int AR[a];
cout << endl;
for (int i = 0; i < a; i++) {
cin >> AR[i];
cout << endl;
}
ss(AR, a);
cout << "The Sorted Array is";
for (int i=0; i < a; i++) {
cout << AR[i] << " ";
cout << endl;
}
}
When I enter the following:
15
6
13
22
23
52
2
The result returned is:
2
13
6
15
22
23
52
What is the bug preventing the list from being sorted numerically as expected?
The function can look like
void ss ( int a[], size_t n )
{
for ( size_t i = 0 ; i < n ; i++ )
{
size _t small = i;
for ( size_t j = i + 1; j < n ; j++ )
{
if ( a[j] < a[small] ) small = j;
}
if ( i != small )
{
int tmp = a[small];
a[small] = a[i];
a[i] = tmp;
}
}
}
It doesn't seem to be the SelectionSort I know. in the algorithm I know during every loop I look for the smallest element in the right subarray and than exchange it with the "pivot" element of the loop. Here's the algorithm
void selectionSort(int* a, int dim)
{
int posMin , aux;
for(int i = 0; i < dim - 1; ++i)
{
posMin = i;
for(int j = i + 1; j < dim; ++j)
{
if(a[j] < a[posMin])
posMin = j;
}
aux = a[i];
a[i] = a[posMin];
a[posMin] = aux;
}
}
and it seems that you change every smaller element you find, but also change the position of the "pivot". I hope the answer is clear.
Everything is ok in the original function, only that the small variable need to be refreshed when two vector elements will be switched.
Also in if statement set the small variable to the new value of AR[i].