Finding plateau in Java Array - java

I having a really hard time finding a plateau within an array. What I'm looking for is length and location of the longest sequence of equal values where the numbers on both sides are smaller. Now I know there could be two or more valid plateaus with same length ideally I would like to print the plateau with a higher value.
I have created an array[40] and a Random obj. To fill the array, once I have filled it I know I will need a loop to check the indexes. But thats where the confusion comes in. I have tried using a for loop to find the plateau but my results would just increase the value stored within the index.
Any points in the right direction I would greatly appreciate it.
import java.util.Random;
public class Plateau {
public static void main(String[]args)
{
int[] array1 = new int[40];
Random genrator = new Random();
for (int i = 0; i < array1.length; i++)
{
array1[i] = genrator.nextInt(21 - 1);
}
for(int i = 0; i < array1.length; i++)
{
System.out.print(array1[i] + " ");
}
System.out.println("\n");
for (int i = 0; i < array1.length; i++)
{
if (array1[i] < array1[i] + 1)
{
System.out.println(array1[i] + " ");
}
}
}
}

In pseudo-code:
V value=first value
P position=1
L length=0
Scan the values from position Q=2
Compare current value C to V
If C is less than V
if this sequence Q-P is longer than L
save length as L
save P as location R
update V and P to current value
If C is greater than V
update V and P to current value
I don't have a compiler for pseudo-code so it might not be exactly right, but it should be a start.

Related

Solving a matrix equation in Java

I have been trying to implement the given formula in JAVA but i was unsuccessful. Can someone help me find what I am doing wrong?
Do i need to shift the summation index and if so how?
My code:
public final class LinearSystem {
private LinearSystem() {
}
public static int[] solve(int [][]A , int []y) {
int n = A.length;
int[] x = new int[n];
for (int i = 0 ; i < n; i++) {
x[i] = 0;
int sum = 0;
for(int k = i + 1 ; k == n; k++) {
sum += A[i][k]*x[k]; // **java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3**
}
x[i] = 1/A[i][i] * (y[i] - sum);
}
return x;
}
public static void main(String[] args) {
int[][]A = new int[][]{{2,-1,-3},{0,4,-1},{0,0,3}};
int [] y = new int[] {4,-1,23};
System.out.println(Arrays.toString(solve(A,y))); **// awaited result [2, -3, 1]**
}
}
Just trying to collect all my comments under the question into one coherent answer, since there are quite a few different mistakes in your program.
This method of solving linear equations relies on your calculating the components of the answer in reverse order - that is, from bottom to top. That's because each x[i] value depends on the values below it in the vector, but not on the values above it. So your outer loop, where you iterate over the x values needs to start at the biggest index, and work down to the smallest. In other words, instead of being for (int i = 0; i < n; i++), it needs to be for (int i = n - 1; i >= 0; i++).
The inner loop has the wrong stopping condition. With a for loop, the part between the two semicolons is the condition to continue iterating, not the condition to stop. So instead of for(int k = i + 1; k == n; k++), you need for(int k = i + 1; k < n; k++).
You're doing an integer division at the beginning of 1 / A[i][i] * (y[i] - sum);, which means the value is rounded to an integer before carrying on. When you divide 1 by another integer, you always get -1, 0 or 1 because of the rounding, and that makes your answer incorrect. The fix from point 4 below will deal with this.
The formula relies on the mathematical accuracy that comes with working with either floating point types or decimal types. Integers aren't going to be accurate. So you need to change the declarations of some of your variables, as follows.
public static double[] solve(double[][] A, double[] y)
double x[] = new double[n];
double sum = 0.0;
along with the corresponding changes in the main method.
First, you need the second loop to go until k < n, otherwise this throws the ArrayOutOfBounds Exceptions.
Second, you need to calculate your x in reverse order as #Dawood ibn Kareem said.
Also, you probably want x[] to be a double-array to not only get 0-values as result.
I am sorry I don't know much about math side so I couldn't fix it to the right solution but I noticed a few things wrong about your code.
1-You shouldn't initialize your arrays as integer arrays, because you will be doing integer division all over the place. For example 1/A[i][i] will result in 0 even if A[i][i] = 2
2-You shouldn't write k == n, if you do it like this then your for loop will only execute if k equals n, which is impossible for your case.
I think you want to do k < n, which loops from i+1 to the point where k = n - 1
Here is my code:
import java.util.Arrays;
public final class LinearSystem {
private LinearSystem() {
}
public static double[] solve(double [][]A , double []y) {
int n = A.length;
double[] x = new double[n];
for (int i = 0 ; i < n; i++) {
x[i] = 0;
int sum = 0;
for(int k = i + 1 ; k < n; k++) {
sum += A[i][k] * x[k]; // **java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3**
}
x[i] = 1/A[i][i] * (y[i] - sum);
}
return x;
}
public static void main(String[] args) {
double[][]A = new double[][]{{2,-1,-3},{0,4,-1},{0,0,3}};
double [] y = new double[] {4,-1,23};
System.out.println(Arrays.toString(solve(A,y))); // awaited result [2, -3, 1]**
}
}
Remember that arrays are indexed from 0, so the last element is at index n - 1, not n.

