Initialize 2d list in Java - java

I am new to Java and trying to create a 2d list the size of which isn't fixed.I have a class which looks like this:
public class q1 {
List<List<Integer> > L = new ArrayList<List<Integer> >();
public void set(int m,int n){
//This is the function which would get the size of the 2d list
}
}
I saw the answers but they had to be of fixed sizes, eg:
ArrayList<String>[][] list = new ArrayList[10][10];
But, I want different sizes of the list L for different objects. There were other options like copyOf, but can the above functionality be achieved just by this array?

You are mixing two things in your question, ArrayLists and arrays. ArrayList is a variable size container backed by an array. ArrayList has a constructor where you can specify the initial capacity you need so with ArrayLists it will look like:
public class q1 {
List<List<Integer>> L;
public void set(int m, int n){
L = new ArrayList<>(m); // assuming m is the number or rows
for(int i = 0; i < m; ++i) {
L.add(new ArrayList<>(n));
}
// now you have a List of m lists where each inner list has n items
}
}
With arrays, the syntax is slightly different:
public class q1 {
Integer[][] L;
public void set(int m, int n){
L = new Integer[m][]; // assuming m is the number or rows
for(int i = 0; i < m; ++i) {
L[i] = new Integer[n];
}
// now you have a array of m arrays where each inner array has n items
}
}
Moreover if all the inner arrays will have the same length (n) the set method could be simplified to:
public void set(int m, int n){
L = new Integer[m][n]; // assuming m is the number or rows
// now you have a array of m arrays where each inner array has n items
}

There's no such special syntax for Lists, but you could always just iterate over the number of smaller lists and initialize them individually. Note that passing the size to the ArrayList's constructor doesn't really set its size, but it is does allocate the space, and may save you rellocations in the future:
public void set(int m,int n){
l = new ArrayList<>(m);
for (int i = 0; i < m; ++i) {
l.add(new ArrayList<>(n));
}
}

Related

How to efficiently sort a Multidimensional Arrray

I was given a task to sort multidimensional array into ascending order without using the pre-made functions in the Array class (such as .sort).
I've tried asking some of my friends for ideas... Many of them turns the array into a single-dimensional array, sort it the way you would sort a single-dimensional array and then turns it back into a multidimensional array.
I'm just curious to know if there'd be any other ways to do this without having to go through such trouble.
I've found a solution... Thanks all
public static void sortAscending(int array[][]) {
int temp = 0;
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
for(int k = 0; k < array.length; k++) {
for(int l = 0; l < array[k].length; l++) {
if(array[i][j] < array[k][l]) {
temp = array[i][j];
array[i][j] = array[k][l];
array[k][l] = temp;
}
}
}
}
}
}
here is a full exemple you can tri
import java.util.Arrays;
import java.util.Comparator;
public class PartNumberQuantityDetailer {
// initialize a two dimensional array
static Integer[][] itemIdAndQty = new Integer[5][2];
public static void main(String[] args) {
// initialize array values
itemIdAndQty[0][0] = 1234;
itemIdAndQty[0][1] = 46;
itemIdAndQty[1][0] = 5443;
itemIdAndQty[1][1] = 564;
itemIdAndQty[2][0] = 362;
itemIdAndQty[2][1] = 24;
itemIdAndQty[3][0] = 6742;
itemIdAndQty[3][1] = 825;
itemIdAndQty[4][0] = 347;
itemIdAndQty[4][1] = 549;
System.out.println("Before sorting");
// show the contents of array
displayArray();
// sort the array on item id(first column)
Arrays.sort(itemIdAndQty, new Comparator<Integer[]>() {
#Override
//arguments to this method represent the arrays to be sorted
public int compare(Integer[] o1, Integer[] o2) {
//get the item ids which are at index 0 of the array
Integer itemIdOne = o1[0];
Integer itemIdTwo = o2[0];
// sort on item id
return itemIdOne.compareTo(itemIdTwo);
}
});
// display array after sort
System.out.println("After sorting on item id in ascending order");
displayArray();
// sort array on quantity(second column)
Arrays.sort(itemIdAndQty, new Comparator<Integer[]>() {
#Override
public int compare(Integer[] o1, Integer[] o2) {
Integer quantityOne = o1[1];
Integer quantityTwo = o2[1];
// reverse sort on quantity
return quantityOne.compareTo(quantityTwo);
}
});
// display array after sort
System.out.println("After sorting on quantity in ascending order");
displayArray();
}
private static void displayArray() {
System.out.println("-------------------------------------");
System.out.println("Item id\t\tQuantity");
for (int i = 0; i < itemIdAndQty.length; i++) {
Integer[] itemRecord = itemIdAndQty[i];
System.out.println(itemRecord[0] + "\t\t" + itemRecord[1]);
}
System.out.println("-------------------------------------");
}
}]
sort multidimensional array into ascending order:
You can sort multi-d array row-wise or column -wise.
If you don't want to flatten the array that is convert it into 1-d then that mean you have to go through each row or column depending on your choice and apply quick-sort(better performance for small data set if pivot is chosen optimally) or merge-sort.
So you can do both in (considering avg. case) O(nlogn) and say there are n rown or n columns the time complexity will be O(n^2(logn)).
Now above the assumption is that you want to sort either row-wise or column-wise.
If you want to achieve the both(row and column) then it's better if you convert the array to 1-d and then apply sort and then convert it back. Otherwise following above approach the time complexity can go O(n^2(logn)) but in the other case it will be O((n+m)log(n+m)) where n amd m are no. of rows and columns in array plus the O(n+m) space complexity.
In my opinion having a bit of space complexity so that you can bring down the run-time is preferable.

