This question already has answers here:
How to determine the longest increasing subsequence using dynamic programming?
(20 answers)
Closed 5 years ago.
I've been working on this problem for awhile and couldn't come up with the solution; I hope you can help out..
I'm trying to find the longest increasing sequence of numbers. For example, if I have the following 4X4 array:
[![enter image description here][1]][1]
int [] nums = {
{97 , 47 , 56 , 36},
{35 , 57 , 41 , 13},
{89 , 36 , 98 , 75},
{25 , 45 , 26 , 17}
};
THE EXPECTED RESULT : return 8 and the LIS 17, 26, 36, 41, 47, 56, 57, 97
I don't have the answer to it yet, I'm trying to reach it.
17 (3,3)
26 (3,2)
36 (2,1)
41 (1,2)
47 (0,1)
56 (0,2)
57 (1,1)
97 (0,0)
I hope my example is clear enough..
This is my code; when I try to find the longest increasing path, it doesn't do it backward not diagonally. Can anyone help me please?
public class Solution2 {
static int[] dx = { 1, -1, 0, 0 };
static int[] dy = { 0, 0, 1, -1 };
public static int longestIncreasingPath(int[][] matrix) {
if (matrix.length == 0)
return 0;
int m = matrix.length, n = matrix[0].length;
int[][] dis = new int[m][n];
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
ans = Math.max(ans, dfs(i, j, m, n, matrix, dis));
}
}
return ans;
}
static int dfs(int x, int y, int m, int n, int[][] matrix, int[][] dis) {
if (dis[x][y] != 0)
return dis[x][y];
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < m && ny < n && matrix[nx][ny] > matrix[x][y]) {
dis[x][y] = Math.max(dis[x][y], dfs(nx, ny, m, n, matrix, dis));
}
}
return ++dis[x][y];
}
public static void main(String[] args) {
int arr[][] = {
{ 97, 47, 56, 36 },
{ 35, 57, 41, 13 },
{ 89, 36, 98, 75 },
{ 25, 45, 26, 17 }
};
System.out.println(longestIncreasingPath(arr));
}
}
I assume we are looking for a strictly increasing sequence (this is not clear from the original problem description).
This problem can then be solved by a dynamic programming approach:
1) sort the cells by their value into decreasing order.
2) in decreasing order assign the length of the longest path starting at this cell:
2a) if you cannot reach any of the previously visited cells assign 1
2b) otherwise assign 1 + max(reachable previous cell)
When this is finished, the overall maximum is the length of the longest path. The path itself can also be found by remembering the max cell in step 2b).
In the example this gives:
0,3 2,1
cell 98 97 89 75 57 56 47 45 41 36 36 35 26 25 17 13
length 1 1 1 2 2 3 4 2 5 6 6 7 7 7 8 7
As far as I understand, you try to implement a depth-first search to find the longest path of increasing order. If so, first of all it is better to mark numbers you visited somehow. A convenient solution is an array. As far as the numbers are marked, you can use it to check whether the particular number has already been counted in an increasing sequence. This is as a little hint for you.
If you are still confused about a depth-first search, I would recommend to read the Depth-First Search Wikipedia page to get a better understanding of what the algorithm is all about.
HTH, Evgeniy
Related
In an infinite sequence of numbers [2, 5, 7, 22, 25, 27, 52, 55, 57, 72, 75, 77, 222, ...].
Given any number in this sequence get the immediate successor number.
Example:
Input Output
22 25
77 222
5 7
I have written the below logic to find the next number in a sequence.
public static int getNextNumInSequence(Integer sequenceCurrentNum) {
List<Integer> sequence = new ArrayList<>();
sequence.add(2);
sequence.add(5);
sequence.add(7);
if(sequence.get(0).equals(sequenceCurrentNum))
return sequence.get(1);
else if(sequence.get(1).equals(sequenceCurrentNum))
return sequence.get(2);
//This is not a finite loop, just for my testing i am running 300 iterations.
for(int i=0;i<300;i++) {
if(sequence.get(i).equals(sequenceCurrentNum)) {
return sequence.get(i+1);
}
int nextVal = sequence.get(i)*10;
Integer firstSeq = nextVal + sequence.get(0);
Integer secondSeq = nextVal + sequence.get(1);
Integer thirdSeq = nextVal + sequence.get(2);
sequence.add(firstSeq);
sequence.add(secondSeq);
sequence.add(thirdSeq);
if(firstSeq.equals(sequenceCurrentNum)) {
return secondSeq;
}else if(secondSeq.equals(sequenceCurrentNum)) {
return thirdSeq;
}
}
return 0;
}
My Approach:
I am constructing the entire sequence from the beginning
Then checking if we have reached to the given number in sequence.
Then return the successor.
Drawbacks:
I am constructing the entire sequence to reach to given number.
Memory wise and performance wise not suggestable.
Please help to understand, is there any better approach to get the successor without constructing entire sequence.
Example: Given 277755 should return 277757. (Without constructing the
entire sequnce)
Note: The sequence will not be provided as an input to our function. The only input we will be given is a valid number from the sequence.
Try this.
public static int getNextNumInSequence(Integer sequenceCurrentNum) {
int head = sequenceCurrentNum / 10;
int tail = sequenceCurrentNum % 10;
int headNext = head == 0 ? 2 : getNextNumInSequence(head);
if (headNext == 0) return 0;
switch (tail) {
case 2: return head * 10 + 5;
case 5: return head * 10 + 7;
case 7: return headNext * 10 + 2;
default: return 0;
}
}
public static void main(String[] args) {
for (int i = 0, k = 2; i < 20; ++i, k = getNextNumInSequence(k))
System.out.println(i + " : " + k);
}
output:
0 : 2
1 : 5
2 : 7
3 : 22
4 : 25
5 : 27
6 : 52
7 : 55
8 : 57
9 : 72
10 : 75
11 : 77
12 : 222
13 : 225
14 : 227
15 : 252
16 : 255
17 : 257
18 : 272
19 : 275
You can also get n-th number.
public static int getNumAtIndex(int n) {
int h = n / 3;
int t = n % 3;
return (h == 0 ? 0 : getNumAtIndex(h) * 10)
+ (t == 0 ? 2 : t == 1 ? 5 : 7);
}
test:
public static void main(String[] args) {
for (int i = 0; i < 10; ++i)
System.out.println(i + " : " + getNumAtIndex(i));
}
output:
0 : 2
1 : 5
2 : 7
3 : 52
4 : 55
5 : 57
6 : 72
7 : 75
8 : 77
9 : 522
First try to understand what is the logic behind the sequence. If you look carefully to the numbers, you may see counting in ternary base. To be more clear, let's replace '2' by '0', '5' by '1' and '7' by '2'. Then your sequence becomes:
(0, 1, 2, 10, 11, 12, 20, 21, 22, 100, 101, 102, ...)
It's just counting.
So the thing is to get the next number in ternary base, but using the digits 2, 5, 7. We must take care of digit 7: if we increment it, we get 2 but we have a carry for the digit before.
Here is a sample code:
public static Integer getNextNumInSequence(Integer number)
{
int digits[] = {2,5,7};
int idx_digits[] = {-1, -1, 0, -1, -1, 1, -1, 2, -1, -1};
Integer next_number = 0;
int carry = 1;
Integer pow10 = 1;
while (number>0)
{
int digit = number%10; //extract last digit
int idx_d = idx_digits[digit]; //get index of digit -- must be 0,1 or 2
if (idx_d==-1)
{
System.out.println("Invalid number");
return -1;
}
next_number += digits[(idx_d+carry)%3]*pow10; //compute next digit in sequence, taking care of the carry
carry = (digit==7)?1:0; //carry is 1 only if the current digit is 7
pow10 *= 10; //increment
number /= 10; //erase last digit
if (carry==0) //if no carry, we can stop the loop here, it's not useful to continue
{
break;
}
}
// at this point, either number>0 or carry==1
return ((carry>0)?2:number)*pow10+next_number; //final number is the digit sequence [2 if carry else number ; next_number]
}
You can solve this recursively.
If the final digit of the given number is 2 or 5, then it is easy: just change that final digit to 5 or 7 respectively.
Otherwise (when the final digit is 7), solve the problem without the last digit, and then append the digit 2 to that result. Of course, "without last digit" means an integer division by 10, and "appending" means multiplying by 10 and then adding the value of the digit.
Here is the function:
public static int getNextNumInSequence(Integer curr) {
if (curr % 10 == 2) return curr + 3;
if (curr % 10 == 5) return curr + 2;
if (curr == 7) return 22;
return getNextNumInSequence(curr / 10) * 10 + 2;
}
Note that one call has worst case time complexity of O(logn) where n is the value of the function argument, but amortised time complexity is O(1) per call.
To construct the list, you can simply do this:
List<Integer> list = Arrays.asList(2, 5, 7, 22, 25, 27, 52, 55, 57, 72, 75, 77, 222);
Note that there are cases where there is not successor. Here I will return null in those cases:
public static Integer getNextNumInSequence(List<Integer> list, Integer num) {
int pos = list.indexOf(num);
if (pos >= 0 && pos+1 < list.size()) {
return list.get(pos+1);
}
return null;
}
Note that I've added a parameter list so that you don't have to build the list each time you want to do a search.
In your example, the list is sorted; If it's always the case, you can use a binary search: Collections.binarySearch(list, num) instead of list.indexOf(num).
OK. If I understand correctly, you have three initial values:
static final int[] initial = {2, 5, 7};
and you can calculate the value at position ix like this:
private static int calculate(int ix) {
int div = ix/initial.length;
int rest = ix%initial.length;
int value = 0;
if (div > 0) {
value = 10*calculate(div-1);
}
return value+initial[rest];
}
To get the successor of num:
public static Integer getNextNumInSequence(int num) {
for (int i = 0; ; ++i) {
int cur = calculate(i);
if (cur == num) {
return calculate(i+1);
} else if (cur > num) {
return null;
}
}
}
Basically I need to find the smallest amount of moves it would take for a knight to reach a certain position on a 8x8 grid numbered 0-63 inclusive.
I have cross checked all test cases that I could think of and every test case is exactly what I am looking for. I used an elimination and placement algorithm modeled after an O(1) solution but for a knight instead.
The test cases I receive for the problem are confidential and I am left to guess what I have missed. When I try to verify my code I receive an output of:
Test 1 passed!
Test 2 failed.
Test 3 passed!
Test 4 failed.
Test 5 failed.
Test 6 failed.
Test 7 failed.
Test 8 failed.
Test 9 failed.
Test 10 failed.
Code:
public class Test {
public static boolean found = false;
public static void main (String[] args) {
int[][] arr = { // 0 1 2 3 4 5 6 7
{ 0, 1, 2, 3, 4, 5, 6, 7}, // 0
{ 8, 9, 10, 11, 12, 13, 14, 15}, // 1
{16, 17, 18, 19, 20, 21, 22, 23}, // 2
{24, 25, 26, 27, 28, 29, 30, 31}, // 3
{32, 33, 34, 35, 36, 37, 38, 39}, // 4
{40, 41, 42, 43, 44, 45, 46, 47}, // 5
{48, 49, 50, 51, 52, 53, 54, 55}, // 6
{56, 57, 58, 59, 60, 61, 62, 63}, // 7
};
int src = 63; // Changed to parameters values later on in testing
int dest = 30; // Changed to parameters values later on in testing
int[] loc = pos(arr, src);
int[][] productMatrix;
int finalNumber = 0;
while(!found && arr[loc[0]][loc[1]] != dest)
{
productMatrix = createknights(arr, loc[0], loc[1], dest);
printMatrix(productMatrix);
System.out.println("--------------------");
finalNumber++;
}
System.out.println(finalNumber);
}
public static int[][] createknights(int[][] arr, int r, int c, int goal)
{
arr[r][c] = -1;
int[][] knightLoc = getKnightLoc(arr);
for(int i = 0; i < knightLoc.length; i++)
{
int[][] possiblePositions = {
{knightLoc[i][0] - 2, knightLoc[i][1] - 1}, //Up Left
{knightLoc[i][0] - 2, knightLoc[i][1] + 1}, //Up Right
{knightLoc[i][0] + 2, knightLoc[i][1] - 1}, //Down Left
{knightLoc[i][0] + 2, knightLoc[i][1] + 1}, //Down Right
{knightLoc[i][0] - 1, knightLoc[i][1] - 2}, //Left Up
{knightLoc[i][0] + 1, knightLoc[i][1] - 2}, //Left Down
{knightLoc[i][0] - 1, knightLoc[i][1] + 2}, //Right Up
{knightLoc[i][0] + 1, knightLoc[i][1] + 2} //Right Down
};
for( int[] row : possiblePositions)
{
if( checkLoc(arr, row[0], row[1]) )
{
if( arr[row[0]][row[1]] == goal )
{
found = true;
break;
}
arr[row[0]][row[1]] = -1;
}
}
}
return arr;
}
public static int[][] getKnightLoc(int[][] arr)
{
int knightNum = getKnightNum(arr);
int[][] knightLocArray = new int[knightNum][2];
for(int i = 0; i < arr.length; i ++)
{
for(int a = 0; a < arr[i].length; a++)
{
if(arr[i][a] == -1)
{
knightLocArray[(knightNum - 1)] = new int[]{i,a};
knightNum--;
}
}
}
return knightLocArray;
}
public static int getKnightNum(int[][] arr)
{
int knightNum = 0;
for(int i = 0; i < arr.length; i ++)
{
for(int a = 0; a < arr[i].length; a++)
{
if(arr[i][a] == -1)
{
knightNum++;
}
}
}
return knightNum;
}
public static boolean checkLoc(int[][] arr, int r, int c)
{
if(r >= 0 && c >= 0 && r < arr.length && c < arr[r].length && arr[r][c] != -1)
{
return true;
}
return false;
}
public static int[] pos(int[][] arr, int src)
{
for(int i = 0; i < arr.length; i ++)
{
for(int a = 0; a < arr[i].length; a++)
{
if(arr[i][a] == src)
{
return new int[]{i , a};
}
}
}
return null;
}
public static void printMatrix(int[][] arr)
{
for(int i = 0; i < arr.length; i ++)
{
for(int a = 0; a < arr[i].length; a++)
{
System.out.print(arr[i][a] + " ");
}
System.out.println();
}
}
}
The O(1) model I checked my answers with:
O(1) model
Output example (ending value is the answer: src=63, dest=30):
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 -1 47
48 49 50 51 52 -1 54 55
56 57 58 59 60 61 62 -1
--------------------
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 -1 30 -1
32 33 34 35 -1 37 -1 39
40 41 42 -1 44 45 -1 -1
48 49 50 51 -1 -1 54 55
56 57 58 -1 60 -1 62 -1
--------------------
0 1 2 3 4 5 6 7
8 9 10 11 -1 13 -1 15
16 17 18 -1 20 -1 22 -1
24 25 -1 27 -1 -1 30 -1
32 -1 34 -1 -1 -1 -1 -1
40 41 -1 -1 -1 45 -1 -1
48 -1 50 -1 -1 -1 54 -1
56 57 -1 -1 -1 -1 -1 -1
--------------------
3 <----Answer
Please tell me what I am missing. Thanks!
Edit:
int src & int dest will not be hard coded at run time. The values will be replaced with parameter values. The values are hard coded for testing purposes.
I’m afraid your program prints 3 every time. This is because you have hardcoded the source as square 63 and the destination as square 30. Coincidentally the answers to two of the test cases are indeed 3. This is a reasonable guess. So you pass those two and fail the rest.
Instead you should of course read the input in whatever way is specified with your assignment.
It turns out that this block of code is a perfect solution except for the fact that apparently the test cases are tested in one continuous section of code.
For example, making a separate method allowed for me to call this section of code:
public static void main (String[] args) {
//Test Cases
System.out.println(answer(63,5));
System.out.println(answer(19,4));
System.out.println(answer(63,0));
}
This would print out:
5
0
0
After further debugging, I found what had caused the leading zeros is disregarding the found variable at the top of the code. Thus, leading to completely incorrect answers.
Previous Code:
while(!found && arr[loc[0]][loc[1]] != dest)
{
productMatrix = createknights(arr, loc[0], loc[1], dest);
printMatrix(productMatrix);
System.out.println("--------------------");
finalNumber++;
}
System.out.println(finalNumber);
New Code:
while(!found && arr[loc[0]][loc[1]] != dest)
{
productMatrix = createknights(arr, loc[0], loc[1], dest);
printMatrix(productMatrix);
System.out.println("--------------------");
finalNumber++;
}
found = false;
System.out.println(finalNumber);
Thus now relaying the correct answers.
Thank you Ole V.V. for brainstorming a solution! I guess just needed some time away from the problem and a couple of ideas.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i'm newbie in java. i have problem search many min in java.
i have a big data. but example data like this.
k[][] = [74 85 123
73 84 122
72 83 121
70 81 119
69 80 118
76 87 125
77 88 126
78 89 127];
and i want output like this.
min1 = 69 min1 = 80 min1 = 118
min2 = 70 min2 = 81 min2 = 119
min3 = 72 min3 = 83 min3 = 121
i use sorting in this data but the results it's not eficient.
someone help me
thx
Here is a general implementation using a helper class for finding the lowest X integers.
With three columns, three instances of the helper class is created, and the data is then iterated to collect the 3 lowest values for each column.
The advantages of this code are:
Only retains the lowest X values
Does not need to box the integers
Uses binary search for improved performance of higher values of X
This means it should be fast and have a low memory footprint, supporting unlimited amounts of data (if streamed).
See IDEONE for demo.
import java.util.Arrays;
class Ideone {
private static final int MIN_COUNT = 3;
public static void main(String[] args) {
int[][] data = { { 74, 85, 123 },
{ 73, 84, 122 },
{ 72, 83, 121 },
{ 70, 81, 119 },
{ 69, 80, 118 },
{ 76, 87, 125 },
{ 77, 88, 126 },
{ 78, 89, 127 } };
// Initialize min collectors
Min[] min = new Min[data[0].length];
for (int col = 0; col < min.length; col++)
min[col] = new Min(MIN_COUNT);
// Collect data
for (int row = 0; row < data.length; row++)
for (int col = 0; col < min.length; col++)
min[col].add(data[row][col]);
// Print result
for (int i = 0; i < MIN_COUNT; i++) {
for (int col = 0; col < min.length; col++)
System.out.printf("min%d = %-5d ", i + 1, min[col].get(i));
System.out.println();
}
}
}
class Min {
private int[] min;
public Min(int count) {
this.min = new int[count];
Arrays.fill(this.min, Integer.MAX_VALUE);
}
public void add(int value) {
int idx = Arrays.binarySearch(this.min, value);
if (idx != -this.min.length - 1) { // not insert at end
if (idx < 0)
idx = -idx - 1;
System.arraycopy(this.min, idx, this.min, idx + 1, this.min.length - idx - 1);
this.min[idx] = value;
}
}
public int get(int index) {
return this.min[index];
}
}
Say your data has N rows and M columns
Iterate over each column
Add all the elements in the column into a minHeap ( min priority queue)
Retrieve the first 3 numbers from the minHeap (these will be the 3 mins)
Clear the queue and move onto the next column
O(n) space, O(MNlg(N)) time
I need to create an application that generates 25 random integers between 0 and 99 and then outputs those integers on two separate lines one for odd numbers and one for even numbers. I will need to use one array for even numbers and one for odd numbers. This is what I have so far:
public static void main(String[] args) {
//Odd Numbers
int[] oddNums = new int[25];
for (int index = 0; index < oddNums.length; index++) {
oddNums[index] = (int) (Math.random()*99);
}
System.out.print("ODD: ");
for (int index = 0; index < oddNums.length; index++) {
System.out.print(oddNums[index] + " ");
}
//Even Numbers
int[] evenNums = new int[25];
for (int index = 0; index < evenNums.length; index++) {
evenNums[index] = (int) (Math.random()*99);
}
System.out.print("\nEVEN: ");
for (int index = 0; index < evenNums.length; index++) {
System.out.print(evenNums[index] + " ");
}
}
I have set up the program to print out 25 random integers, but I do not know how I am going to get the program to print out only even numbers on one line and odd numbers on another (I am new to java).
Here is a sample output I am getting:
ODD: 28 36 54 98 35 1 59 43 96 69 41 66 37 15 30 17 29 67 56 83 71 4
24 70 38
EVEN: 34 45 36 26 73 84 60 39 21 49 28 98 69 14 32 24 72 29 26 88 77 2
23 58 47
This is wrong since there are both even and odd numbers on both lines.
This is what the output should look like:
ODD: 25 97 23 45 63 91 13 47 93 51 29
EVEN: 22 94 46 74 18 48 32 84 28 92 56
There are only odd numbers on one line and even numbers on another line.
Does anyone know what I need to add here?
A little modification to your program will yield the desired result.
public static void main(String[] args) {
//Odd Numbers
int[] randomNumbers = new int[25];
int[] evenNumbers = new int[25];
int[] oddNumbers = new int[25];
int k = 0, l = 0;
for (int index = 0; index < randomNumbers.length; index++) {
randomNumbers[index] = (int) (Math.random() * 99);
}
for (int i = 0; i < 25; i++) {
if (randomNumbers[i] % 2 == 0) {
evenNumbers[k] = randomNumbers[i];
k++;
} else {
oddNumbers[l] = randomNumbers[i];
l++;
}
}
}
You can generate an even number uniformly at random in [0,100] with the formula n = 2*x where x is uniformly random in [0, 49].
You can similarly generate an uniformly random odd number with n = 2*x+1 where x is uniformly random in [0,49].
You can just generate the 25 number. After generating those ints, you can locate them in the array they belong.
int num;
int oddIndex = -1;
int evenIndex = -1;
for (index = 0; index < 25 ; index++){
num = (int) (Math.random()*99);
if (num % 2 == 1){
oddIndex++;
oddNum[oddIndex] = num;
}
else{
evenIndex++;
evenNum[evenIndex] = num;
}
}
In this case, you're not sure about the sizes of each array. So, I advise you to use ArrayList instead of array. If you use an ArrayList, you won't need to deal with oddIndex and evenIndex.
Firstly,The random function you have written will be generating random numbers between 0 and 99. It will not be considering whether the numbers are odd or even.
If there is no restriction on the number of odd numbers and number of even numbers, just use the random generator once and depending on whether it is odd or even place it in the correct array.
For doing so, use the MOD operator i.e. check for remainder after dividing by 2 to see odd or even
At some point in your code, you need to have something like,
Pseudocode:
if (nextNumber is odd) then
put nextNumber at end of ODD array
else
put nextNumber at end of EVEN array
endif
You should also have a look at util.Random.nextInt() which is preferable for generating random integers.
Here's a solution that uses Java 8 streams:
public class NumberGenerator {
public static void main(String[] args) {
Random random = new Random();
int[] ints = random.ints(25, 0, 99).sorted().toArray();
int[] even = IntStream.of(ints).filter(x -> x % 2 == 0).toArray();
int[] odd = IntStream.of(ints).filter(x -> x % 2 == 1).toArray();
System.out.println(Arrays.toString(even));
System.out.println(Arrays.toString(odd));
}
}
First an array of all random integers are being created. 25 random integers are created and they should all be between 0 and 99.
The evens and odds are filtered out into two separate arrays.
[0, 4, 6, 16, 18, 22, 40, 42, 58, 64, 82, 84, 98]
[7, 27, 29, 31, 35, 55, 73, 75, 75, 79, 83, 91]
I have an array with this values 80 82 84 90 94 is it possible to subtract the values so the output could be 0 2 2 6 4?
I´ve edited the question:Now I want to use this in an android cursor adapter but I´m getting index out of bounds when it reaches the calculation of the difference.
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
double weight = cursor.getDouble(cursor
.getColumnIndex(DbHelper.ENTRY_USER_WEIGHT));
int count=cursor.getCount();
Double[] input = new Double[count];
// Obtaining the number of records
System.out.println("number of records "+input.length);
// Array for storing differences
double[] difference= new double[count ];
difference [0] = 0; // First record difference is 0 only
int i;
// Looping number of records times
for( i=0; i<count-1 ;i++)
{
input[i]=weight;
System.out.println("i value"+i);
System. out.println(""+input[i]);
// Difference = next record - current record
difference [i]= input [i+1] - input[i];
// System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i]);
}
// Setting the input array.
int input[]= {80, 82, 84, 90, 94};
// Obtaining the number of records
int noOfRecords = input.length;
// Array for storing differences
double[] difference= new double[noOfRecords ];
difference [0] = 0; // First record difference is 0 only
// Looping number of records times
for( int i=0; i < noOfRecords -1 ;i++)
{
// Difference = next record - current record
difference [i+1]= input [i+1] - input[i];
System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i+1]);
}
System.out.println("My final difference array Output is : "+java.util.Arrays.toString( difference ));
OUTPUT:
Difference between 82 and 80 is : 2.0
Difference between 84 and 82 is : 2.0
Difference between 90 and 84 is : 6.0
Difference between 94 and 90 is : 4.0
My final difference array Output is : [0.0, 2.0, 2.0, 6.0, 4.0]
If you replace double[] difference = new double[noOfRecords ]; by
int [] difference = new int [noOfRecords];
You get an output exactly as you wanted :
Difference between 82 and 80 is : 2
Difference between 84 and 82 is : 2
Difference between 90 and 84 is : 6
Difference between 94 and 90 is : 4
My difference array Output is : [0, 2, 2, 6, 4]
Logic:
for array Arr[] = {80 82 84 90 94}
Required output = {0,2,2,6,4}
Sol:
output[0] = 0;
for( i=1;i<cursor.getCount();i++)
{
output[i] = Arr[i]-Arr[i-1];
}
Note that the output array elements are obtained by subtracting current index element with the element at previous index.
Example 82-80 =2, 84-82=2, 90-84=6 and 94-90=4
You can subtract a number from its next number.
int[] numbers={80, 82, 84, 90, 94};
for (int i = 0; i < numbers.length; i++) {
if(i < numbers.length - 1)
System.out.println(numbers[i + 1] - numbers[i]);
}
}
Output-
2
2
6
4