Efficient Data Structure for the average of a matrix - java

I have an array list.
Its value is
arrlist[0] = 1 2 3
arrlist[1] = 4 5 6
arrlist[2] = 7 8 9
arrlist[3] = 10 11 12
arrlist[4] = 13 14 15
WHat I want is getting the avg of : 1,4,7,10,13. Then an avg of 2,5,8,11,14 and so on
and the resulting arraylist should contain only one string like 7,8,9 (the avg of all 5 columns )
The nos would be random.
Which would be the best efficient manner. ??
I thought of a method where I store every element in a new array list but the looping would be much big.
Can anyone suggestme an efficient way.
The way I am thinking is : Just a psuedo code
arraylist newarrylist = new arraylist ();
for(int j=0;j<arrlist.size*arrlist[0].size;j++) // as each arrlist would have same elements
{
newarrylist[j] = arrlist(j).sunstring(j); // means will get the substring, first column, then second..
}

Like people said, premature optimization is the root of all evil; unless of course your array is big (e.g. 10000 rows * 10000 columns).
In any case, there are not that many options in calculating averages!
What I'd do is something like this (take this more as a pseudo-code, I have not debugged it; also, make sure there are no integer overflows):
int[] columnAverages = new int[width];
for (int row = 0; row < height; row++)
for (int column = 0; column < width; column++)
{
int value = (parse the next integer here);
columnAverages[column] += value;
}
for (int column = 0; column < width; column++)
columnAverages[column] /= height;
Hope this helps

The data structure used in here is an array list (collection) of an array of integers.
There you go, a solution for your problem:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
*
* #author Mohamed Ennahdi El Idrissi
* 25 February 2014.
*
*/
public class User3345483 {
/*
* arrlist[0] = 1 2 3
* arrlist[1] = 4 5 6
* arrlist[2] = 7 8 9
* arrlist[3] = 10 11 12
* arrlist[4] = 13 14 15
*/
static List<Integer[]> arrliste = new ArrayList<Integer[]>();
public static void main(String[] args) {
/*
arr = new Integer[]{1, 2, 3};
arrliste.add(arr);
arr = new Integer[]{4, 5, 6};
arrliste.add(arr);
arr = new Integer[]{7, 8, 9};
arrliste.add(arr);
arr = new Integer[]{10, 11, 12};
arrliste.add(arr);
arr = new Integer[]{13, 14, 15};
arrliste.add(arr);
*/
initArray();
initArray();
initArray();
initArray();
initArray();
displayArray();
Integer[] arr;
arr = new Integer[3];
int avg;
for (int i = 0; i < arr.length; i++) {
avg = 0;
for (int j = 0; j < arrliste.size(); j++) {
avg += ((Integer[]) arrliste.get(j))[i];
}
avg = avg/arrliste.size();
System.out.println("Average Column " + i + ": " +avg);
arr[i] = avg;
}
}
static void initArray() {
Integer[] arr = new Integer[3];
for (int i = 0; i < arr.length; i++) {
arr[i] = new Random().nextInt(100);
}
arrliste.add(arr);
}
static void displayArray() {
System.out.println("Values of the Populated Array:");
for (Integer[] integer : arrliste) {
for (int i = 0; i < integer.length; i++) {
System.out.print(integer[i] + "\t");
}
System.out.println();
}
}
}

Related

fill two dimensional array with unique random number with java

