I do not want to change the array inside the method [duplicate] - java

This question already has an answer here:
Java Arrays.sort(test) sorts two arrays
(1 answer)
Closed 9 years ago.
when I put an array inside my method public int[] insertionSort(final int array[])
I do not change the array[]
public int[] insertionSort(final int array[]) {
int[] array_for_sorting = array;
final int[]TempArray = array;
int n = array_for_sorting.length;
// printNumbers(TempArray);
for (int j = 1; j < n; j++) {
int key = array_for_sorting[j];
int i = j-1;
while ( (i > -1) && ( array_for_sorting [i] > key ) ) {
array_for_sorting [i+1] = array_for_sorting [i];
i--;
}
array_for_sorting[i+1] = key;
// printNumbers(array_for_sortying);
}
//array = TempArray;
printNumbers(TempArray);// for printing
return array_for_sorting;
}
also, why my TempArray change after the for loop ?

All your array references (array, array_for_sorting, TempArray) are referring the same array object. So, when you modified the array content, it will visible from all its reference.
What does final means here, You can't reassign another array to a final array reference. But, its content can be altered
If you need to copy a arrays, use Arrays.copyOf(array, array.length);

Actually the TempArray and array are two referances to same location in memory, so you are modifying the TempArray when you modify the array
So you need to create a new array like, u can use :
System.arraycopy(array, 0, TempArray, 0, array.length );
Then modify the Array and another array will not change.

Related

How to fill a copy of an array with zeros without using array functions?

My sample Mid-term asks me to write a method that takes an array called origArr and returns a copy of it. The returned copy should have a specified length called len and if len is greater than origArr's length than the extra slots are filled with zero. The question also states that no functions of the array class can be used. When I print the new array it doesn't add the zero's to the extra slots. So far my code is:
public static void main(String[] args) {
int[] origArr = {1,2,3,4,5,6};
int len = 0;
int[] array = myCopyOf(origArr, len);
for (int i=0; i < array.length; i++) {
System.out.println(array[i]);
}
}
public static int[] myCopyOf(int[] origArr, int len) {
//declare new array//
int[] myCopyOf = new int[origArr.length];
//declare length should be equal to origArr' length//
len = origArr.length;
if (len > origArr.length) {
for (int i = 0; i < origArr.length; i++) {
myCopyOf[i] = origArr[i] + 0;
}
}
return myCopyOf;
}
In Java, primitives - int is a primitive - always have a value; if they aren't initialized explicitly with a value they are assigned their default value, which for numeric primitives is zero.
This means that when you create a int[], all elements are 0, so you don't have to do anything special - the extra elements are already 0.
There are 2 bugs in your code.
First bug:
int[] myCopyOf = new int[origArr.length];
Should be:
int[] myCopyOf = new int[len];
Second bug: you should delete the if and correct the loop termination condition:
for (int i = 0; i < origArr.length && i < len; i++) {
myCopyOf[i] = origArr[i];
}
which handles when len is less or greater than the array's length.
Also, no need for the + 0.
int[] myCopyOf = new int[origArr.length];
Here you create a new array with the same length as the original array. But your requirements say that the length must be what is specified by the len parameter, so use that:
int[] myCopyOf = new int[len];
This will automatically fill in zeros when len is greater than origArray.length. You will need to be careful when origArray is shorter, though. You can make a small modification to the for loop to fix that. I will leave the details as an exercise.

Write a function called arraySum that returns the sum (as an int) of all the values in a two-dimensional array of int values (Java)

