I'm new at C and I'm trying to solve this problem. Here is the code.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int my_rand_arr(int a, int b);
void random_arr(int arr[], int n);
void output_arr(int arr[], int n);
int main(){
srand(time(0));
const int N = 20;
int arr[N];
random_arr(arr, N);
output_arr(arr, N);
return 0;
}
int my_rand_arr(int a, int b){
return rand() % (b - a 1) a;
}
void random_arr(int arr[], int n){
for(int i = 0; i < n; i ){
arr[i] = my_rand_arr(1, 6);
}
}
void output_arr(int arr[], int n){
for(int i = 0; i < n; i ){
if(arr[i] == arr[i 1]){
cout << "(";
}
cout << arr[i] << " ";
}
cout << endl;
}
It is random array and the thing I'm trying to achieve is that if there is a couple of equal adjacent numbers, those numbers will be written inside brackets.
Expected output:
1 6 3 (1 1) 6 2 (4 4 4) 3 6 1 5 6 5 2 1 (5 5)
What should I do in order to achieve that output?
CodePudding user response:
Just count the number of repetitons of each element and print the elements when reaching the a different element or the end of the array.
void output_arr(int arr[], size_t const n) {
auto pos = arr;
auto const end = arr n;
while (pos != end)
{
size_t count = 1;
auto const element = *pos;
for ( pos; pos != end && *pos == element; pos, count)
{
}
if (count == 1)
{
std::cout << element << ' ';
}
else
{
std::cout << '(' << element;
for (; count != 1; --count)
{
std::cout << ' ' << element;
}
std::cout << ") ";
}
}
std::cout << '\n';
}
int main() {
int arr[] = { 1, 6, 3, 1, 1, 6, 2, 4, 4, 4, 3, 6, 1, 5, 6, 5, 2, 1, 5, 5 };
output_arr(arr, sizeof(arr) / sizeof(*arr));
}
CodePudding user response:
Before evaluating the expression arr[i] == arr[i 1]
, you must verify that n 1
is not out of bounds of the array. Otherwise your program will invoke undefined behavior.
Here is my solution to the problem:
#include <iostream>
void output_arr( int arr[], int n )
{
for ( int i = 0; i < n; i )
{
//determine whether there are adjacent identical numbers
if ( i 1 != n && arr[i] == arr[i 1] )
{
//only add space if we are not at the start of the line
if ( i != 0 )
std::cout << ' ';
//print opening parenthesis and first number of repetition
std::cout << '(' << arr[i];
//print remaining numbers of repetition
do
{
i ;
std::cout << ' ' << arr[i];
} while ( i 1 != n && arr[i] == arr[i 1] );
//print closing parenthesis
std::cout << ')';
}
else
{
//only add space if we are not at the start of the line
if ( i != 0 )
std::cout << ' ';
//print non-repeating number without parentheses
std::cout << arr[i];
}
}
//finish line
std::cout << '\n';
}
int main()
{
int arr[] = { 1, 6, 3, 1, 1, 6, 2, 4, 4, 4, 3, 6, 1, 5, 6, 5, 2, 1, 5, 5 };
output_arr( arr, sizeof arr / sizeof *arr );
}
This program has the desired output:
1 6 3 (1 1) 6 2 (4 4 4) 3 6 1 5 6 5 2 1 (5 5)