how to display the closest pair product in array

import java.util.Scanner;
class my
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int t;
int a[] = new int[5];
int l = a.length;
int prod[] = new int[100];
int index[] = new int[100];
int n;
System.out.println("enter a elements into array ");
for(int i = 0;i<5;i++)
{
a[i] = sc.nextInt();
}
for(int i = 0 ;i<4;i++)
{
for(int j = 0;j<(4-i);j++)
{
if(a[j]>a[j+1])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
System.out.println("enter a number");
n = sc.nextInt();
for(int i = 0;i<l-1;i++)
{
prod[i] = a[i]*a[i+1];
index[i] = a[i];
index[i+1]=a[i+1];
}
for(int i = 0;i<l;i++)
{
if(prod[i]!=0)
System.out.println(prod[i]);
}
for(int i = 0;i<l-1;i++)
{
if(n>prod[i]&&n<=prod[i+1])
System.out.println(index[i+1]+"\t"+index[i+2]);
}
}
}
if want to display the closest pair product in array, which nearest to the entered number. but when i entered array element 1, 2 ,3, 5, 4
and after enter the array i am entering number 8 it is display 3, 4 pair from array instead of 5,2. answer would be 5,2 because the product of 5 * 2 is 10 which is closest to entered number is 8.
The problem with the code is that it is just calculating the product of two consecutive elements and than your are simply comparing that with the product of other elements, which is not a correct way.
Since you sort the array a better way to do it is, by using the logic of binary search. And the logic that the product of pair closest to x will have the least difference.
The algorithm which you can use is as followed:
1. Make a variable difference and initialize to Integer.MAX_VALUE;
2. Now traverse the array from both the direction, i.e set index of left = 0, and right = arr.length -1.
3. Loop while left < right.
(a) If abs((arr[left] * arr[right]) - x) < difference
then update difference and result
(b) if((arr[left] * arr[right]) < x) then
left++
(c) Else right--
Time Complexity : O(nlog(n))
I don't understand why you have so many loops and so many variables in your solution. You also don't need to sort the array a.
In pseudo code:
var a[]
var n
var closest = MAX_INTEGER
var closest_i
var closest_j
for i in range [0, a.length)
for j in range [i + 1, a.length)
var distance = abs(a[i] * a[j] - n)
if distance < closest
closest = distance
closest_i = i
closest_j = j
Note that this has O(n) time complexity.

Trying to determine smallest amount and position in a Java array