Is there any way to fill two dimensional array with unique random number ? I tried so much but all of my tries are failed .
I can do this
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i < 26; i++) { //element will be in range (1,25)
list.add(i);
}
Collections.shuffle(list);
for (int j = 0; j < 5; j++) {
System.out.print(list.get(j) + " ");
}
System.out.println();
If you wanted to print a 5x5 matrix of numbers from the List, you just need two layers of for loops. See the below code in action here.
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i < 26; i++) { // element will be in range (1,25)
list.add(i);
}
Collections.shuffle(list);
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 5; k++) {
System.out.format("%3d ", list.get(j * 5 + k));
}
System.out.println();
}
System.out.println();
Example Output:
3 4 23 18 15
1 8 20 6 7
5 21 19 2 24
17 13 22 16 25
14 9 12 10 11
I guess you can use combination of library which generates the random number and hashset. Hashset to remember the random number generated so far, and if duplicate is generated, you re-generate until it gives you the unseen number
Try this.
static List<List<Integer>> uniqueRandomNumbers(int height, int width) {
List<Integer> list = IntStream.rangeClosed(1, height * width)
.boxed()
.collect(Collectors.toList());
Collections.shuffle(list);
List<List<Integer>> matrix = IntStream.range(0, height)
.mapToObj(i -> list.subList(i * width, (i + 1) * width))
.collect(Collectors.toList());
return matrix;
}
and
List<List<Integer>> matrix = uniqueRandomNumbers(5, 5);
for (List<Integer> list : matrix)
System.out.println(list);
result
[16, 4, 15, 14, 25]
[19, 11, 6, 21, 9]
[17, 20, 3, 1, 5]
[10, 7, 22, 18, 2]
[12, 13, 24, 23, 8]
Does this can help ?
public static void main(String[] args)
{
// declare arrays
int[][] ticketInfo;
String[][] seatingChart;
// create arrays
ticketInfo = new int [2][3];
seatingChart = new String [3][2];
// initialize the array elements
ticketInfo[0][0] = 15;
ticketInfo[0][1] = 10;
ticketInfo[0][2] = 15;
ticketInfo[1][0] = 25;
ticketInfo[1][1] = 20;
ticketInfo[1][2] = 25;
seatingChart[0][0] = "Jamal";
seatingChart[0][1] = "Maria";
seatingChart[1][0] = "Jacob";
seatingChart[1][1] = "Suzy";
seatingChart[2][0] = "Emma";
seatingChart[2][1] = "Luke";
// print the contents
System.out.println(ticketInfo);
System.out.println(seatingChart);
}

how to get minimum in 2d array java

I need help, please! I am building up the following code to extract the minimum value of each column of the distance
I have tried to compute the code but to no avail
public static void main(String[] args) {
int data[] = {2, 4, -10, 12, 3, 20, 30, 11};//,25,17,23}; // initial data
int noofclusters = 3;
int centroid[][] = new int[][]{
{0, 0, 0},
{2, 4, 30}
};
getCentroid(data, noofclusters, centroid);
}
public static int[][] getCentroid(int[] data, int noofclusters, int[][] centroid) {
int distance[][] = new int[noofclusters][data.length];
int cluster[] = new int[data.length];
int clusternodecount[] = new int[noofclusters];
centroid[0] = centroid[1];
centroid[1] = new int[]{0, 0, 0};
System.out.println("========== Starting to get new centroid =========");
for (int i = 0; i < noofclusters; i++) {
for (int j = 0; j < data.length; j++) {
//System.out.println(distance[i][j]+"("+i+","+j+")="+data[j]+"("+j+")-"+centroid[0][i]+"="+(data[j]-centroid[0][i]));
distance[i][j] = Math.abs(data[j] - centroid[0][i]);
System.out.print(distance[i][j] + " ,");
}
System.out.println();
}
int[] result = new int[distance.length];
for (int i = 0; i < distance.length; i++) {
//int min = distance;
int min = distance[i][0];
for (int j = 0; j < distance[0].length; j++) {
if (distance[i][j] < min) {
min = distance[i][j];
}
result[j] = min;
System.out.println(result[j] + ", ");
}
}
return result;
}
}
The result of the computation for distance gives
row 1: 0 ,2 ,12 ,10, 1 ,18 ,28 ,9
row 2: 2 ,0 ,14 ,8 , 1 ,16 ,26 ,7
row 3: 28,26,40 ,18, 27 ,10 ,0 ,19
I want to go through each column to get the minimum value
0 0 12 8 1 10 0 7
Thanks for your help in advance
To get the minimum value in each column, first, you need to iterate the column in the outer loop. By doing so, we can access the matrix colunm-wise.
Assign the first value of each column to a variable. Then iterate through the rows in the inner loop.
Check if the current value is less than the minimum value. If so, assign the smallest value to minimum.
When we use an array, we get an array of minimum values of the column.
To obtain the minimun value in each row, swap the loops and use min[i].
Below is an example code:
int []min = new int[column_lenght];
for(int j = 0; j < column_length; j++) {
min[j] = array[i][j];
for(int i = 0; i < row_length; i++) {
if(array[i][j] < min[j]) {
min[j] = array[i][j];
}
}
}
The min[] will contain the minimum value of each column.

How to double input of an array in java?

