In: Computer Science
From the MathWorks Cody Challenges (Problem 9).
You have a matrix for which each row is a person and the columns represent the number of quarters, nickels, dimes, and pennies that person has (in that order). What is the row index of the person with the most money?
Note for those unfamiliar with American coins: quarter = $0.25, nickel = $0.05, dime = $0.10, penny = $0.01.
Example:
Input a = [1 0 0 0; 0 1 0 0]
Output b = 1
since the first person will have $0.25 and the second person will have only $0.05.
TASKS:
a. The first version is to be done without the use of matrix multiplication; instead, use for loop(s) to find the total value of the coins held by each player. Pseudocodefor this version:
%% Initialize variables for (1) most money seen so far (say, M = -1), and
%% (2) which was the first player to have that amount (say, b = 0).
%% Use the size() function to find the total number of players (number of rows in matrix a)
%% For each player:
%% find the value of all their change
%% if that value is the largest seen so far,
%% update the most money seen so far
%% and the first player to have that amount.
%% Return with the maximum value found and which player had that amount
import java.util.*;
class max
{
public static void main(String[] args)
{
Scanner sc=new Scanner (System.in);
System.out.println("Ënter the no of persons you want to take as input");
int n=sc.nextInt();
int i,j,l;
int arr[][]=new int[n][4];
//taking array as input
for(i=0;i<n;i++)
{
for(j=0;j<4;j++)
{
arr[i][j]=sc.nextInt();
}
}
l=arr.length;
double ans[]=new double[2];
ans=most_change(arr,l);
System.out.println("max value="+ans[0]);
System.out.println((int)ans[1]+"person has the max amount");
}
private static double[] most_change(int[][] arr, int l) {
// TODO Auto-generated method stub
double ans[]=new double[2];
int i,j;
double value=0;
double max=-1;
int p=-1;
for(i=0;i<l;i++)
{
value=0;
for(j=0;j<4;j++)
{
if(j==0)
value+=(double) (arr[i][j]*0.25);
if(j==1)
value+=(double) (arr[i][j]*0.05);
if(j==2)
value+=(double) (arr[i][j]*0.10);
if(j==3)
value+=(double) (arr[i][j]*0.01);
}
if(value>max)
{
max=value;
p=i+1;
}
}
ans[0]=max;
ans[1]=p;
return(ans);
}
}
Since no language was mentioned, I have written the code in java I could not use size function... If you want to write in some other language you may use that function.This code is fully compiled and executed with no errors.