I am trying to sum all the int values of a 2D array. I named it array. my function is then called arraySum. If arraySum is null, I return 0. Otherwise, it goes through two for-loops, summing the values of these arrays.
int i = 0;
int j = 0;
static int sum = 0;
int[][] array = new int[i][j];
static int arraySum(int[][] array) {
if (array == null) { // test if the incoming param is null
return 0;
} else {
for (int i = 0; i < array.length; i++) { // length of the outer array
for (int j = 0; j < array[i].length; j++) { // length of the inner array
sum += array[i][j];
}
}
return sum; // moved out of the loop
}
}
my error message:
java.lang.AssertionError: Incorrect result: expected [-217085] but found [-308126]
Fixing the method signature is the first step.
Then you'll need to fix the null check.
Then your loops need to check the size of the inner and outer arrays.
Move the return statement.
Here's the fixed code:
static int arraySum(int[][] array) { // fix the signature
if (array == null) { // test if the incoming param is null
return 0;
} else {
int sum = 0; // you need this in the scope of the method - it will be returned at the end
for (int i = 0; i < array.length; i++) { // length of the outer array
for (int j = 0; j < array[i].length; j++) { // length of the inner array
sum += array[i][j];
}
}
return sum; // moved out of the loop
}
}
Edit: I've concentrated on just the method now - how you call it is up to you. Please note that the method will not affect any externally defined sum variable. It will return the sum and it's up to the caller to store that value somewhere.
Avoid using primitive for statement. See following:
static int arraySum(int[][] array) {
int sum = 0;
if (array == null) return 0;
for(int[] row: array){
for(int col : row) {
sum += col;
}
}
return sum;
}
Streams can do this too:
//Create 2D array
int[][] array = {{1,2,3},{4,5},{6}};
//Sum all elements of array
int sum = Stream.of(array).flatMapToInt(IntStream::of).sum();
System.out.println(sum);
Picking apart the summing code:
Stream.of(array)
Turns the 2D array of type int[][] into a Stream<int[]>. From here, we need to go one level deeper to process each child array in the 2D array as the stream only streams the first dimension.
So at this point we'll have a stream that contains:
an int[] array containing {1,2,3}
an int[] array containing {4,5}
an int[] array containing {6}
.flatMapToInt(IntStream::of)
So far we have a Stream of int[], still two-dimensional. Flat map flattens the structure into a single stream of ints.
flatMapToInt() expands each int[] element of the stream into one or more int values. IntStream.of() takes an array int[] and turns it into an int stream. Combining these two gives a single stream of int values.
After the flattening, we'll have an int stream of:
{1,2,3,4,5,6}
.sum()
Now we have an IntStream with all elements expanded out from the original 2D array, this simply gets the sum of all the values.
Now the disclaimer - if you are new to Java and learning about arrays, this might be a little too advanced. I'd recommend learning about nesting for-loops and iterating over arrays. But it's also useful to know when an API can do a lot of the work for you.

How should I concatenate arrays [duplicate]

This question already has answers here:
How can I concatenate two arrays in Java?
(66 answers)
Closed 7 years ago.
I am using a function that returns some integers
int[] return;
This function is inside a loop like this
public static int[] toEOBArray(double[] tempVal)
{
int[] out;
for (int i = 0; i < 10; i++)
{
out = fixArray(tempVal[i]);
}
return out;
}
What I want is as new arrays come from fixArray to add them to the previous results, so in the end I have a big array that will contain all the small arrays resulting from fixArray
What is the most efficient way of doing this?
My main problem is not knowing how to initialize the array that is to hold all the values.
If you want to work only with arrays, you must first find the length of the concatenated array. Then you can use System.arraycopy to copy the small arrays to the output array.
public static int[] toEOBArray(double[] in)
{
int[][] arrays = new int[10][];
int len = 0;
for (int i = 0; i < 10; i++)
{
arrays[i] = fixArray(tempVal[i]);
len += arrays[i].length;
}
int[] out = new int[len];
int offset = 0;
for (int i = 0; i < 10; i++)
{
System.arraycopy(arrays[i],0,out,offset,arrays[i].length);
offset += arrays[i].length;
}
return out;
}
If you insist on working with native arrays (as opposed to a Collection like ArrayList) then you will want to use ArrayUtils class from Apache Common Lang that adds many Collection-like features to Java native arrays, one of which is addAll:
ArrayUtils.addAll(fixArray, tempVal);

How to add or remove a value on an array?

1st quesiton :
How do i remove from an array ? Basically the parameter will specify which index will be removed.
I will have to update this in a new array and return it.
int[] removeFromArray(int[] array, int index) {
int[] newArray = array
}
2nd quesiton:
I guess same concept, but i have to add to an array.
Conditions:
I cant use ArrayUtils , etc.
I'm guessing this can be done using for loops ?
Cheers
if you really want to remove element from array , you can do following
static int[] removeFromArray(int[] s, int idx)
{
int[] dest = new int[s.length-1];
System.arraycopy(s, 0, dest, 0, idx);
System.arraycopy(s, idx+1, dest, idx, s.length-idx-1);
return dest;
}
I would suggest consider other options like 'ArrayList' or suggestions made by Thihara.
You can't add or remove from an array.
You can however set the elements in the array to null, or set a separate value.
If you want to remove an array you will have to create a new array and assign the elements you don't want to remove manually.
Alternatively you can shift the elements downward so only the last index of an element will be removed.
Rather than do all of this manually please look into java's ArrayList(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html) and Collection API(http://docs.oracle.com/javase/tutorial/collections/
)
You can not remove anything from an array as they are immutable. Although, you can create a new array that does not contain the elements you want
public int[] removeFromArray(int[] array,int index){
int[] newArray = new int[array.length - 1];
for(int i = 0;i<array.length;i++){
if(i == index){
continue;
}else{
if(i>index && i!= (index+1)){
newArray[i-1] = array[i];
}else{
newArray[i] = array[i];
}
}
}
return newArray;
}
Please clarify what you mean by add an array. Are you trying to say that add the values of all the elements of two arrays and display them ?
Assuming you want to add int[] arrays together, you can do that as follows:
public int[] addTwoArrays(int[] array1,int[] array2){
if(array1.length != array2.length){
System.out.println("Can not add arrays of different lengths.");
return null;
}else{
int[] additionArray = new int[array1.length]; // or array[2].length cause they are the same length;
for(int i = 0;i<array1.length;i++){
additionArray[i] = array1[i] + array2[i];
}
}
return additionArray;
}

