Mathematical notation to programming code - java

I have difficulties with transcripting the following two functions written in mathematical notation into Java code (the input of both functions is an array with D elements):
Can somebody take a look at the code below and tell me if something is wrong with it?
public double firstFunction(double[] arrayOfElements) {
double sum = 0;
double sumTwo = 0;
for(int i = 0; i < arrayOfElements.length; i++) {
for(int j = 0; j < i; j++){
sumTwo = sumTwo + arrayOfElements[j];
}
sum = sum + Math.pow(sumTwo, 2);
}
return sum;
}
public double secondFunction(double[] arrayOfElements) {
double maximum = Math.abs(arrayOfElements[0]);
for (int i = 0; i < arrayOfElements.length; i++) {
if (Math.abs(arrayOfElements[i]) > maximum) {
maximum = Math.abs(arrayOfElements[i]);
}
}
return maximum;
}

The first method should reset sumTwo to zero in every iteration. Currently it accumulates values from one execution of the outer loop to the next. Otherwise it's OK.
Alternatively, and more efficiently, you could notice that the difference between the sumTwo of one iteration and the next is the new array element. This means you don't need the inner loop.
for(int i = 0; i < arrayOfElements.length; i++) {
sumTwo = sumTwo + arrayOfElements[j];
sum = sum + Math.pow(sumTwo, 2);
}
The second method is supposed to return the index of the element with maximum absolute value, not the element itself. Note the subindex i in max.

Related

How to check how long it takes to sort out random integers using bubblesort in java?

