Answer the question
In order to leave comments, you need to log in
How to dynamically resize an array?
given an array of dimension n. Construct an array without repetitions containing the elements of a given array.
How to declare the resulting array?
public static void main(String ... args){
int a[] ={0,1,1,2,3,3,0,4,5,6};
//
int b[]=new int[a.length];
b[0]=a[0];
int indexb=1;
boolean flag;
for(int i=1;i<a.length;i++){
flag=false;
for(int j=0;j<b.length;j++){
if(b[j]==a[i]){
flag=true;
}
}
if(!flag){b[indexb]=a[i];
indexb++;
}
}
for (int k = 0; k < b.length; k++) {
System.out.print(b[k] + " ");
}
Answer the question
In order to leave comments, you need to log in
java.util.Set - set (each element occurs at most once)
hammer all array elements into a set, repeating elements fall back on their own.
An almost correct solution, only in the inner loop:
1. No need to go through all the elements of B, since some of them will be empty. (should not be j
Well, you can also troll a little on the labs, why not?
For example, bring the following decision with the words "I am an artist, this is how I see it."
Though recursion, probably, pass later.
import java.util.Arrays;
public class Main {
static int[] uniques(final int[] arr) {
return filter(arr, new int[0]);
}
static int[] filter(final int[] arr, final int... uniques) {
if (arr.length == 0) {
return uniques;
}
final int newElement = arr[0];
boolean isDuplicated = false;
for (int uniqElement : uniques) {
if (newElement == uniqElement) {
isDuplicated = true;
break;
}
}
if (isDuplicated) {
return filter(Arrays.copyOfRange(arr, 1, arr.length), uniques);
} else {
final int[] newUniques = Arrays.copyOf(uniques, uniques.length + 1);
newUniques[uniques.length] = newElement;
return filter(Arrays.copyOfRange(arr, 1, arr.length), newUniques);
}
}
public static void main(String[] args) {
int a[] = {0, 1, 1, 2, 3, 3, 0, 4, 5, 6};
for (int i : uniques(a)) {
System.out.println(i);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question