Friday, 31 July 2015

The Secret Number Simple Algorithm Solution.

/*
The Secret Number
All numbers from 1 to N have been inserted into an array of N-1 integers in random order, except for the secret number. Assuming it is less than N, find the secret number in the given array.
Example
N=10,  Array: [6, 8, 3, 10, 1, 9, 2, 5, 7]
Missing Number: 4

N=5, Array: [5, 2, 4, 1]
Missing Number: 3


Input 1 (A) → array.integer :

Array with N-1 numbers (only missing the 'Secret number')
Output → integer :

The missing number
Tag: C++ , Algorithm, Code Fight, Searching Algorithm, Array. 
*/

Solution:

#include <bits/stdc++.h>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int missingNumber(vector< int > A) {

   sort(A.begin(),A.end());
   int number = 0;                        //assigning zero here because of test-case 1.
   for(int i = 0; i < A.size(); i++){
      number ++;
      if(number != A[i])break;
   }
   return number;
}
int main() {

   int n,a;
   vector<int>v;
   cin >> n;
   for(int i = 0; i < n; i++){
      cin >> a;
      v.push_back(a);
   }
   cout << missingNumber(v) << endl;
   return 0;
}

Given an array of integers, find the product of its elements Simple Algorithm Solution.

/*
Given an array of integers, find the product of its elements.
Example
for [1, 3, 2, 10] output should be 60
[input] array.integer inputArray
non-empty array of integers
[output] integer
product of all elements of inputArray

Tag: Algorithm , C++, Code Fight , Array.
*/

Solution:

#include <bits/stdc++.h>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int arrayProduct(vector<int> inputArray) {

   int result = 1;
   for (int i = 0; i < inputArray.size(); i++)result*= inputArray[i];
   return result;
}
int main() {

   int n,a;
   vector<int>v;
   cin >> n;
   for(int i = 0; i < n; i++){
      cin >> a;
      v.push_back(a);
   }
   cout << arrayProduct(v) << endl;
   return 0;
}

Given an array of integers, find its minimal element Simple Algorithm Solution.

/*
Given an array of integers, find its minimal element.
Example
for [19, 32, 11, 23] output should be 11
[input] array.integer inputArray
[output] integer
the minimal element of inputArray
Tag: Algorithm,Easy Solution , Array, Code Fight.
*/

Solution:

#include <bits/stdc++.h>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int arrayMinimum(vector<int> inputArray) {

  int indexOfMinimum = 0;
  for (int i = 1; i < inputArray.size(); i++) {
    if (inputArray[i] < inputArray[indexOfMinimum]) {
      indexOfMinimum = i;
    }
  }
  return inputArray[indexOfMinimum];
}
int main() {

   int n,a;
   vector<int>v;
   cin >> n;
   for(int i = 0; i < n; i++){
      cin >> a;
      v.push_back(a);
   }
   cout << arrayMinimum(v) << endl;
   return 0;
}