Subtract elements in an array - java

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

Related

How to sum an ArrayList in Java element by element

I have a double ArrayList that has this numbers:
2, 4, 10, 14, 20, 33...
And I want to create a new ArrayList with the sum of the first ArrayList, but the sum result must to be:
2, 6, 16, 30, 50, 83...
The operations inside must to be:
position 0: 2 without operations
position 1: 2 + 4 = 6
position 2: 10 + 6 = 16
position 3: 14 + 16 = 30
position 4: 20 + 30 = 50
position 5: 33 + 50 = 83
...
At the moment i have this:
ArrayList <Double> velocidad = new ArrayList();
ArrayList <Double> velocidad_acum = new ArrayList();
double prevVel = 0;
double vel_acum = 0;
velocidad.add(vel);
for (double i : velocidad){
int currentIndex = velocidad.indexOf(i);
int prevIndex = velocidad.indexOf(i) - 1;
if (currentIndex > 0){
prevVel = velocidad.get(prevIndex);
vel_acum = prevVel + i;
}
}
velocidad_acum.add(vel_acum);
"vel" is a variable that update its value each second, and each second the ArrayList "velocidad" acumulates a new number inside.
This code mades with the example above:
2, 6, 14, 24, 34, 53...
position 0: 2 without operations
position 1: 2 + 4 = 6
position 2: 10 + 4 = 14
position 3: 14 + 10 = 24
position 4: 20 + 14 = 34
position 5: 20 + 33 = 53
...
List<Double> one = Arrays.asList(2.0, 4.0, 10.0, 14.0, 20.0, 33.0);
List<Double> two = new ArrayList<>();
double sum = 0;
for (double d: one) {
sum += d;
two.add(sum);
}
System.out.println(two);
// [2.0, 6.0, 16.0, 30.0, 50.0, 83.0]
Start sum with 0 and keep adding intermediate sum values to the List.
We're not going to do your homework for you, but here is a basic pseudo code solution:
public static List<Double> sum(List<Double> src) {
//Create a List<> to hold your sums
List<Double> sumList = new ArrayList<>();
//loop through your src list
for (Double item : src) {
//If the sumList is empty, add the item to your sumList
//other wise, grab the value at the end of your sumList
//add it to the item, and add that value to your sumList
}
return sumList;
}

How read array from a file