Add element into array java

Here's what the layout is
index num
0 [10]
1 [20]
2 [30]
(Add 35 here)
3 [40] Move elements down
4 [50]
5 [60]
6 [70]
then my method is this
public static void method(int[] num, int index, int addnum)
{
}
How can i add 35 in there?
Tried this:
public static void method(int[] num, int index, int addnum)
{
int index = 10;
for(int k = num.length k>3; k++)
{
Num[k]=num[k++]
}
Num[3] = 35;
As this is something you should accomplish yourself, I will only provide the method to implement it, not the code:
If you would set the number at position index, you would overwrite the value that was there previously. So what you need to do is move every element one position towards the end of the array starting from index: num[x] becomes num[x+1], etc.
You will find out that you need to do this in reverse order, otherwise you will fill your array with the value in num[index].
During this process you will need to decide what to do with the last entry of the array (num[num.length - 1]):
You could just overwrite it, discarding the value
You could return it from your function
You could throw an exception if it is non-zero
You could create a new array that is 1 entry larger than the current array instead to keep all values
etc.
After this, you have duplicated num[index]: the value is present in num[index+1], too, as you have moved it away.
Now it is possible to write the new value at the desired position without overriding an existing value.
EDIT
You have several errors in your code:
You increment k, you need to decrement it (k--, not k++)
You modify k again in your loop body: it is updated twice in each cycle
If you start with k = num.length, you will try to write at num[num.length + 1], which is not possible
Very crudely, you want to do something like this:
public static void(int[] num, int index, int addnum)
{
// initialize new array with size of current array plus room for new element
int[] newArray = new int[num.length + 1];
// loop until we reach point of insertion of new element
// copy the value from the same position in old array over to
// same position in new array
for(int i = 0; i < index; i++)
{
newArray[i] = num[i];
}
i = i + 1; // move to position to insert new value
newArray[i] = addnum; // insert the value
// loop until you reach the length of the old array
while(i < num.length)
{
newArray[i] = num[i-1];
}
// finally copy last value over
newArray[i + 1] = num[i];
}
You need to
allocate a new array with room for one new element.
int[] newArray = new int[oldArray.length + 1];
Copy over all elements and leave room for the one to insert.
for (int i = 0; i < newArray.length - 1; i++)
newArray[i < insertIndex ? i : i + 1] = oldArray[i];
Insert 35 in the empty spot.
newArray[insertIndex] = numberToInsert;
Note that it's not possible to do in a method like this:
public static void method(int[] num, int index, int addnum)
^^^^
since you can't change the length of num.
You need to allocate a new array, which means that need to return the new array:
public static int[] method(int[] num, int index, int addnum)
^^^^^
and then call the method like this:
myArr = method(myArr, 3, 35);
Since this very closely resembles homework what you need to realize is that you cannot dynamically increase the size of an array. So in your function:
public static void(int[] num, int index, int addnum)
{
int[] temp = new int[num.length *2];
for(int i = 0; i < index; i++)
copy num[i] into temp[i]
insert addnum into temp[index]
fill temp with remaining num values
}
That pseudocode above should get you started.
What you're looking for is an insertion sort.
It's classwork, so it's up to you to figure out the proper code.
Well, you can't unless there is "extra space" in your array, and then you can shift all elements [starting from index] one element to the right, and add 35 [num] to the relevant place.
[what actually happen is that the last element is discarded out].
However - a better solution will probably be to use an ArrayList, and use the method myArrayList.add(index,element)
How about this?
public class test {
public static void main(String[] arg) throws IOException
{
int[] myarray={1,2,3,5,6};//4 is missing we are going to add 4
int[] temp_myarray=myarray;//take a temp array
myarray=addElement(myarray,0);//increase length of myarray and add any value(I take 0) to the end
for(int i=0;i<myarray.length;i++)
{ if(i==3) //becaues I want to add the value 4 in 4th place
myarray[i]=4;
else if(i>3)
myarray[i]=temp_myarray[i-1];
else
myarray[i]=temp_myarray[i];
}
for(int i=0;i<myarray.length;i++)
System.out.print(myarray[i]);//Print new array
}
static int[] addElement(int[] arr, int elem) {
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = elem;
return arr;
}
}

Categories

Resources