I am new to the site, and new to programming in general, so please be gentle. I'm doing an assignment and I've built everything it needs, but I'm having problems with one particular part.
So the code below is just the for loop part of the overall program that I'm having trouble with. I created an array to store the user's quarterly input. When I go to determine which quarter had the largest rainfall, the code works no problem.
Where I'm having problems however is when I try to determine the quarter with the least amount. I basically set them both up the same way, but it doesn't work. I'm sure I must have a logic problem somewhere in there, but I've racked my brain trying to figure it out. Any help would be greatly appreciated. I'm sure its something small and stupid that I'm doing.
double largest=0;
for (int k = 0; k < quarterlyArray.length; k++) { // Determines the largest quarterly rainfall.
if ( quarterlyArray[k] >= largest ) {
largest = quarterlyArray[k];
}
}
for (int k = 0; k < quarterlyArray.length; k++) { // Determines in which quarter had largest rainfall.
if (quarterlyArray[k] == largest) {
System.out.println("Quarter " + (k+1) + " saw the most rain this year with " + largest + " inches.");
}
}
double smallest = 0;
for (int p = (quarterlyArray.length-1); p == 0; p--) { // This is not working right now.
if (quarterlyArray[p] < quarterlyArray [quarterlyArray.length-1] || quarterlyArray[p] < smallest) {
quarterlyArray[p] = smallest;
}
}
for (int l = quarterlyArray.length; l == 0; l--) { // Nor this.
if (quarterlyArray[l] == smallest) {
System.out.println("Quarter " + (l+1) + " saw the least rain this year with " + smallest + " inches.");
}
}
A few things that I notice, that are contributing to your problem:
for (int p = (quarterlyArray.length-1); p == 0; p--) {
The p == 0 is the termination expression. Your loop will only iterate while this condition is true. Your loop will not execute because the condition is false on the first iteration.
for (int l = quarterlyArray.length; l == 0; l--) {
Same problem in this loop, too. Look at your condition in your first for loop - k < quarterlyArray.length. When this is false, your loop will terminate.
quarterlyArray[p] = smallest
You are modifying the array rather than your local variable smallest.
You also need to be careful about bounds of the arrays. Your loop sets l to the array length - int l = quarterlyArray.length. If you then try to index into this array using quarterlyArray[l] you would get an ArrayIndexOutOfBoundsException because Java arrays (and most programming languages I would say) are 0-based.
Another thing to point out is how you are calculating both the min and max. Say, for example, that your quarterlyArray contains all negative values. What would largest be? Well, none of the items in the array are greater than 0, so largest would be 0. That would be incorrect because that value is not in the array.
In your first case, it looks like you are starting with an element that you know will always be lower than the elements in the array. This works out fine if you know all the elements will be greater than that. Your double largest = 0 will be changed to the maximum value of the array based on the constraints of the problem you are solving.
A better way to approach this is to start with a known element from the array. If you simply change your largest to be the first/last element from the array, and then go through the rest, you will always come out with the desired result.
double largest = quarterlyArray[0];
for (int k = 1; k < quarterlyArray.length; k++) { // Determines the largest quarterly rainfall.
if ( quarterlyArray[k] >= largest ) {
largest = quarterlyArray[k];
}
}
Notice how all I changed was the initialization of largest, and int k = 1. You can do the same thing for smallest. In this case, I start from the end of the array.
double smallest = quarterlyArray[quarterlyArray.length - 1];
for (int p = quarterlyArray.length - 2; p >= 0; p--) {right now.
if (quarterlyArray[p] < smallest) {
smallest = quarterlyArray[p];
}
}
Another note for after you get through this, is how could do both in 1 for loop?
Start the last loop form quarterlyArray.length-1.Change to
for (int l = quarterlyArray.length-1; l >= 0; l--)
The last element of the array would be at quarterlyArray.length-1 not at quarterlyArray.length
And l == 0(termination expression) should be l >= 0 because when the termination expression evaluates to false, the loop terminates.
Your loop for the smallest is all wrong - you are setting the array values, not finding the smallest.
Do it all in one loop:
double largest=Double.MIN_VALUE;
double smallest = Double.MAX_VALUE;
for (int k = 0; k < quarterlyArray.length; k++) {
if ( quarterlyArray[k] > largest ) {
largest = quarterlyArray[k];
}
if ( quarterlyArray[k] < smallest ) {
smallest = quarterlyArray[k];
}
}
You can also refine this in the manner shown by #mkobit to make it a bit faster:
double largest=quarterlyArray[0];
double smallest = largets;
for (int k = 1; k < quarterlyArray.length; k++) {
if ( quarterlyArray[k] > largest ) {
largest = quarterlyArray[k];
} else if ( quarterlyArray[k] < smallest ) {
smallest = quarterlyArray[k];
}
}
Of course, you should first check to ensure that quarterlyArray has a length greater than zero.

searching a 2D int[][] array?

How do I search a 2D array for a specific number (1)? I thought the following code did it, but apparently I was looking in a specific spot whenI declared it with [4][4].
boolean undirectedCircuit (int [][] graph)
{
//graph = graph1(graph1(null));
int edgeCounter = 0;
for (int edge = 0; edge < graph.length; edge++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if(graph[4][4] == '1')
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
if (edgeCounter % 2 == 0)
{
System.out.println("This is a circuit!");
//return true;
}
else System.out.println("This is not a circuit!!");
return false;
}
public void go ()
{
graph1 = new int[][] //This line is complained about.
{
{0,1,1,1,0},
{1,0,0,0,1},
{1,0,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}
};
undirectedCircuit(graph1); //This is complained about.
}
This is part of an assignment from my school, just pointers would be great. Thank you!
This line is wrong in two ways:
if(graph[4][4] == '1')
The quotes around '1' make it a char literal. Since your array contains ints, you'll want to drop the quotes and just write 1.
graph[4][4] will always check the same value in the array as you said. Specifically, it will always access the fifth value in the fifth array of your 2d array. Whenever you write numbers in your code, they are constants: the number 4 is never going to change during your program's execution, so you keep using 4 as the index over and over again, accessing the fifth element each time you do so.
In order to access every element in an array, you can loop over it like this:
for (int n = 0; n < array.length; n ++)
{
array[n]; //access the nth element of the array
}
n in this instance is the same as your edge variable.
However, since you are using a 2d array, these elements are themselves arrays! Therefore, you need another loop:
//array is a 2d array...
for (int n = 0; n < array.length; n ++)
{
//...so its elements are 1d arrays
for (int m = 0; m < array[n].length; m ++)
{
array[m][n]; //here we have a specific object in our 2d array.
}
}
We use variables for our indices so they can change in the loop and access different values in the array. Hope this helps!
You could try something like this where you will iterate through both dimensions of the array and check your current location rather than the 4,4
for (int x = 0; x < graph.length; x++)
{
for (int y = 0; y < graph[x].length; y++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if (graph[x][y] == 1)
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
}

Transferring the contents of a one-dimensional array to a two-dimensional array

I'm trying to make an encryption program where the user enters a message and then converts the "letters into numbers".
For example the user enters a ABCD as his message. The converted number would be 1 2 3 4 and the numbers are stored into a one dimensional integer array. What I want to do is be able to put it into a 2x2 matrix with the use of two dimensional arrays.
Here's a snippet of my code:
int data[] = new int[] {10,20,30,40};
*for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for (int ctr=0; ictr<data.length(); ictr++){
a[i][j] = data[ctr];}
}
}
I know there's something wrong with the code but I am really lost.
How do I output it as the following?
10 20
30 40
(instead of just 10,20,30,40)
Here's one way of doing it. It's not the only way. Basically, for each cell in the output, you calculate the corresponding index of the initial array, then do the assignment.
int data[] = new int[] {10, 20, 30, 40, 50, 60};
int width = 3;
int height = 2;
int[][] result = new int[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
result[i][j] = data[i * width + j];
}
}
Seems like you want to output a 2xn matrix while still having the values stored in a one-dimensional array. If that's the case then you can to this:
Assume the cardinality m of your set of values is known. Then, since you want it to be 2 rows, you calculate n=ceil(m/2), which will be the column count for your 2xn matrix. Note that if m is odd then you will only have n-1 values in your second row.
Then, for your array data (one-dimension array) which stores the values, just do
for(i=0;i<2;i++) // For each row
{
for(j=0;j<n;j++) // For each column,
// where index is baseline+j in the original one-dim array
{
System.out.print(data[i*n+j]);
}
}
But make sure you check the very last value for an odd cardinality set. Also you may want to do Integer.toString() to print the values.
Your code is close but not quite right. Specifically, your innermost loop (the one with ctr) doesn't accomplish much: it really just repeatedly sets the current a[i][j] to every value in the 1-D array, ultimately ending up with the last value in the array in every cell. Your main problem is confusion around how to work ctr into those loops.
There are two general approaches for what you are trying to do here. The general assumption I am making is that you want to pack an array of length L into an M x N 2-D array, where M x N = L exactly.
The first approach is to iterate through the 2D array, pulling the appropriate value from the 1-D array. For example (I'm using M and N for sizes below):
for (int i = 0, ctr = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j, ++ ctr) {
a[i][j] = data[ctr];
}
} // The final value of ctr would be L, since L = M * N.
Here, we use i and j as the 2-D indices, and start ctr at 0 and just increment it as we go to step through the 1-D array. This approach has another variation, which is to calculate the source index explicitly rather than using an increment, for example:
for (int i = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j) {
int ctr = i * N + j;
a[i][j] = data[ctr];
}
}
The second approach is to instead iterate through the 1-D array, and calculate the destination position in the 2-D array. Modulo and integer division can help with that:
for (int ctr = 0; ctr < L; ++ ctr) {
int i = ctr / N;
int j = ctr % N;
a[i][j] = data[ctr];
}
All of these approaches work. Some may be more convenient than others depending on your situation. Note that the two explicitly calculated approaches can be more convenient if you have to do other transformations at the same time, e.g. the last approach above would make it very easy to, say, flip your 2-D matrix horizontally.
check this solution, it works for any length of data
public class ArrayTest
{
public static void main(String[] args)
{
int data[] = new int[] {10,20,30,40,50};
int length,limit1,limit2;
length=data.length;
if(length%2==0)
{
limit1=data.length/2;
limit2=2;
}
else
{
limit1=data.length/2+1;
limit2=2;
}
int data2[][] = new int[limit1][limit2];
int ctr=0;
//stores data in 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
data2[i][j] = data[ctr];
ctr++;
}
else
{
break;
}
}
}
ctr=0;
//prints data from 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
System.out.println(data2[i][j]);
ctr++;
}
else
{
break;
}
}
}
}
}

Categories

Resources