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;
}
Related
I have a problem with one of our old exam tasks.
the task is
"the method positions should return a field containing exactly the positions of those elements of the list that have null as content. if there are no such elements than return a field with the length 0"
the code starts with :
public int[] positions() {
int[] result = new int[0];
I keep getting stuck on because of the "new int[0]" when I tried solving the problem without it I managed to get somewhat of a result. but I don't know how to do it with this part.
Just think for a moment what the code is doing here.
int[] result = new int[0];
creates an empty, fixed lenght, primitive array. This array cannot be further expanded.
Your exam task would be translated as (simplifying at a large degree):
public int[] positions(final Object[] objects) {
// Initialize the array with the max possible size, which is the input array size
final int[] positions = new int[objects.lenght];
int j = 0;
for (int i = 0; i < objects.length; i++) {
if (objects[i] == null) {
// Assign the index of the null value to the holder array.
// Increment j, which is the index of the first free position in the holder array
positions[j++] = i;
}
}
// This will return a copy of the "positions" array, truncated at size j
return Array.copyOf(positions, j);
}
I'm trying to write a function that returns an array of unique numbers. The array must be sorted. The function works fine when there are more than just one element, but it doesn't work for when there is just one element in the array. The function should return the only element found in that array, but instead, it is returning an empty array.
Why is this happening?
Array must be sorted for numUnique and removeDuplicates
public static int numUnique (double[] list){
int uniques = 1;
int i = 1;
if(list.length == 0) return 0;
while(i<list.length){
if(list[i] != list[i - 1])
uniques++;
i++;
}
return uniques;
}
public static double[] removeDuplicates(double[] list){
double[] arrayOfUniques = new double[numUnique(list)];
if(list.length == 0) return arrayOfUniques;
int uniques = 1;
int i = 1;
arrayOfUniques[0] = list[0];
while(i < list.length){
if(list[i] != list[i - 1])
arrayOfUniques[uniques++] = list[i];
i++;
}
return arrayOfUniques;
}
Array:
double[] a = {11,11,21,31,41,41,51,61,61,61,71,71,81,91,91,100,100};
Output:
Unique numbers: 9
Array of uniques:
[11.0, 21.0, 31.0, 41.0, 51.0, 61.0, 71.0, 81.0, 91.0]
But it doesn't work when the array just has one element:
double[] a = {11};
Output:
Unique numbers: 0
Array of uniques:[]
Try this.. Convert your array to list & convert list to set
Set not have duplicate values.. simple
List<String> myList= Arrays.asList(a);//convert array to List
Set<Double> uniqueSet = new HashSet<Double>(myList);//you get unique values
If you want to Set to Array try this https://stackoverflow.com/a/5982478/3879847
public List<Double> removeDuplicates (List<Double> list){
// add elements to al, including duplicates
Set<Double> hs = new HashSet<Double>();
hs.addAll(list);
list.clear();
list.addAll(hs);
return list;
}
Actually, it doesn't work for arrrays having only one unique element either (e.g. it returns empty array for new double[]{11.0,11.0, 11.0}). I would recommed a simpler approach using Java 8's stream:
public static double[] removeDuplicates(double[] list){
LinkedHashSet<Double> uniqueElements = Arrays.stream(list)
.boxed()
.collect(Collectors.toCollection(LinkedHashSet::new));
return uniqueElements.stream().mapToDouble(d -> d).toArray();
}
With Java 8 we get Stream, so how to use it in this case :
public static void main (String[] args) {
double[] a = {11,11,21,31,41,41,51,61,61,61,71,71,81,91,91,100,100};
//Way 1 just to print the unique element
DoubleStream.of(removeDuplicate(a)).forEach(System.out::println);
//Way 2 to save the update the array with only the unique element
a = removeDuplicate(a);
}
private static double[] removeDuplicate(double[] a) {
return DoubleStream.of(a).distinct().sorted().toArray();
}
In the main, we're just calling the method, and then read the result and print the values
In the removeDuplicate method : we create Stream of the values, then we keep only the different elements, then we sort them, and them we come back to an array (to follow your wishes)
If you're not sure to HAVE to use array, better use List every time ;)
Let's say I have an array in the length of n, and the only values that can appear in it are 0-9. I want to create a recursive function that returns the number of different values in the array.
For example, for the following array: int[] arr = {0,1,1,2,1,0,1} --> the function will return 3 because the only values appearing in this array are 0, 1 and 2.
The function receives an int array and returns int
something like this:
int numOfValues(int[] arr)
If you are using Java 8, you can do this with a simple one-liner:
private static int numOfValues(int[] arr) {
return (int) Arrays.stream(arr).distinct().count();
}
Arrays.stream(array) returns an IntStream consisting of the elements of the array. Then, distinct() returns an IntStream containing only the distinct elements of this stream. Finally, count() returns the number of elements in this stream.
Note that count() returns a long so we need to cast it to an int in your case.
If you really want a recursive solution, you may consider the following algorithm:
If the input array is of length 1 then the element is distinct so the answer is 1.
Otherwise, let's drop the first element and calculate the number of distinct elements on this new array (by a recursive call). Then, if the first element is contained in this new array, we do not count it again, otherwise we do and we add 1.
This should give you enough insight to implement this in code.
Try like this:
public int myFunc(int[] array) {
Set<Integer> set = new HashSet<Integer>(array.length);
for (int i : array) {
set.add(i);
}
return set.size();
}
i.e, add the elements of array inside Set and then you can return the size of Set.
public int f(int[] array) {
int[] counts = new int[10];
int distinct = 0;
for(int i = 0; i< array.length; i++) counts[array[i]]++;
for(int i = 0; i< counts.length; i++) if(counts[array[i]]!=0) distinct++;
return distinct;
}
You can even change the code to get the occurrences of each value.
You can try following code snippet,
Integer[] arr = {0,1,1,2,1,0,1};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
Output: [0, 1, 2]
As you asked for a recursive implementation, this is one bad way to do that. I say bad because recursion is not the best way to solve this problem. There are other easier way. You usually use recursion when you want to evaluate the next item based on the previously generated items from that function. Like Fibonacci series.
Ofcourse you will have to clone the array before you use this function otherwise your original array would be changed (call it using countDistinct(arr.clone(), 0);)
public static int countDistinct(int[] arr, final int index) {
boolean contains = false;
if (arr == null || index == arr.length) {
return 0;
} else if (arr.length == 1) {
return 1;
} else if (arr[index] != -1) {
contains = true;
for (int i = index + 1; i < arr.length; i++) {
if (arr[index] == arr[i]) {
arr[i] = -1;
}
}
}
return countDistinct(arr, index + 1) + (contains ? 1 : 0);
}
int numOfValues(int[] arr) {
boolean[] c = new boolean[10];
int count = 0;
for(int i =0; i < arr.length; i++) {
if(!c[arr[i]]) {
c[arr[i]] = true;
count++;
}
}
return count;
}
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.
Write a method deleteElement which takes as input an int[] and an int target and deletes all occurrences of target from the array. The method should return the newint[]
. Question to consider:
Why is it that we have to return an array and can't simply change the input parameter array?
public class warm5{
public static void main(String[] args){
int[] array1= {1,2,2,3,4,5,2};
int target1 = 2;
deleteElement(array1,target1);
public static int[] deleteElement(int[] array, int target){
for(int i = 0, i<array.length, i++){
if(array1[i] == target){
}
}
}
}
}
Here is what i wrote, im not sure how to continue it to remove the 2's in the array.
please help!
You can't delete elements from an array, by definition they're of fixed size. What you can do is create a new array, copy all the elements from the old array except the ones that you intend to delete and return the new array. Or, use an ArrayList, which has operations that allow removing elements:
public E remove(int index)
public boolean remove(Object o)
public boolean removeAll(Collection<?> c)
protected void removeRange(int fromIndex, int toIndex)
First, iterate through your array and figure out how many of your target element are present.
Once you know that, you know the size of your new array. As Oscar mentions, you can't "remove" from an array, you just make a new array without the elements you don't want in it.
int targetCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
targetCount++;
}
}
Now you know how many items will be in your new array: array.length-targetCount.
int[] newArray = new int[array.length-targetCount];
int newArrayIdx = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != target) {
newArray[newArrayIdx] = target;
newArrayIdx++;
}
}
Here we iterate through the old array and check each element to see if it's our target. If it's not, we add it to the new array. We have to keep track of our old array's index and our new array's index independently or we may risk trying to assign an index outside of the array bounds.
This is a common interview question. In the solution presented by Oscar you do not know what will be the size of the new array. So the solution does not work or is memory inefficient.
Trick is to loop over the array and at any time when you encounter an element equal to the given element you put that element towards the end of the array and swap it with the element that was there at the end position. By doing this you are collecting all occurrences of given element at the end of the array.
Here is a working logic
deleteElement(int[] given, int elem) {
int endIdx = array.length - 1;
for(int idx = 0; idx <= endIdx; idx++) {
if(given[idx] == elem) {
//swap idx with endIdx
int tmp = given[endIdx];
given[endIdx] = given[idx];
given[idx] = tmp;
endIdx--;
}
}
return Arrays.copyOfRange(given, 0, endIdx);
}