Convert given array to Arithmetic Progression by adding an element in C++


In this tutorial, we will be discussing a program to convert given array to arithmetic progression by adding an element.

For this we will be provided with an array. Our task is to convert the given array into an arithmetic progression by adding a single element to it and return the added element. If it is not possible, return -1.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
//returning the number to be added
int print_number(int arr[], int n){
   sort(arr,arr+n);
   int d = arr[1] - arr[0];
   int numToAdd = -1;
   bool numAdded = false;
   for (int i = 2; i < n; i++) {
      int diff = arr[i] - arr[i - 1];
      if (diff != d) {
         if (numAdded)
            return -1;
         if (diff == 2 * d) {
            numToAdd = arr[i] - d;
            //if number has been added
            numAdded = true;
         }
         //if not possible
         else
         return -1;
      }
   }
   //returning last element +
   //common difference
   if (numToAdd == -1)
      return (arr[n - 1] + d);
   //else return the chosen number
   return numToAdd;
}
int main() {
   int arr[] = { 1, 3, 5, 7, 11, 13, 15 };
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << print_number(arr, n);
}

OUTPUT

9
raja
Published on 16-Jan-2020 07:28:47
Advertisements