Array (Example 2)

Concepts:
Arrays, initialization and utilization

Text:
Implement a C program that:

As an example, given the array:

int v[DIM_VETT] = {2, 2, 3, 3, 3, 4, 2, 2, 4, 3, 3, 3, 3, 5, 5, 6, 1, 2, 3, 3};

the program must provide the following output:

Value 2 repeated 2 times, starting form the position 0
Value 3 repeated 3 times, starting form the position 2
Value 2 repeated 2 times, starting form the position 6
Value 3 repeated 4 times, starting form the position 9
Value 5 repeated 2 times, starting form the position 13
Value 3 repeated 2 times, starting form the position 18

Solution:

array_2.c
/*******************************************
 Given the vector, for instance:
 v:      2   2   3   3   3   4   2   2   4   3   3   3   3   5   5   6   1   2   3   3
 whose elements are in the positions
 POS :   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19
 
 find the equal adjacent values that are repeated more than one time
 in the vector, indicating the first element of the repetition
 and the number of adjacent repeated elements.
 
 In the case of the array of the example,
 the output of the program should be:
 
 Value 2 repeated 2 times, starting form the position 0
 Value 3 repeated 3 times, starting form the position 2
 Value 2 repeated 2 times, starting form the position 6
 Value 3 repeated 4 times, starting form the position 9
 Value 5 repeated 2 times, starting form the position 13
 Value 3 repeated 2 times, starting form the position 18
 
 *******************************************/
 
#include <stdio.h>
 
 
#define DIM_VETT 20
 
int main(){
 
  int v[DIM_VETT] = {2, 2, 3, 3, 3, 4, 2, 2, 4, 3, 3, 3, 3, 5, 5, 6, 1, 2, 3, 3};
  int i, j, n_rep, pos;
 
  /* Print the array */
  printf("VETT: ");
  for(i=0; i<DIM_VETT; i++)
    printf("%3d ", v[i]);
  printf("\n");
 
  /* Print the position of the vector elements */
  printf("POS : ");
  for(i=0; i<DIM_VETT; i++)
    printf("%3d ", i);
  printf("\n");
 
  /* First solution */
  printf("\nSOLUTION 1\n");
  i = 0;
  pos = 0;
  n_rep = 1;
 
  for(i=0; i<DIM_VETT-1; i++){
 
    if(v[i]==v[i+1]){
      n_rep++;
    }else{
      if(n_rep>1){
        printf("Value %d repeated %d times, starting form the position %d\n", v[i], n_rep, pos);
      }
      n_rep = 1;
      pos = i+1;
    }
  }
 
  if(n_rep>1){
    printf("Value %d repeated %d times, starting form the position %d\n", v[i], n_rep, pos);
  }
 
  /* Second solution */
  printf("\nSOLUTION 2\n");
  i=0;
  while(i<DIM_VETT-1){
    pos = i;
    n_rep = 1;
 
    j = i+1;
    while(v[i]==v[j] && j < DIM_VETT){
      n_rep++;
      j++;
    }
 
    if(n_rep>1){
      printf("Value %d repeated %d times, starting form the position %d\n", v[i], n_rep, pos);
      i = j;
    }else{
      i++;
    }
  }
}