Array as an attribute in a java class?

I have an assignment which consists of several small tasks:
I have to initilize an array and fill it with a 200/400/800 values (each amount - once).
I have to take the array values and put it in a red black tree, with certain conditions that are translated to methods.
Some more tasks.
I could do it all in the main class, however it seems to me I would be better off start a new class - handleArray.
If I start a class such as:
public class handlyArray{
protected int [] arr = new int[];
}
But if I do that, should I write a "get" and "set" functions to get the array's length?
The problem is that when I make this an error pops up - "Array initilizer expected".
Additional functions I have in the class:
public void fillArray(handleArray arr, int k){
Random rand=new Random();
for (int i = 0; i <k ; i++) {
int value = rand.nextInt(1024);
arr[i]=value;
}
}
- A function that creates Nodes for the redblackTree and inserts them to the tree
Any suggestions for how to build it?
Can I build the class with no attributes at all?
Thanks!
I'm wary of this being homework so I'll give you an overview and let you do the specifics.
Yes you can build a getter and setter in your new class, something like:
public int[] getArray() {
return arr;
}
public void setArray(int[] arr) {
this.arr = arr; //
}
As for getting the length, you don't need a method for it as you can just call the above getter and ask it for the length, e.g.
int arrayLength = handlyArray.getArray().length;
Finally yes you need to set up your array first, if you pass in an initialized array to the setter that will do fine, e.g.
handlyArray.setArray(new int[] {200, 400, 800});
Good luck, feel free to ask if you require further explanation.
You can inisialize the array inside the method like this :
public void fillArray(handlyArray arr, int k) {
Random rand = new Random();
arr.arr = new int[k];//<<---------------------Initialize the array
for (int i = 0; i < k; i++) {
int value = rand.nextInt(1024);
arr.arr[i] = value;// Note to fill the array you have to use arr.arr not just arr
}
}
and the handlyArray should be like this :
public class handlyArray {
protected int[] arr;//<<---------------------Just declare the array
}
to use fillArray method you can use :
a.fillArray(new handlyArray(), length);
I don't think so. I would just do a static method somewhere:
public static int[] randomArray(int size){
Random rand=new Random();
int[] arr = new int[size];
for (int i = 0; i < size ; i++) {
int value = rand.nextInt(1024);
arr[i]=value;
}
return arr;
}
Now, as for the red/black tree, I believe that a TreeSet is implemented with a red/black tree.
You can't set an arrays length. The length of an array has to be set during initialization. You can pass the length of the array in the constructor of your class:
public class HandleArray {
protected int [] arr;
public HandleArray(int length) {
arr = new int[length];
}
}

How to reset a sorted array to unsorted in Java?