I want to see how long it takes for 10,000 random integers to be sorted. Since in a bubblesort, the arrays are sorted at each stage and it could also vary each time, I want to know the total time it takes for the final sorting array to appear. So my time calculations should be when each sorting of the array is taking place, and when the final sorting happens and the results appear, the output should tell me the time in seconds.
I have used System.currentTimeMillis(); for this task but how would I use it so it calculates the time at each sorting stage? I have used it inside the for (int k = 0; k < numbers.length; k++){ loop because this loops through all the stages of the sorting, but my program would not output anything. How would I fix that?
Code:
class Main {
public static void main(String[] args) {
// Clear screen
System.out.print("\033[H\033[2J");
System.out.flush();
double msStartTime = 0d;
double msEndTime = 0d;
// Initialize an int array variable and set the limit to 10,000
int numbers[] = new int[10000];
// Generate random 10,000 integers to bubblesort
for (int x = 0; x < numbers.length; x++) {
numbers[x] = (int) (Math.random() * 10001);
}
for (int i = 0; i < numbers.length; i++) {
for (int j = i; j < numbers.length; j++) {
if (numbers[j] < numbers[i]) {
int temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
for (int k = 0; k < numbers.length; k++){
msStartTime = (double) System.currentTimeMillis();
}
}
msEndTime = (double) System.currentTimeMillis();
System.out
.println("To sort an array of 10,000 integers, it takes " + (msEndTime - msStartTime) / 1000 + " seconds");
}
}
i think you can use StopWatch.here is how u can add it to maven and use it
https://www.baeldung.com/java-measure-elapsed-time

Modifying a static method to add two counters when comparing arrays using for loops in Java

Using this segment of code I already have, I want to modify the selectionSort method to have two counters, one for the number of comparisons, and one for the number of data swaps. Each time two data elements are compared (regardless of whether the items are in the correct order—we're interested in that a comparison is being done at all), increment the comparison counter. Each time two data items are actually swapped, increment the data swap counter.
So far this is what I have tried to add the counters. However, I receive an error "Unresolved compilation problem: counter cannot be resolved to a variable".
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
int counter = 0;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
counter += 1;
}
System.out.println("The size of the sorted array is " + list.length + " and the count is " + counter);
}
I have the main method prepared below.
public static void main(String[] args) {
final int NUM_ELEMENTS = 10;
double[] lo2Hi = new double[NUM_ELEMENTS];
for (int i = 0; i < NUM_ELEMENTS; i++) {
lo2Hi[i] = i + 1;
}
selectionSort(lo2Hi);
double[] hi2Lo = new double[NUM_ELEMENTS];
for (int i = 0; i < NUM_ELEMENTS; i++) {
hi2Lo[i] = 10 - i;
}
selectionSort(hi2Lo);
double[] random = new double[NUM_ELEMENTS];
for (int i = 0; i < random.length; i++) {
random[i] = Math.random();
}
selectionSort(random);
}
Your println() at the end of selectionSort() is trying to acces the variable counter, but counter is "out of scope" at that point. Variables only exist within the pair of {}'s they were declared inside (that's what "scope" is).
Move the int counter = 0; statement out of the for loop, and put it at top of the method. Then it will be in-scope for the print statement.

Locate the largest element in a multidimensional arrays

I have to write a program using a method that returns the location of the largest element in a two dimensional array.
example
Enter the number of rows and columns of the array:
3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
the location of the largest element is at (1, 2)
I have finished my code but it isn't working. How can I fix it? All I got are the following errors:
symbol : variable maxvalue
location: class int[]
if (a[i][j] > largest.maxvalue)
^
homework1a.java:51: row is already defined in locateLargest(double[][])
double row = i;
^
homework1a.java:52: column is already defined in locateLargest(double[][])
double column = j;
^
homework1a.java:53: maxValue is already defined in locateLargest(double[][])
double maxValue = a[i][j];
^
homework1a.java:88: i is already defined in main(java.lang.String[])
for (int i = 0; i < 2; i++)
^
5 errors
My code
import java.util.Scanner;
public class hwm1 {
public static int[] locateLargest(double[][] a)
{
int[] largest = new int[2];
double row = 0;
double column = 0;
double maxValue = a[0][0];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a.length; j++)
{
if (a[i][j] > largest.maxvalue)
{
double row = i;
double column = j;
double maxValue = a[i][j];
}
}
}
return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);
//User input rows and columns
System.out.println("Enter the number of rows and columns in the array: ");
int numberOfRows = input.nextInt();
int numberOfColumns = input.nextInt();
//User input data in array
System.out.println("Enter numbers into array: ");
//Create array
double[][] a = new double[numberOfRows][numberOfColumns];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
a[i][j] = input.nextDouble();
}
int[] largest = locateLargest(a);
System.out.println("The location of the largest element is at "+ "("+largest[0] +", " + largest[1] + ")");
for (int i = 0; i < 2; i++)
{
System.out.print(largest[i]);
}
}
}
}
You are declaring the variables row, column and maxValue twice.
Also, in the line:
if (a[i][j] > largest.maxvalue)
There is no such thing as maxvalue in your code, and neither is it a member of largest
In this part of your code:
Since i is already declared in the outer for-loop, you don't need to declare it again. Just use:
...
for(i = 0; i < 2; i++){
...
}
homework1a.java:51:, homework1a.java:52:, homework1a.java:53:
For these three, remove 'double'. If you state the type when referencing the variable, Java will assume you are trying to define the variable in question. Here you already have those three defined. Additionally, since you don't use row or column at all, I suggest that you simply remove them.
homework1a.java:88: i is already defined in main(java.lang.String[])
For this one, you have a nested for loop, but it uses i as well. You should use k for the second of the nested for loops (the one after the one using j).
. You don't need to post full code below code snippet is sufficient
double row = 0; //declaring first time
double column = 0;//declaring first time
double maxValue = a[0][0];//declaring first time
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a.length; j++)
{
if (a[i][j] > largest.maxvalue)// there is no variable maxvalue in Array class in java
{
double row = i; // declaring again
double column = j;// declaring again
double maxValue = a[i][j];// declaring again
}
}
}
return largest;
Issues:
Loop on j should be using a[i].length
the lines in if block is re-declaring the variables, remove the keyword 'double '
You are not declaring setting largest anywhere so you have a logic issue
Using a largest.maxValue is logically incorrect as it should contain the row and column number and not the actual max value
I would solve this by re-writing the code as follows which I believe is the most efficient way of achieving the goal:
public static int[] locateLargest(double[][] a)
{
int maxRow=-1,maxCol=-1;
double maxVal=-1;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
if (a[i][j] > maxVal)
{
maxRow = i;
maxCol = j;
maxVal = a[i][j];
}
}
}
return new int[]{maxRow,maxCol};
}
Good luck!

Raising a matrix to the power method JAVA