So, I am trying to take an array input of 6,7,34,7,6 and create a method to have the ouput be 6 6 7 7 34 34 7 7 6 6.
How would i go about that?
So far I have:
public int [] twice (int[] ary)
int [] A = new int [ary.length * 2]
A [0] = 6;
A [1] = 7;
A [2] = 34;
A [3] = 7;
A [4] = 6;
But i don't know where to go from there.
Try this one:
public static int[] twice(int[] ary) {
int[] A = new int[ary.length * 2];
for(int i=0, j=0;j<ary.length;i=i+2,j++) {
A[i] = A[i+1] = ary[j];
}
return A;
}
Just use two for loops
{
for (int i=0;i<5;i++) System.print(ary[i]);
for (int i=0;i<5;i++) System.print(ary[4-i]);
}
If u want to add the values at the end
// Java program explaining System class method - arraycopy()
import java.lang.*;
import java.util.Arrays;
public class NewClass
{
public static void main(String[] args)
{
int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int d[] = Arrays.copyOf(s, s.length*2);
int source_arr[], sourcePos, dest_arr[], destPos, len;
source_arr = s;
sourcePos = 0;
dest_arr = d;
destPos = s.length;
len = s.length;
// Use of arraycopy() method
System.arraycopy(source_arr, sourcePos, dest_arr,
destPos, len);
// Print elements of destination after
System.out.print("final dest_array : ");
for (int i = 0; i < d.length; i++)
System.out.print(d[i] + " ");
}
}
public static int [] twice (int[] ary)
{
int [] A = new int [ary.length * 2];
//take 2 variables one to point input array and 1 for output array
int c = 0;
for(int n: ary) {
//put each element of input array twice in output array
A[c] = A[c+1] = n;
c += 2;
}
//return output array
return A;
}
As your input values look like they're sorted and then you put the same values to destination array again in descending order, you might want to try attempt with sorting your input first depending on what you want to achieve:
public int [] twice(int[] ary) {
int[] temporary = new int[ary.length];
for (int i = 0; i < ary.length; i++) { // copying ary to temporary
temporary[i] = ary[i];
}
Arrays.sort(temporary); // sorting temporary in ascending order
int[] result = new int[ary.length * 2]; // creating double sized result array
for(int i = 0; i < temporary.length; i++) { // copying sorted contents of temporary at the beginning of result array
result[i] = temporary[i];
}
int j = 0 ;
for(int i = result.length - 1; i >= result.length / 2; i--) { // inserting contents of temporary from the end of result array to the middle ("from right to left")
result[i] = temporary[j++];
}
return result; // returning result array
}

Remove elements from 2D array

I want to remove elements that are in routedClients from array, so I converted it to an ArrayList, then used remove, finally I converted it back to double[][] array. But when I execute it, it gives me this message about this line:
double[][] remainingStockout = (double[][]) stockout.toArray();
The error is:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Double;
Any help would be really appreciated. :)
public double[][] removeSite(double[][] array) {
List<double[]> stockout = new ArrayList<double[]>(Arrays.asList(array));
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < routedClients.size(); j++) {
if (array[i][0] == routedClients.get(j)) {
stockout.remove(i);
}
}
}
double[][] remainingStockout = (double[][]) stockout.toArray();
return remainingStockout;
}
The below appears to work
double[][] remainingStockout = (double[][]) stockout.toArray(new double[][]{});
Full class for testing:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
static ArrayList<Double> routedClients = new ArrayList<Double>();
public static void main(String[] args) {
double[][] arr1 = { { 2, 4, 6 }, { 3, 6, 9 }, { 5, 10, 15 } };
routedClients.add(new Double(1));
routedClients.add(new Double(2));
routedClients.add(new Double(3));
print(arr1);
double[][] arr2 = removeSite(arr1);
print(arr2);
}
private static void print(double[][] arr1) {
for (int i = 0; i < arr1.length; i++) {
double[] arr2 = arr1[i];
for (int j = 0; j < arr2.length; j++) {
System.out.println("arr1[" + i + "][" + j + "] = " + arr1[i][j]);
}
}
}
public static double[][] removeSite(double[][] array) {
List<double[]> stockout = new ArrayList<double[]>(Arrays.asList(array));
System.out.println("length before = " + stockout.size());
for (int i = array.length-1; i >= 0; i--) {
for (int j = 0; j < routedClients.size(); j++) {
if (array[i][0] == routedClients.get(j)) {
System.out.println("removing " + routedClients.get(j));
stockout.remove(i);
}
}
}
double[][] remainingStockout = (double[][]) stockout.toArray(new double[][] {});
System.out.println("length after = " + remainingStockout.length);
return remainingStockout;
}
}
Here is the output
arr1[0][0] = 2.0
arr1[0][1] = 4.0
arr1[0][2] = 6.0
arr1[1][0] = 3.0
arr1[1][1] = 6.0
arr1[1][2] = 9.0
arr1[2][0] = 5.0
arr1[2][1] = 10.0
arr1[2][2] = 15.0
length before = 3
removing 3.0
removing 2.0
length after = 1
arr1[0][0] = 5.0
arr1[0][1] = 10.0
arr1[0][2] = 15.0
You are trying to cast an object into an array.
This cannot be done.
Instead you will need to convert each element in the array and then need to add it to they the 2D Array.
The following line will never work:
double[][] remainingStockout = (double[][]) stockout.toArray();
You can cast a double array into a list array because the compiler just makes a list with all the elements, but the compiler can't know which size to make a 2D array.
Maybe you could try creating a list of lists. You would need to traverse your array two more times though. One for assigning the values to the nested list and then to assign them again to the double array before returning the value.
you can use the overloaded method of toArray() .. like this -
double[][] remainingStockout = new double[array.length][array.length];
stockout.toArray(remainingStockout);

