Concentration of juice after mixing n glasses in equal proportion
Given an array arr[] where arr[i] is the concentration of juice in ith glass. The task is to find the concentration of the resultant mixture when all the glasses are mixed in equal proportions.
Examples:
Input: arr[] = {10, 20, 30}
Output: 20
Input: arr[] = {0, 20, 20}
Output: 13.3333
Approach: Since the juices are mixed in equal proportions so the resultant concentration will be the average of all the individual concentrations. Therefore the required answer would be sum(arr) / n where n is the size of the array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
double mixtureConcentration( int n, int p[])
{
double res = 0;
for ( int i = 0; i < n; i++)
res += p[i];
res /= n;
return res;
}
int main()
{
int arr[] = { 0, 20, 20 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << mixtureConcentration(n, arr);
}
|
C
#include <stdio.h>
double mixtureConcentration( int n, int p[])
{
double res = 0;
for ( int i = 0; i < n; i++)
res += p[i];
res /= n;
return res;
}
int main()
{
int arr[] = { 0, 20, 20 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "%f" , mixtureConcentration(n, arr));
}
|
Java
class GFG
{
static double mixtureConcentration( int n, int []p)
{
double res = 0 ;
for ( int i = 0 ; i < n; i++)
res += p[i];
res /= n;
return res;
}
public static void main (String[] args)
{
int []arr = { 0 , 20 , 20 };
int n = arr.length;
System.out.println(String.format( "%.4f" ,
mixtureConcentration(n, arr)));
}
}
|
Python3
def mixtureConcentration(n, p):
res = 0 ;
for i in range (n):
res + = p[i];
res / = n;
return res;
arr = [ 0 , 20 , 20 ];
n = len (arr);
print ( round (mixtureConcentration(n, arr), 4 ));
|
C#
using System;
class GFG
{
static double mixtureConcentration( int n, int []p)
{
double res = 0;
for ( int i = 0; i < n; i++)
res += p[i];
res /= n;
return Math.Round(res,4);
}
static void Main()
{
int []arr = { 0, 20, 20 };
int n = arr.Length;
Console.WriteLine(mixtureConcentration(n, arr));
}
}
|
PHP
<?php
function mixtureConcentration( $n , $p )
{
$res = 0;
for ( $i = 0; $i < $n ; $i ++)
$res += $p [ $i ];
$res /= $n ;
return $res ;
}
$arr = array ( 0, 20, 20 );
$n = count ( $arr );
print ( round (mixtureConcentration( $n , $arr ), 4));
?>
|
Javascript
<script>
function mixtureConcentration(n, p)
{
var res = 0;
for ( var i = 0; i < n; i++)
res += p[i];
res /= n;
return res;
}
var arr = [ 0, 20, 20 ];
var n = arr.length;
document.write(mixtureConcentration(n, arr).toFixed(4));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
23 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...