I have unsolvable task, I have task, where i have insert random number to array. The user can choose if array is 1D, 2D, 3D,size of array is optional . I tried everything but withot success. I can not use ArrayList.
Thank you for help.
double[] array= new double[size];
for ( int i;i<dimensional;i++)
{
double[] array= new double[size];
}
Edit:
I mind if is effective way to create array with 1D and then add to this array one or more dimension.
Multi-dimensional arrays in java are essentially just arrays of arrays. The user provides the number of dimensions and sizes at runtime so you need to dynamically build this array at this point. It's a strange problem, and not one that you would try to solve with arrays in production code, but nevertheless it should be possible. Try the accepted answer for this question, it seems like a pretty good attempt.
So, an "unsolvable" task ... well, as long as you work with primitive types and the dimension can be theoretically any number (only limited by memory available), you may be right.
You can however use some kind of object (Java is an object-oriented language) and solve the task rather easily. Basically, you might want a tree structure with nodes. You can even write a constructor that sets fixed sizes for every level and give no direct accessors to the array as a whole. Start with:
class Node {
double payload;
Node[] children;
}
I don't really understand what do you want to do with that, but it pretty much fits the idea of N-dimensional array.
Another solution: Make the array one-dimensional, but using the sizes of the individual dimensions, you can calculate the correct index. Of course, it will require you to handle the logic.
E.g. in a 2D array of 3x3 size, you can use a 1D array of 9 size and use first three indexes for first row, next three for second row, last three for third row. You can then use a cycle like this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//arr[i * 3 + j] = ...
}
}
Related
I have an array of byte that I want to process. My goal is to remove fixed size patterns.
I am using the following code :
byte buffer[] = {1,2,3,4,5,6,7,8,9,10};
int position; // position of the patern in the stream
int length = buffer.length();
int pattern_size = 64; // size of the patern to delete
for(i = position; i<length; i++){
// Shift the bytes
buffer[i] = buffer[i+pattern_size];
}
for(i = length; i>=(length-pattern_size); i--){
// Adding 0s at the end to make up for the loss of data
buffer[i]=0;
}
data_removed = data_removed + pattern_size;
As you can see I am adding zeros at the end of the byte array. I would actually prefer to reduce the size of the array. How can I do this ?
I'm sorry that this probably isn't going to be what you want to hear, but in java, arrays are technically fixed and size cannot be directly changed.
There are ways around it, and the method (not a java method!) that I suggest would be to use a linked list data structure. It sounds intimidating, but there's tons of help on YouTube when it comes to java.
In a nutshell, it's a way of letting you connect "item types" together in whatever order that you want. One item is either in front of an item or behind another item, so it's similar to an array in this sense.
Using a linked list would also allow you to add zeros to the end of your data as well as giving you the freedom of being able to manipulate the content in your data without the concern of size.
I really hope this helped, I'm sorry if it wasn't much. Teaching data structures in a single comment wouldn't be an easy feat, haha!
Best of luck!
You cannot reduce the size of array besides creating new array since its size is final. Try any of java.util.List implementations for your purposes.
You can only do that with an Arraylist
I'm learning Java and surprisingly I found out that Java arrays are not dynamic - even though its cousing languages have dynamic arrays.
So I came out with ideas to kind of imitate a dynamic array in java on my own.
One thought I had was to copy the original array references to a temporary array, then turn the original array to null, re-set its index to a bigger value and then finally re-copy the values from the temporary array.
Example.:
if(numberOfEntries == array.length){
Type[] temp = new Type[numberOfEntries];
for(int x=0; x < numberOfEntries; x++){
temp[x] = array[x];
}
array = null;
array = new Type[numberOfEntries+1];
for(int x=0; x < numberOfEntries; x++){
array[x] = temp[x];
}
I know that this can result in data loss if the process is interrupted, but aside from that, is this a bad idea? What are my options?
Thanks!
Your idea is in the right ballpark. But for a task that you propose you should never implement your own version, unless it is for academic purposes and fun.
What you propose is roughly implemented by the ArrayList class.
This has an internal array and a size 'counter'. The internal array is filled when items are added. When the internal array is full all elements are copied to a bigger array. The internal array is never released to the user of the class (to make sure it's state is always valid).
In your example code, because an array is a pointer, you don't really need the temp array. Just create a new one, copy all elements and save the pointer to it as your array.
You might want to look into thrashing. Changing the size of the array by 1 is likely to be very inefficient. Depending on your use case, you might want to increase the array size by double, and similarly halve the array when it's only a quarter full.
ArrayList is convenient, but once it's full, it takes linear time to add an element. You can achieve something similar to resizing with the ensureCapacity() method. I'd recommend becoming more familiar with Java's Collections framework so you can make the best decisions in future by yourself.
Arrays are not dynamic their size can't change dynamically and right now you aren't changing the same object, you are replacing smaller size object with larger size object
int[5] Arr = new int[5] ; // Create an array of size 5
Arr = new int[10] ;// you assigned the different objects. It is not the same object.
So, we can't change the size of the array dynamically. You can use ArrayList for the same.
But keep try !!!
Please take a look at java.util.ArrayList which is dynamically, it is part of the Collections framework. Making the Array dynamically should be slower and error-prone.
Have you heard about time complexity , do you know how much time complexity you are increasing, Every time you are copying old array element to new array let you have 1 million element in array then think about copying time of element of one array to another array.
One more thing i want to tell you, ArrayList implementation used same logic except new length that you are using .
First off don't call this a duplicate unless you actually find a thread that works for exactly what I'm trying to do, as I've gone through about 50 threads that aren't helping.
~Problem: I don't know how to correctly add an integer to an array like "private int test[] ={}"
~My code:
private int generatedList[] = {};
private int lastInt = 1;
private void startList() {
if (generatedList.length == 30000) {
System.out.println(generatedList);
} else {
generatedList[lastInt+1] = generatedList[lastInt];
lastInt++;
System.out.println(generatedList);
startList();
}
}
~What I'm trying to accomplish: if the length of the list is less than 30,000 add the last int to the array then lastInt++, so after looping say 5 times the list will print like this: 1,2,3,4,5
How do I add the "lastInt" to the generatedList[]?
Arrays in Java are of a fixed size. The one you declared is of size 0, in fact. You won't be able to append to the end of it. Check out the ArrayList class, it will help you.
private ArrayList<Integer> generatedList;
...
generatedList.add(1234);
However, there is a bigger problem with your code. Your recursive implementation is going to be extremely slow, and it doesn't have an initialization for the first value in the array. It would be much better to use a primitive array of fixed size 30,000, and simply loop from 0..30k and fill in the values by index. I leave that as an exercise for you since this is probably related to some homework assignment :)
Arrays are not extendible. This is by design.
I suggest using an ArrayList. It's like an array (can index any property, works almost as fast in terms of runtime complexity) but has the additional properties that you can add and remove items.
The easy way to do this is to change generatedList into ArrayList<Integer>. If you want to preserve an array, you can always create a new array and copy over the contents. (ArrayLists are easier, though.)
Your trying to add new elements to an array of size zero size. Use an arraylist or specify array size first.
So my question starts out as being is it possible to make an array of linked lists in Java?
For some background on why I am asking. I am working on a project in which we are given a file of square matrices. We have to find the determinant of the matrices but they have to be stored in a linked structure. We have previously done this same thing using arrays and so I can reuse a decent bit of my source from that one. Here is what I have though up to do (mostly based on my previous project):
Read each line of the file in as a string
Count the number of matrices and determine where each starts and ends.
* Read each element of each matrix into a multi-linked ListNode (I'll write the class for those)
* Repeat for each matrix
Process the determinant of each.
So the two starred steps are the ones I'm having a tough time figuring out. I want to read in all the matrices at once so I don't lose track of where I am in the file like I would if I read in one matrix, did the determinant, and then went back to the file to get another one. However, I don't know how to store each linked list representation so that I can just iteratively process through each. My only thought is to read each matrix into the linked list structure and store each linked list structure in an array if possible. If not possible, what is a possible alternative?
It is entirely possible to store an array of LinkedLists; arrays can be applied to objects as well as primitive types. However, I would advise creating a Matrix class, because square matrices are not linked lists; they have data in two dimensions, not just one. At the very least, you could use a two-dimensional array of floats to represent a matrix, and store a LinkedList of double[][]s. The closer your representation is to the actual object, the easier it will be for you.
If you are allowed to use the standard LinkedList class what java already has, the here is a possible implementation of reading, and storing your matrices:
int size = 10; //width and height of your matrix.
LinkedList<LinkedList<Integer>> matrix = new LinkedList<LinkedList<Integer>>();
for (int i = 0; i<size; i++)
{
LinkedList<Integer> list = new LinkedList<Integer>();
for (int j = 0; j < size; j++)
{
//read the actual item
}
matrix.add(list);
}
For reading a matrix (probably numbers) i advise to use the class called Scanner. You can create a new Scanner, what will be able to read your file, number by number:
Scanner sc = new Scanner(new File("input.txt"));
And you can read integer values with it, without any conversion like this:
int x = sc.nextInt();
You can make an array of linked lists in Java by declaring LinkedList[], but if you do, your performance will suffer badly. A look at matrix multiplication will illustrate the reason.
If A and B are matrices where the A's column count equals B's row count, then A * B[r, c] is the dot product of row r in A with column c in B. This means we have to extract rows and columns from our matrices.
If we form matrices from lists (of any sort), we can store them row-wise (i.e., where the 0-th list represents row 0), or column-wise (where the 0-th list represents column 0).
Now we run into a problem. In a linked list, the method get(n) starts at the beginning of the list and finds the next member n times -- which makes it run in order n time. A matrix built from linked lists will either extract columns very slowly (if stored row-wise), or extract rows very slowly (if stored column-wise).
I's suggest keeping it simple by using arrays of arrays. You can allocate an n x n array with
int[][] values = new int[n][n];
The value 'n' must be defined, of course.
Hope that this helps.
I'm writing a program in java where I need to slide the elements of the array and it should be performing as less as possible number of operations as it's inside a double loop and I'm working with length of array ranging from upto 10^8.
Example : A = {1,2,3,4,5,6}
Result : A = {2,3,4,5,6,1} for 1st time
A = {3,4,5,6,1,2} for 2nd time and so on..
Please feel free to suggest any other data structure or any modifications to the array!! Thank you guys!! :D
The simplest way to achieve that effect, is to do a "circular array"; that is, instead of moving the contents of the array, you can simply store the index that marks the beginning of the array.
To get the item at index i, you then do:
Type item = arr[(offset + i) % arr.length];
This way, you get the same properties as you have in an array, and you can perform any rotation in O(1).
In order to make this less of a hassle to use, you could make a simple wrapper class, that simply wraps an array, allowing easy rotation through this method. That way, the code could look clean, while you get efficient rotation.
In order to achieve an O(1) complexity, you could...
use a linked list
wrap your array with a class that stores the start position and let you access the array through "virtual" indexes (wrapped.acces(i) => array[(start + i) % array.length]
"double" your array and slice it in an appropriate way (so you don't have to change the surrounding code)
Otherwise, if you want to stick with your data structure, you need to pay O(n), no matter what.
I'd go with (2), because it is faster to both random access and linear access patterns (arrays have better data locality + O(1) random access complexity wrt O(n) of linked lists).
Use Collections.rotate(Arrays.asList(myArray), myDistance).
If you're not married to the idea of using arrays, then you could make use of the Collections.rotate() method.
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 6; i++) {
list.add(i-1, new Integer(i));
}
int j = 0;
while (j < 100) {
Collections.rotate(list, -1);
System.out.print("{");
for (Integer integer : list) {
System.out.print(integer + ", ");
}
System.out.println("}");
}
Why do You have to rotate the table ?
Imagin that table is a circle and after that you can walk like this:
Object object = array[(offset + i) % array.length];
This give you O(1) on any access or rotation step;
You can use a simple List for that. If you do this sliding often, a queue would be the best choice.
The thing is, the array doesn't really change, you just start to read at position x and then continue to read at the start of the array length(array)-x elements. This is the fastest Variant.