Code has incorrect last value in array

I can not find why the code has the last incorrect value for test 3 and 5. I can not change the array to array list. The methods are the only thing that I can change.
package Semester;
import java.util.ArrayList;
public class MemberArrayList {
private ArrayList<Integer> friendsScore = new ArrayList<Integer>();
private ArrayList<String> friendsID = new ArrayList<String>();
// Add a friend with ID with the score into friends.
public void addFriend(String friendID, int score) {
// TODO
friendsScore.add(score);
friendsID.add(friendID);
}
// Removes a friend with friendID, but you cannot use indexOf. Only methods you can use: size, equals, get, remove
public void removeFriend(String friendID) {
// TODO
for (int i = 0; i < friendsID.size(); i++)
{
if ( friendID.equals(friendsID.get(i)))
{
friendsScore.remove(i);
friendsID.remove(i);
}
}
}
// Get the scores of first 10 friends added
public int [] getScores10() {
// TODO
int size = 10;
int[] score = new int[size];
for (int i = 0; i < 10; i++)
{
score[i] = friendsScore.get(i);
}
return score;
}
public int [] getScoresLast10() {
// TODO
int[] score = new int[10];
int j = 0;
for (int i = friendsScore.size()-1; i > (friendsScore.size()-10); i--)
{
score[j] = friendsScore.get(i);
j++;
}
return score;
}
// Get the scores of the friends in the array, but you cannot use indexOf function. You can only use size, get, equals, intValue
public int [] getScores(String [] friendIDs) {
// TODO
int value = friendIDs.length;
int[] score = new int[value];
for (int i = 0; i < value; i++)
{
String person = friendIDs[i];
for (int j = 0; j < friendsID.size(); j++)
{
if (person.equals(friendsID.get(j)))
{
score[i] = friendsScore.get(j);
}
}
}
return score;
}
public static void main(String[] args) {
MemberArrayList member = new MemberArrayList();
member.addFriend("Paul", 3);
member.addFriend("Peter", 1);
member.addFriend("Mary", 2);
member.addFriend("John", 4);
member.addFriend("Karen", 7);
member.addFriend("Kevin", 3);
member.addFriend("Walter", 1);
member.removeFriend("Mary");
member.removeFriend("Walter");
member.addFriend("Steven", 21);
member.addFriend("Kelly", 9);
member.addFriend("Kaitlin", -5);
member.addFriend("Bea", 77);
member.addFriend("Max", 32);
System.out.println("Test 1");
String [] friendIDs = {"Paul","Kevin","Steven","Max"};
int [] scores = member.getScores(friendIDs);
for (int i = 0; i < scores.length; i++)
System.out.println(friendIDs[i]+" "+scores[i]);
System.out.println("Test 2");
scores = member.getScores10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
System.out.println("Test 3");
scores = member.getScoresLast10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
member.removeFriend("Bea");
member.addFriend("Eric", -1);
member.addFriend("Abby", -2);
member.addFriend("Jacob", 3);
member.addFriend("Blake", 8);
System.out.println("Test 4");
scores = member.getScores10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
System.out.println("Test 5");
scores = member.getScoresLast10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
}
}
The output should be
Test 1
Paul 3
Kevin 3
Steven 21
Max 32
Test 2
3
1
4
7
3
21
9
-5
77
32
Test 3
32
77
-5
9
21
3
7
4
1
3
Test 4
3
1
4
7
3
21
9
-5
32
-1
Test 5
8
3
-2
-1
32
-5
9
21
3
7
Your loop for counting down is missing one value to copy:
Wrong:
for (int i = friendsScore.size()-1; i > (friendsScore.size()-10); i--)
This runs for 9 times.
Right:
for (int i = friendsScore.size()-1; i >= (friendsScore.size()-10); i--)
This runs 10 times and copies all 10 values to the array. Note the >= instead of >.
With the first loop the last value of your array will never be set and so defaults to 0 or whatever your compiler might set (I think it is always 0 in java but I'm not sure).

Categories

Resources