I am having a really hard time creating a method to raise a matrix to the power. I tried using this
public static int powerMethod(int matrix, int power) {
int temp = matrix ;
for (int i = power; i == 1; i--)
temp = temp * matrix ;
return temp ;
but the return is WAYYY off. Only the first (1,1) matrix element is on point.
I tried using that method in a main like so
// Multiplying matrices
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
for (l = 0; l < row; l++)
{
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
// Solving Power of matrix
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
Where "power", "row", and "column" is an int that the user enters.
Any ideas how I can do this??
Thanks!!!
You have a lot of issues here.
First, your matrix squaring algorithm has a (common) error. You have:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
for (l = 0; l < row; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
However, you need to store the result in a temporary second matrix, because when you do matrix[i][j] = sum, it replaces the value at that position with the output, then later results end up being incorrect. Also I suggest initializing sum to 0 first, since it appears you declare it outside of this loop, and initializing it first protects you against any arbitrary value sum may have before going into the loop. Furthermore, it is not immediately clear what you mean by row and column -- make sure you are iterating over the entire matrix. E.g.:
int temp[][] = new int[matrix.length];
for (i = 0; i < matrix.length; i++) {
temp[i] = new int[matrix[i].length];
for (j = 0; j < matrix[i].length; j++) {
sum = 0 ;
for (l = 0; l < matrix.length; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
temp[i][j] = sum ;
}
}
// the result is now in 'temp', you could do this if you wanted:
matrix = temp;
Note that matrix.length and matrix[i].length are fairly interchangeable above if the matrix is square (which it must be, in order to be multiplied by itself).
Secondly, your multiplication squares a matrix. This means if you repeatedly apply it, you keep squaring the matrix every time, which means you will only be able to compute powers that are themselves powers of two.
Your third issue is your final bit doesn't make much sense:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
It's not immediately clear what you are trying to do here. The final part seems to be trying to raise individual elements to a certain power. But this is not the same as raising a matrix to a power.
What you need to do is define a proper matrix multiplication method that can multiply two arbitrary matrices, e.g.:
int[][] multiplyMatrices (int[][] a, int[][] b) {
// compute and return a x b, similar to your existing multiplication
// algorithm, and of course taking into account the comments about
// the 'temp' output matrix above
}
Then computing a power becomes straightforward:
int[][] powerMatrix (int[][] a, int p) {
int[][] result = a;
for (int n = 1; n < p; ++ n)
result = multiplyMatrices(result, a);
return result;
}
Why not just use Math.pow?
import java.lang.Math;
Then you just have to do
matrixFinal[power][i][j] = (int) Math.pow(matrix[i][j],power); //might have to cast this to an int

Hosoya Triangle in java

Objective: Individually, create a recursive representation of Hosoya’s triangle.
Your task: Haru Hosoya, a famous mathematician described a triangle (seen below) which is a triangular arrangement of numbers based on the Fibonacci numbers. Get a height from the user and use an array to store the values on each line. Print out the appropriate number of levels of Hosoya’s triangle using a recursive method. Do NOT assume that the input will be good. You should also implement try…catch blocks to catch erroneous input.
Here is the code I have so far:
public class HosoyaTri {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean continueLoop = true;
int num = s.nextInt();
do {
try {
System.out.println("How many levels?");
System.out.println(num + " levels");
continueLoop = false;
} catch (InputMismatchException im) {
System.err.println("I said INTEGER, try again");
s.nextLine();
} catch (Exception e) {
System.err.println("What did you do?");
}
} while (continueLoop);
int triangle[][] = new int[num][num];
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
triangle[i][j] = 0;
}
}
for (int i = 0; i < num; i++) {
triangle[i][0] = 1;
}
for (int i = 1; i < num; i++) {
for (int j = 1; j < num; j++) {
triangle[i][j] = triangle[i - 1][j - 1] * triangle[i - 1][j];
}
}
for (int i = 0; i < num; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
One problem is that you are reading the number of levels once, before the input loop. You are then prompting for a level and then printing num without giving the user any chance to provide input! You should fix that. You should also be testing against num <= 0.
As far as how to use recursion goes, the entries in Hosoya's triangle can be defined recursively:
H0, 0 = H1, 0 = H1, 1 = H2, 1 = 1
Hn, j = Hn−1, j + Hn−2, j or
Hn, j = Hn−1, j−1 + Hn−2, j−2
Another (equivalent) definition is:
Hn, i = Fi+1 × Fn−i+1
where Fn is the nth Fibonacci number, defined recursively as:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2 (n > 1)
I would suggest using one of these definitions to write a (recursive) static method in your class that calculates the correct value for one entry in the triangle (given n and j as arguments). Then you can eliminate the triangle variable and all the code that initializes it. Simply run your output loop and substitute a call to the recursive method where you now access a specific element of triangle. (If for some reason you need to explicitly build the triangle, simply initialize each element by calling the recursive method. As an aside: there's no need to initialize the elements of triangle to 0; Java does that automatically when the matrix is allocated.)

Categories

Resources