im trying to create a matrix from a file, the file is like this:
Where my first line has the size of the matrix= 10 x 9
And in the other lines, we have 15 values distributed aleatory.
3 5
4 5 6
12 34 12 12 8
34 23
12 34 34 10 89
With the info size i will define my matriz. I use this method for read:
public static void read(){
String line= "";
int i = 0;
try {
while((line = bf.readLine()) != null){
if (i == 0){
//Call method that get the size and create my global matriz
}else{
String[] list = line.split(" ");
//I need help here, for insert correctly in the array
}
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How i can do for insert orderly in the matrix? My matrix should be like:
4 5 6 12 34
12 12 8 34 23
12 34 34 10 89
Any idea?
This is one way to do it:
String input = "3 5\n" +
"4 5 6\n" +
"12 34 12 12 8\n" +
"34 23\n" +
"12 34 34 10 89\n";
Scanner in = new Scanner(input);
final int rows = in.nextInt();
final int cols = in.nextInt();
int[][] matrix = new int[rows][cols];
int row = 0, col = 0;
for (int i = 0; i < rows * cols; i++) {
matrix[row][col] = in.nextInt();
if (++col == cols) {
row++;
col = 0;
}
}
System.out.println(Arrays.deepToString(matrix));
Output:
[[4, 5, 6, 12, 34], [12, 12, 8, 34, 23], [12, 34, 34, 10, 89]]
It is not necessarily the best way to do it, but I wanted to show the manual increment logic of col and row, where row is incremented when col rolls over.
Using answer by sebenalern, it'd work like this:
int[][] matrix = new int[rows][cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
matrix[row][col] = in.nextInt();
Using answer by Paul, it'd work like this:
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows * cols; i++)
matrix[i / 5][i % 5] = in.nextInt();
All 3 versions rely on the Scanner to simply provide all the values in a sequence, regardless of how they were put together on lines.
If you don't want to use Scanner (e.g. because it is slow), and read the input line-by-line, then values on a line, the 1st version would be easier to use. Otherwise the 3rd is the shortest, and the 2nd version is the most straightforward.
Just a hint - I'll leave your homework to you - :
In this case it would be pretty simple to maintain a counter of all values that have been read so far, and map each of these counter-values to a matrix-value like this:
0 = (0 , 0)
1 = (1 , 0)
...
5 = (0 , 1)
6 = (1 , 1)
...
Using something like this:
int row = counter / rowLength;
int col = counter % rowLength;
In your case:
matrix[counter/5][counter%5] = someValue;

How to check duplicate numbers and print out the read input numbers in the same order that they were read (excluding all duplicates.)

I'm trying to write a code. There I'll get max 1000 (int)inputs from an user (it has to be array[1000]) and it'll print out the ints in the same order as they were written.
Reading can be stopped by ctrl+z if the user wants that. The program will not write out duplicate numbers.
Example;
Input: 45 77 -22 3 45 0 21 -1 3
Output: 45 77 -22 3 0 21 -1
So far I've coded(within 2 days):
static int i = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] array = new int[1000];
int[] arrayCopy = new int[1000];
int k=0,j=0;
System.out.println("enter your integer numbers");
while(input.hasNext())
{
array[i] = input.nextInt();
for(j =0 ; j< array.length; j++)
{
arrayCopy[j] = array[j];
}
for( k =1; k<arrayCopy.length; k++)
{
int aV = arrayCopy[k];
}
i++;
}
input.close();
}
}
Use a HashMap to keep track of numbers already seen. Only add to your output string if it is a new number. You can modify your code with the following:
int[] array = new int[1000];
Scanner input = new Scanner(System.in);
int index = 0;
while(input.hasNext()) {
array[index] = input.nextInt();
index++;
}
HashMap<Integer, Boolean> seenNumbers = new HashMap<Integer, Boolean>();
String result = "";
for (int i = 0; i < index; i++) {
int value = array[i];
if (!seenNumbers.containsKey(value)) {
result += " " + value;
seenNumbers.put(value, true);
}
}
System.out.println(result);
The simplest solution is for me to use LinkedHashSet - will not allow duplicates and preserves insertion order
Set <Integer> set = new LinkedHashSet<>(1000);
while (input.hasNext()) {
int next = input.nextInt();
set.add(next);
}
input.close();
for (Integer number : set) {
System.out.print(number+" ");}
Should work
Provided you can resolve a sort order, and use arrays:
Below pseudocode and data. It's written as arrays, but you can ofc always loop where required. I also write the data without commas, as that's what my language Dyalog APL outputs ;-), but the data below are simply 9-element 1-dimensional arrays. The result seems to hold 7 elements.
You have
A = 45 77 -22 3 45 0 21 -1 3
Resolve the ascending sort order for A:
order = 3 8 6 4 9 7 1 5 2 // A[3] is smallest, then A[8], A[6], etc.
Write:
B = A[order] // B now holds: -22 -1 0 3 3 21 45 45 77
Loop through all but first element of B, check if next element is same as current. Write the result to C, which is a same-length vector of zeroes, however first element of C must be 1:
C = 1 0 0 0 0 0 0 0 0
s = 2
:While (s <= [length of C])
C[s] = (B[s-1] == B[s]) // C[s] is 0 or 1
s += 1
:End
Now C holds:
1 1 1 1 0 1 1 1 0
Create an empty variable D (or just copy from A or B - you will overwrite it):
D = A
Assign the elements of D as follows:
D[order] = C // D now holds: 1 1 1 1 0 1 1 1 0
Take only D elements of A (you pick elements of A and append them to a Result, which is initially empty - ie. has zero length):
s = 1
:While (s <= [lenght of A])
:if D[s] // Means: If (D[s] == 1)
[append A[s] to Result]
s += 1
:End
:End
Result now contains
45 77 -22 3 0 21 -1
Use Set instead of array. Set wont add duplicates.

1 Dimensional Array, Multiples of 5. Stuck on a few. New to coding

