1) Write a method that accepts the length and width of a rectangle and returns the perimeter of the rectangle
double Perimeter(double length, double width) { return length*2 + width*2; }
2) Write a method that accepts the base and height of a triangle and returns the area of the triangle
double areaTriangle(double base, double height) { return 0.5*base*height; }
3) Write a method that accepts three integers as paramaters and returns the average of the integers.
double average(int a, int b, int c) { return((a+b+c)/3.0); }
4) Write a method that accepts an integer array as a parameter and returns the average of the values of that array.
double average(int [] numbers) { double av = 0; double total = 0; for(int n: numbers) { total += n; } return total/numbers.length; }
5) Write a method that accepts an integer array as a parameter and returns the minium value in that array
double min(int [] numbers) { int minVal = numbers[0]; for (int n : numbers) { if (n < minVal) minVal = n; } return minVal; }
or
double min(int [] numbers) { Arrays.sort(numbers); return numbers[0]; }
6) Write a method that returns the hypotenuse of a triangle when the other two sides are int a and int b. (Remember: hypotenuse squared equals a squared plus b squared)
double hypotenuse(double a, double b) { return Math.sqrt(a*a + b*b); }
7) The scalar product of u=(u1,u2,u3) and v=(v1,v2,v3) is defined to be u1v1+u2v2+u3v3. Write a method that accepts two int arrays as parameters and returns an int representing the scalar product of those two arrays
double scalarProduct(int [] u, int [] v) throws Exception { if (u.length != v.length) throw new Exception(); double product = 0; for(int i = 0; i<u.length; i++) { product += u[i]*v[i]; } return product; }
8) If A = (a1,a2, …an) and B = (b1,b2, …bn) then the vector sum of the two arrays A + B = (a1+b1, a2+b2, … , an+bn). Write a method that accepts two arrays as parameters and returns an array representing the vector sum of those two arrays.
double [] vectorSum(int [] u, int [] v) throws Exception { if (u.length != v.length) throw new Exception(); double [] sum = new double[u.length]; for(int i = 0; i<u.length; i++) { sum[i] = u[i] + v[i]; } return sum; }
9) The Euclidean distance between two points A = (a1,a2, …an) and B = (b1,b2, …bn) is defined as sqrt((a1-b1)2 + (a2-b2)2 +… + (an-bn)2). Write a method that accepts two int arrays representing A and B as parameters and returns a double representing the Euclidean distance between them.
double [] eDistance(int [] u, int [] v) throws Exception { if (u.length != v.length) throw new Exception(); double [] sum = new double[u.length]; double dist = 0; for(int i = 0; i<u.length; i++) { dist += Math.pow((u[i]-v[i]),2); } return sum; }