I am writing a program to compare different sort methods. I random generated 100,000 integers and store these data to an array. I want to apply the same array to different sort methods in order to do the comparison. (I think create class for each method may solve my problem. But I don't want to create too many class). So I decided to create one class called Sorts and bunch of sort functions under this class. I want to my sorted array reset to unsorted in order apply the same array to different sort method. Could anyone tell me how?
Generate data:
int size = Integer.parseInt(br.readLine());
int [] data = new int[size];
for (int i = 0; i< size; i++){
data[i] = (int)(Math.random()*(10*size));
System.out.print(data[i]+" ");
}
Create object:
Sorts sort = new Sorts(size, data);
Invokeļ¼š
switch(index){
case "1" :
System.out.print("\nYou select bubble sort\n");
sort.bubbleSort();
break;
case "2" :
System.out.print("You select quick sort\n");
sort.quickSort();
break;
My class:
class Sorts{
private int size;
private int data[];
Sorts(int size, int [] data){
this.size = size;
this.data = data;
}
protected void bubbleSort(){
int temp = 0;
for (int i = 0; i< (data.length-1); i++){
for (int j = 0; j<(data.length-1);j++){
if(data[j]>data[j+1]){
temp = data[j];
data[j] = data[j+1];
data[j+1]= temp;
}
}
}
printResult();
}
protected void quickSort(){
}
protected void resetData(){
}
}
Well, you could use Collections.shuffle, which takes a 'List' parameter. This would obviously mean converting your 'int[]' to 'List' (and back again).
Here's the java spec for 'Collections.shufffle'.
See the 'Collections.shuffle' tutorial on tutorialspoint.
There's also a sample array ('int[]') version on Vogella.
On another point, rather than implement it as you have, Ithink it's better to use the Strategy pattern to implement multiple sort mechanisms like this. For instance:
interface Sort {
void sort(int data[], int size);
}
class QuickSort implements Sort {
void sort(int data[], int size) {
...
}
}
class MergeSort implements Sort {
void sort(int data[], int size) {
...
}
}
etc...
As a further aside:
this is only sorting ints so consider how to sort any type (and perhaps generics).
some sorts (e.g. MergeSort) are stable and use new arrays to represent the sorted data. How can you return that to the caller? You can't set 'data' to your new array.
You can use the Method shuffle of the class Collection
Collection.shuffle(yourList);
This will shuffle your list automatically without implementing an own function.
After that you can convert the list back to an array. :)
I think for the usecase OP seems to have, the array just needs a reshuffling, this method reshuffles although there is no guarantee that it would reset it to the original array
private void reset(final int arr[]) {
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
int nextInt = rand.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[nextInt];
arr[nextInt] = temp;
}
}

filling values in array

what i want to do is fill the empty aray kyo[] with the add() method but it keeps getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
0 at TestPlass.Add(TestPlass.java:30) at
TestPlass.main(TestPlass.java:18)
i'm just new to programming
public static int size = 30;
public static void main (String args[]) {
int kyo[] = {};
Add(kyo);
for(int x:kyo){
System.out.print(x + " ");
}
}
static void Add(int x[]){
for(int g=0; g<=size; g++){
x[g] = g;
}
}
If your kyo array has a fized size, you need to create it with this size.
public static int size = 30;
public static void main(String args[]) {
int kyo[] = new int[size];
add(kyo);
for (int x : kyo) {
System.out.print(x + " ");
}
}
static void add(int x[]) {
for (int g = 0; g < x.length; g++) {
x[g] = g;
}
}
You add function receives int x[] as input, so it should use x.length for the iterator and not your size variable.
I have also edited the name of your Add() method to be add() to respect Java code conventions.
An empty array can never have any content.
Once an array has been created, its size is fixed - you can change the content of the elements, but you can't change how many elements it has. See the Java arrays tutorial for more information.
If you need a dynamically-sized collection, I suggest you use a List<E> implementation, such as ArrayList<E>:
List<Integer> list = new ArrayList<>();
add(list);
for (int x : list) {
System.out.print(x + " ");
}
...
private static void add(List<Integer> list) {
// I assume you want "size" elements, not "size + 1"
for (int g = 0; g < size; g++) {
list.add(g);
}
}
This line:
int kyo[] = {};
creates an array of size zero. Arrays have a fixed size in Java; once an array has been created, its size is fixed. You have to create the array like this:
int[] kyo = new int[30];
This will create an array with 30 elements.
You need to give the size of the array when you create it, like:
int kyo[] = new int[size];
You can find some great info on arrays here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Arrays do not resize themselves automatically, so the size you initialize it with will be its size forever.
Cheers,
Marcus
Your problem lies here: int kyo[] = {};
{} Creates an array of zero size. Since you are adding 31 elements to the array you need to initialize you array to appropriate size.
For example: int[] kyo = new int[31];

Shuffle the Integer of the Object<Integer,String> in a List/ArrayList

List<Data> list = new ArrayList<Data>();
public class Data{
public int n;
public String p;
public Data(int N, String P) {
n = N;
p = P;
}
}
How can i shuffle the Integer of the Object: Data. So the String stays at the same position, and the Integer get's shuffled.
Loop through list and store the int of each Data object in a separate list. Shuffle this list using Collections.shuffle(...). Loop through this new shuffled list and set the n field of each corresponding member of list to the new random int found in the shuffled list.
Probably have to do it yourself:
for (int i = list.size(); i > 0; i--) {
int j = (int)(Math.random() * (i + 1));
int temp = list.get(i).n;
list.get(i).n = list.get(j).n;
list.get(j).n = temp;
}
The best you can do from java libraries is to first split it into two lists, one of ints and one of strings, then shuffle only the ints (using Collections.shuffle), then combine the two lists back into one list of Datas
You could use something like this:
List<Integer> ns = new ArrayList<Integer>(list.size());
for (Data data : list) {
ns.add(data.n);
}
Collections.shuffle(ns);
for (int i = 0; i < list.size(); i++) {
Data data = list.get(i);
int newN = ns.get(i);
data.n = newN;
}
Note that it's best practice to use accessors getN() and setN(int) and make Data.n private.

Categories