This is the assignment:
Write a program that assigns and stores the first 20 multiples of 5 in the array called Data, no other array can be used in the program. The program should output the elements of the array, according to the following:
a) write only the commands to assign and store the values in Data
b) output the array: 10 numbers/line with the sum of each line
c) output the array: in reversed order, 5 numbers/line with the sum for each line
d) the odd indexed position values (Data[1], Data[3], Data[5],...), 5 values/line and their sum
e) the even indexed position values (Data[3], Data[4], Data[6],...), 5 values/line and their sum
This is my code:
//** TASK 4
//a,b
int data[]=new int[21]; int sum=0;
for(int i=1;i<21;i++){
data[i]=5*i;
sum+= data[i];
if(i%11==0)
System.out.println();
System.out.print(data[i] + " ");
}
System.out.println("sum " + sum);
// int a[]=new int[21];
// for(int i=1;i<21;i++){
// a[i]=5*i;
// //System.out.print(a[i] + " ");
// }
// System.out.println();
System.out.println();
//c
int sum2=0;
for(int i=data.length-2;i>0;i--){
data[i]+=5;
sum2+= data[i];
if(i%5==0)
System.out.println();
System.out.print(data[i] + " ");
}
System.out.println("sum " + sum2);
System.out.println();
//d
int sum3=0;
for(int i=1;i<21;i=i+2){
data[i]=5*i;
sum3+= data[i];
if(i%11==0)
System.out.println();
System.out.print(data[i] + " ");
}
System.out.println("sum " + sum3);
System.out.println();
//e
int sum4=0;
for(int i=2;i<21;i=i+2){
data[i]=5*i;
sum4+= data[i];
if(i%5==0)
System.out.println();
System.out.print(data[i] + " ");
}
System.out.println("sum " + sum4);
This is the output:
For a/b)
5 10 15 20 25 30 35 40 45 50
55 60 65 70 75 80 85 90 95 100 sum 1050
I dont know how to seperate my a and b code
For c)
100 95 90 85
80 75 70 65 60
55 50 45 40 35
30 25 20 15 10 sum 1045
for c i am getting 4 numbers in the first line, i dont know why
For d)
5 15 25 35 45
55 65 75 85 95 sum 500
I have this right
For e)
10 20 30 40
50 60 70 80 90
100 sum 550
it is not letting me have 5 numbers per line
***I dont know how to put the sum for each line for all of the parts of this assignment.
My teacher did not teach us how and wont help up and i am so confused. Please help. I have been trying to figure it out for so long
he wants it to start from 5 not 0
I won't give the answer here, being a homework assignment I believe the process is more important than the result. However I'll try to guide as well as I can.
The first thing I notice is that the StringBuilder class is extremely useful here.
As #Filburt pointed out: Try to do this one part at a time.
Starting with a: Try to get used to the fact that the first index is 0, then just iterate over the 20 elements and make their value what you want: (i+1)*5
b: Here modulus and the StringBuilder comes in handy. What you are looking to do is something like iterating over all data[i] then appending data[i] + " " to the string builder, at the same time setting a running sum of the value.
Since you want to add the sum and a new line every 10 entries a useful thing to know is that i%10 for the 20 values is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
So when you get to the 10th element, 9 you want to add the sum to the StringBuilder and a new line character ("\r\n"on windows, "\n" on Unix/MacOSX) and set the sum back to 0.
At the end you can simply print the stringbuilder and voila!
c: Same as the previous, really, just iterating backwards, and a modulus of 5 going 4, 3, 2, 1, 0, ... (meaning you add the sum on 0 ).
d & e: This is actually identical with b, but only printing every other entry, where i%2 == 1 and i%2 == 0 in that order. So just make sure only to append to the stringbuilder when this is true and all should be fine.
Hoping this helps without being too obvious.
I don't know if I should be posting this, but here you go anyway:
// Part (a)
int data[] = new int[21];
for (int i = 1; i < 21; i++){
data[i]=5*i;
}
// Part (b)
int sum=0;
for(int i = 1; i < 21; i++){
System.out.print(data[i] + " ");
sum+= data[i];
if(i%10==0)
{
System.out.println(" Sum: " + sum);
sum = 0;
}
}
System.out.println();
// Part (c)
int sum2=0;
for(int i = 1; i < 21; i++){
System.out.print(data[21-i] + " ");
sum2+= data[21-i];
if(i%5==0)
{
System.out.println(" Sum: " + sum2);
sum2 = 0;
}
}
System.out.println();
// Part (d)
int sum3=0;
for(int i= 2; i < 22; i = i+2){
System.out.print(data[i-1] + " ");
sum3+= data[i-1];
if(i % 10 == 0){
System.out.println(" Sum: " + sum3);
sum3 = 0;
}
}
System.out.println();
// Part (e)
int sum4=0;
for(int i=2;i<21;i=i+2){
System.out.print(data[i] + " ");
sum4+= data[i];
if(i % 10==0){
System.out.println(" Sum: " + sum4);
sum4 = 0;
}
}
This is what you need, I think.

creating a 2d array from a String

I am trying to create a 2d array from a String. But i am getting some weird results when i try to set the value of elements in the array.
Here String s = 120453678;
public int[][] create2D(String s){
int[][] puzzle = new int[3][3];
int a;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
puzzle[i][j] = (int)s.charAt(i*3+j);
System.out.println(s.charAt(i*3+j));
System.out.println(i +" "+ j+" "+ puzzle[i][j]);
}
}
return puzzle;
}
The output i am getting is. Don't know why its 49, 50 , 51 and so on
1
0 0 49
2
0 1 50
3
0 2 51
4
1 0 52
5
1 1 53
0
1 2 48
6
2 0 54
7
2 1 55
8
2 2 56
You are converting the character to it's int representation. That's why you are getting this result.
puzzle[i][j] = (int)s.charAt(i*3+j);
ASCII table can be referred below. You can see that 49 is ASCII value of character '1'.
http://www.asciitable.com/
To fix your code, you can use
puzzle[i][j] = Character.getNumericValue(s.charAt(i*3+j));

Categories