I am looking to sort the following array based on the values of [][0]
double[][] myArr = new double[mySize][2];
so for example, myArr contents is:
1 5
13 1.55
12 100.6
12.1 .85
I want it to get to:
1 5
12 100.6
12.1 .85
13 1.55
I am looking to do this without having to implement my own sort.
Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.
double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };
java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
public int compare(double[] a, double[] b) {
return Double.compare(a[0], b[0]);
}
});
JAVA-8: Instead of that big comparator, we can use lambda function as following-
Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));
Welcome Java 8:
Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));
The simplest way:
Arrays.sort(myArr, (a, b) -> a[0] - b[0]);
Decreasing/increasing order for an integer array of 2 dimension you can use:
Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0])); //decreasing order
Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]); //increasing order
You need to implement a Comparator<Double[]> like so:
public static void main(String[] args) throws IOException {
final Double[][] doubles = new Double[][]{{5.0, 4.0}, {1.0, 1.0}, {4.0, 6.0}};
final Comparator<Double[]> arrayComparator = new Comparator<Double[]>() {
#Override
public int compare(Double[] o1, Double[] o2) {
return o1[0].compareTo(o2[0]);
}
};
Arrays.sort(doubles, arrayComparator);
for (final Double[] arr : doubles) {
System.out.println(Arrays.toString(arr));
}
}
Output:
[1.0, 1.0]
[4.0, 6.0]
[5.0, 4.0]
Although this is an old thread, here are two examples for solving the problem in Java8.
sorting by the first column ([][0]):
double[][] myArr = new double[mySize][2];
// ...
java.util.Arrays.sort(myArr, java.util.Comparator.comparingDouble(a -> a[0]));
sorting by the first two columns ([][0], [][1]):
double[][] myArr = new double[mySize][2];
// ...
java.util.Arrays.sort(myArr, java.util.Comparator.<double[]>comparingDouble(a -> a[0]).thenComparingDouble(a -> a[1]));
Simplified Java 8
IntelliJ suggests to simplify the top answer to the:
Arrays.sort(queries, Comparator.comparingDouble(a -> a[0]));
It is really simple, there are just some syntax you have to keep in mind.
Arrays.sort(contests, (a, b) ->
Integer.compare(a[0],b[0]));//increasing order ---1
Arrays.sort(contests, (b, a) ->
Integer.compare(b[0],a[0]));//increasing order ---2
Arrays.sort(contests, (a, b) ->
Integer.compare(b[0],a[0]));//decreasing order ---3
Arrays.sort(contests, (b, a) ->
Integer.compare(a[0],b[0]));//decreasing order ---4
If you notice carefully, then it's the change in the order of 'a' and 'b' that affects the result. For line 1, the set is of (a,b) and Integer.compare(a[0],b[0]), so it is increasing order. Now if we change the order of a and b in any one of them, suppose the set of (a,b) and Integer.compare(b[0],a[0]) as in line 3, we get decreasing order.
To sort in descending order you can flip the two parameters
int[][] array= {
{1, 5},
{13, 1},
{12, 100},
{12, 85}
};
Arrays.sort(array, (b, a) -> Integer.compare(a[0], b[0]));
Output:
13, 5
12, 100
12, 85
1, 5
much simpler code:
import java.util.Arrays;
int[][] array = new int[][];
Arrays.sort(array, ( a, b) -> a[1] - b[1]);
import java.util.*;
public class Arrays2
{
public static void main(String[] args)
{
int small, row = 0, col = 0, z;
int[][] array = new int[5][5];
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(100);
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println("\n");
for(int k = 0; k < array.length; k++)
{
for(int p = 0; p < array[k].length; p++)
{
small = array[k][p];
for(int i = k; i < array.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < array[i].length; z++)
{
if(array[i][z] <= small)
{
small = array[i][z];
row = i;
col = z;
}
}
}
array[row][col] = array[k][p];
array[k][p] = small;
System.out.print(array[k][p] + " ");
}
System.out.println();
}
}
}
Good Luck
Java 8 is now very common nowadays.
Arrays.sort(myArr,(double[] a,double[] b)->{
//here multiple lines of code can be placed
return a[0]-b[0];
});
You can use your own sort, it is very simple.
int[][] matrix = {
{2, 1, 3},
{5, 4, 6},
{8, 7, 9}
};
for (int k = 0; k < length; k++) {
for (int i= 0; i < matrix[k].length; i++) {
for (int j = 0; j < matrix[k].length; j++) {
if (matrix[k][i] < matrix[k][j]) {
int temp = matrix[k][i];
matrix[k][i] = matrix[k][j];
matrix[k][j] = temp;
}
}
}
}
System.out.println(Arrays.deepToString(matrix));
OUTPUT
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
There are multiple approaches to do this, Here I'm sharing follow two methods by which it can be achieved.
Using Comparator Arrays.sort : An built-in feature of Java.
Using Merge Sort
Using Comparator Arrays.sort : A built-in feature of Java.
import java.util.Arrays;
class Array2D {
public static void printTwoDimensionArray(int [][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
public static void main(String [] args) {
int [][] arr = {
{1, 2},
{6, 8},
{4, 7},
{9, 11},
{7, 10},
{13, 16},
{5, 9},
{8, 9},
{10, 11}
};
Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));
printTwoDimensionArray(arr);
}
}
Using Merge Sort
import java.util.ArrayList;
class MergeSortComparator {
public static void printSingleDimensionArray(int [] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void printDoublyDimensionArray(int [][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
public static void merge(int[][] arr, int start, int mid, int end, int index) {
int i, j, k;
int n1 = mid - start + 1;
int n2 = end - mid;
int columnLength = arr[0].length;
int [][] leftSubArray = new int [n1][columnLength];
int [][] rightSubArray = new int [n1][columnLength];
// Copy elements to Temp LeftSubArray
for (i = 0; i < n1; i++) {
for (j = 0; j < columnLength; j++) {
leftSubArray[i][j] = arr[start + i][j];
}
}
// Copy elements to Temp RightSubArray
for (i = 0; i < n2; i++) {
for (j = 0; j < columnLength; j++) {
rightSubArray[i][j] = arr[mid + 1 + i][j];
}
}
i = j = k = 0;
while(i < n1 && j < n2) {
if (leftSubArray[i][index] <= rightSubArray[j][index]) {
arr[start + k] = leftSubArray[i];
i++;
} else {
arr[start + k] = rightSubArray[j];
j++;
}
k++;
}
while(i < n1) {
arr[start + k] = leftSubArray[i];
i++;
k++;
}
while(j < n2 && (start + k) < end) {
arr[start + k] = rightSubArray[j];
j++;
k++;
}
}
public static void mergeSort(int[][] arr, int start, int end, int index) {
if (start >= end) {
return;
}
int mid = (start + end) / 2;
mergeSort(arr, start, mid, index);
mergeSort(arr, mid + 1, end, index);
merge(arr, start, mid, end, index);
return;
}
public static void main(String [] args) {
int [][] arr = {
{1, 2},
{6, 8},
{4, 7},
{9, 11},
{7, 10},
{13, 16},
{5, 9},
{8, 9},
{10, 11}
};
int m = arr.length;
int n = arr[0].length;
// Last argument as Index is set to 0,
mergeSort(arr, 0, m-1, 0);
printDoublyDimensionArray(arr);
}
}
To sort 2-D array lexicographically.
First sort each ArrayList in the Array<ArrayList>.
ArrayList<ArrayList<Integer>> allSubset = new ArrayList<>();
for(ArrayList<Integer> row : allSubset) {
Collections.sort(row);
}
Second sort the whole ArrayList<ArrayList> in lexicographically.
allSubset.sort((ArrayList<Integer> o1, ArrayList<Integer> o2) -> {
if(o2.size() == 0) return 1;
int min = Math.min(o1.size(), o2.size());
int i;
for(i = 0; i < min - 1; i++) {
if(o1.get(i).equals(o2.get(i))) continue;
return o1.get(i).compareTo(o2.get(i));
}
return o1.get(i).compareTo(o2.get(i));
});
or
Collections.sort(allSubset, (ArrayList < Integer > first, ArrayList < Integer > second) -> {
for (int i = 0; i < first.size() && i < second.size(); i++) {
if (first.get(i) < second.get(i))
return -1;
if (first.get(i) > second.get(i))
return 1;
}
if (first.size() > second.size())
return 1;
return -1;
});
For a general solution you can use the Column Comparator. The code to use the class would be:
Arrays.sort(myArr, new ColumnComparator(0));
Related
I'm trying to write a method, union(), that will return an int array, and it takes two int array parameters and check if they are sets, or in other words have duplicates between them. I wrote another method, isSet(), it takes one array argument and check if the array is a set. The problem is I want to check if the two arrays in the union method have duplicates between them, if they do, I want to extract one of the duplicates and put it in the unionArray[] int array. This is what I tried so far.
public int[] union(int[] array1, int[] array2){
int count = 0;
if (isSet(array1) && isSet(array2)){
for (int i = 0; i < array1.length; i++){
for (int j = 0; j < array2.length; j++){
if (array1[i] == array2[j]){
System.out.println(array2[j]);
count ++;
}
}
}
}
int[] array3 = new int[array2.length - count];
int[] unionArray = new int[array1.length + array3.length];
int elementOfUnion = 0;
for (int i = 0; i< array1.length; i++){
unionArray[i] = array1[i];
elementOfUnion = i + 1 ;
}
int index = 0;
for (int i = elementOfUnion; i < unionArray.length; i++){
unionArray[i] = array3[index];
index++;
}
return unionArray;
}
public boolean isSet(int[] array){
boolean duplicates = true;
for (int i = 0; i < array.length; i++){
for(int n = i+1; n < array.length; n++){
if (array[i] == array[n])
duplicates = false;
}
}
return duplicates;
}
What I was trying to do is to use all of array1 elements in the unionArray, check if array2 has any duplicates with array1, and then move all the non-duplicate elements from array2 to a new array3, and concatenate array3 to unionArray.
It will be much easier to do it with Collection API or Stream API. However, you have mentioned that you want to do it purely using arrays and without importing any class, it will require a few lengthy (although simple) processing units. The most important theories that drive the logic is how (given below) a union is calculated:
n(A U B) = n(A) + n(B) - n(A ∩ B)
and
n(Only A) = n(A) - n(A ∩ B)
n(Only B) = n(B) - n(A ∩ B)
A high-level summary of this solution is depicted with the following diagram:
Rest of the logic has been very clearly mentioned through comments in the code itself.
public class Main {
public static void main(String[] args) {
// Test
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 3, 4, 5, 6 }));
display(union(new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 1, 2, 3, 4 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 3, 4 }));
display(union(new int[] { 1, 2, 3, 4 }, new int[] { 4, 5 }));
display(union(new int[] { 1, 2, 3, 4, 5, 6 }, new int[] { 7, 8 }));
}
public static int[] union(int[] array1, int[] array2) {
// Create an array of the length equal to that of the smaller of the two array
// parameters
int[] intersection = new int[array1.length <= array2.length ? array1.length : array2.length];
int count = 0;
// Put the duplicate elements into intersection[]
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
intersection[count++] = array1[i];
}
}
}
// Create int []union of the length as per the n(A U B) = n(A) + n(B) - n(A ∩ B)
int[] union = new int[array1.length + array2.length - count];
// Copy array1[] minus intersection[] into union[]
int lastIndex = copySourceOnly(array1, intersection, union, count, 0);
// Copy array2[] minus intersection[] into union[]
lastIndex = copySourceOnly(array2, intersection, union, count, lastIndex);
// Copy intersection[] into union[]
for (int i = 0; i < count; i++) {
union[lastIndex + i] = intersection[i];
}
return union;
}
static int copySourceOnly(int[] source, int[] exclude, int[] target, int count, int startWith) {
int j, lastIndex = startWith;
for (int i = 0; i < source.length; i++) {
// Check if source[i] is present in intersection[]
for (j = 0; j < count; j++) {
if (source[i] == exclude[j]) {
break;
}
}
// If j has reached count, it means `break;` was not executed i.e. source[i] is
// not present in intersection[]
if (j == count) {
target[lastIndex++] = source[i];
}
}
return lastIndex;
}
static void display(int arr[]) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(i < arr.length - 1 ? arr[i] + ", " : arr[i]);
}
System.out.println("]");
}
}
Output:
[1, 2, 5, 6, 3, 4]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 5, 4]
[1, 2, 3, 4, 5, 6, 7, 8]
Using Java's streams could make this quite simpler:
public int[] union(int[] array1, int[] array2) {
return Stream.of(array1, array2).flatMapToInt(Arrays::stream).distinct().toArray();
}
Even with all the restrictions of only using arrays, you can simplify your code a lot. No need to check for sets. Just :
allocate an array to store all elements of the union (i.e., int[] tmp_union ), which at worst will be all elements from both arrays array1 and array2.
iterate over the elements of array1 and compared them against the elements from tmp_union array, add them into the tmp_union array only if they were not yet added to that array.
Repeat 2) for the array2.
During this process keep track of the number of elements added to the tmp_union array so far (i.e., added_so_far). In the end, copy the elements from the tmp_union array into a new array (i.e., unionArray) with space allocated just for the union elements. The code would look something like:
public static int[] union(int[] array1, int[] array2){
int[] tmp_union = new int[array1.length + array2.length];
int added_so_far = add_unique(array1, tmp_union, 0);
added_so_far = add_unique(array2, tmp_union, added_so_far);
return copyArray(tmp_union, added_so_far);
}
private static int[] copyArray(int[] ori, int size) {
int[] dest = new int[size];
for(int i = 0; i < size; i++)
dest[i] = ori[i];
return dest;
}
private static int add_unique(int[] array, int[] union, int added_so_far) {
for (int element : array)
if (!is_present(union, added_so_far, element))
union[added_so_far++] = element;
return added_so_far;
}
private static boolean is_present(int[] union, int added_so_far, int element) {
for (int z = 0; z < added_so_far; z++)
if (element == union[z])
return true;
return false;
}
Suppose my input array is [15,20,12]
The required answer is a 2D array
The Required is output is as followed
[12
20
20 12
15
15 12
15 20
15 20 12
]
Not clear if it's homework or practical case. This is how would I solve it using Guava PowerSet:
public static void main(String[] args) {
Integer input[] = {15,20,12};
List<Integer> rev = Lists.reverse(Arrays.asList(input));
Set<Integer> indices = IntStream.range(0, input.length).boxed().collect(ImmutableSet.toImmutableSet());
Object output[] = Sets.powerSet(indices).stream()
.filter(indexset -> !indexset.isEmpty())
.map(indexset -> indexset.stream().map(i -> rev.get(i)).collect(Collectors.collectingAndThen(toList(), Lists::reverse)))
.map(List::toArray)
.toArray();
System.out.println(Arrays.deepToString(output));
}
Disclaimer:
This is my original work. No part of the solution has been copied from anywhere.
My solution works perfectly for 3 elements. However, this needs to be improved to work for arrays of other sizes. Despite this, I am publishing it so that OP or anyone else can extend this solution to work for an array of any size.
This question is close to the power set except for the fact that a power set can not have duplicate elements. If this exception is removed from this question, there are many solutions available e.g. at 1, 2, 3 etc.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = { 15, 20, 12 };
System.out.println(Arrays.deepToString(subsets(arr)));
}
public static int[][] subsets(int input[]) {
int[][] subarrs = new int[(int) Math.pow(2, input.length) - 1][input.length];
int[] indices = { 0 };
subsetsHelper(input, subarrs, 0, 0, 0, indices);
return subarrs;
}
private static void subsetsHelper(int input[], int[][] subarrs, int index, int i, int j, int[] indices) {
if (i == input.length) {
subarrs[index] = input;
return;
}
int[] subarr = new int[indices.length];
for (int x = 0; x < subarr.length; x++) {
subarr[x] = input[indices[x]];
}
subarrs[index] = subarr;
if (j == input.length - 1) {
subsetsHelper(input, subarrs, index + 1, i + 1, i + 1, new int[] { i + 1 });
} else {
subsetsHelper(input, subarrs, index + 1, i, j + 1, new int[] { i, j + 1 });
}
}
}
Output:
[[15], [15, 20], [15, 12], [20], [20, 12], [12], [15, 20, 12]]
Here you go.
public static void main(String[] args) {
int[] nums= {15, 20, 12};
int[][] subsets = subsets(nums);
for (int i = 1; i < subsets.length; i++) {
System.out.println(Arrays.toString(subsets[i]));
}
}
public static int[][] subsets(int input[]) {
List<List<Integer>> list = new ArrayList<>();
subsetsHelper(list, new ArrayList<>(), input, 0);
return convertListToArray(list);
}
private static void subsetsHelper(List<List<Integer>> list , List<Integer> resultList, int [] nums, int start){
list.add(new ArrayList<>(resultList));
for(int i = start; i < nums.length; i++){
// add element
resultList.add(nums[i]);
// Explore
subsetsHelper(list, resultList, nums, i + 1);
// remove
resultList.remove(resultList.size() - 1);
}
}
private static int[][] convertListToArray(List<List<Integer>> list) {
int[][] array = new int[list.size()][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[list.get(i).size()];
}
for(int i=0; i<list.size(); i++){
for (int j = 0; j < list.get(i).size(); j++) {
array[i][j] = list.get(i).get(j);
}
}
return array;
}
1.As each recursion call will represent subset here, add resultList(see recursion code above) to the list of subsets in each call.
2.Iterate over elements of a set.
3.In each iteration
Add elements to the list
explore(recursion) and make start = i+1 to go through remaining elements of the array.
Remove element from the list
Output:
[15]
[15, 20]
[15, 20, 12]
[15, 12]
[20]
[20, 12]
[12]
public static int[][]returnallsub(int arr[], int si){
if(si==arr.length)
{int[][]ret=new int [1][0];
return ret;
}
int [][]rss =returnallsub(arr,si+1);
int [][]tss=new int[rss.length*2][];
int i=0;
for(;i<rss.length;i++) {
tss[i]=new int [rss[i].length];
}
int k=0;
for(;k<rss.length;k++) {
tss[i]=new int [rss[k].length+1];
i++;
}
int j=0;
for(i=0;i<rss.length;i++) {
for(j=0;j<rss[i].length;j++){
tss[i][j]=rss[i][j];
}
}
for(k=i;k<tss.length;k++) {
tss[k][0]=arr[si];
}
int r=i;
for(i=0;i<rss.length;i++) {
for(j=0;j<rss[i].length;j++){
tss[r][j+1]=rss[i][j];
}
r++;
}
return tss;
}
public static int[][] subsets(int arr[]) {
int start=0;
return returnallsub( arr,0);
}
}
I am trying to sort a list of numbers from smallest to the biggest and print it. I've tried two things:
1.
public class Sorter {
public static void main(String[] args) {
int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
int[] sorted = new int[numbers.length];
for (int a = 0; a < numbers.length; a++) {
int check = 0;
for (int b = 0; b < numbers.length; b++) {
if (numbers[a] < numbers[b]) {
check++;
}
}
sorted[check] = numbers[a];
}
for (int c = numbers.length - 1; c >= 0; c--) {
System.out.print(sorted[c] + ", ");
}
}
}
and this thing works, but won't work with repeated values, so I tried this other thing
public class Sortertwo {
public static void main(String[] args) {
int[] numinput = {3, 2, 1, 4, 7, 3, 17, 5, 2, 2, -2, -4};
int[] numsorted = new int[numinput.length];
int n = 0;
for (; n < numinput.length; ) {
for (int b = 0; b < numinput.length; b++) {
int check = 0;
for (int c = 0; c < numinput.length; c++) {
if (numinput[b] <= numinput[c]) {
check++;
}
}
if (check >= (numinput.length - n) && numinput[b] != 0) {
numsorted[n] = numinput[b];
numinput[b] = 0;
n++;
}
if (n >= (numinput.length)) {
break;
}
}
}
for (int g = 0; g < numinput.length; g++) {
System.out.print(numsorted[g] + ", ");
}
}
}
Where it relies on the thing that once the number from the first array is used (the smallest one is found), it has to be ignored when the program goes through the array next time around.
I tried to assign it like null value, but it doesn't work, so I assigned it to zero and then ignore it, which is a problem, because the list cant have a zero in it.
Is there any like better way to go about it? Thanks.
You can always use:
Arrays.sort(numbers);
If you want to use your first method then change this:
if (numbers[a] < numbers[b])
{
check++;
}
to:
if (numbers[a] <= numbers[b])
{
check++;
}
Unless this is homework, using Arrays.sort as the comments suggest, should be the way to go
import java.util.Arrays;
public class S {
public static void main(String ... args) {
int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
Prints:
[-2, 0, 1, 2, 3, 5, 7, 8, 15]
Need assistance with programming issue.
Must be in Java. Cannot use any libraries (Arraylist, etc.).
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0}
int[] b = {0, 2, 11, 12, 5, 6, 8}
Have to create an object referencing these two arrays in a method that merges them together, removes duplicates, and sorts them.
Here's my sort so far. Having difficulty combining two arrays and removing duplicates though.
int lastPos;
int index;
int temp;
for(lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for(index = 0; index <= lastPos - 1; index++) {
if(a[index] > a[index+1]) {
temp = a[index];
a[index] = a[index+1];
a[index+1] = temp;
}
}
}
a method that merges them together, removes duplicates, and sorts them.
I suggest you break this down into helper methods (and slightly tweak the order of operations). Step 1, merge the two arrays. Something like,
static int[] mergeArrays(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
return c;
}
Step 2, sort the new array (your existing sort algorithm is fine). Like,
static void sortArray(int[] a) {
for (int lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for (int index = 0; index <= lastPos - 1; index++) {
if (a[index] > a[index + 1]) {
int temp = a[index];
a[index] = a[index + 1];
a[index + 1] = temp;
}
}
}
}
Finally, remove duplicates. Step 3a, count unique values. Assume they're unique, and decrement by counting adjacent (and equal) values. Like,
static int countUniqueValues(int[] c) {
int unique = c.length;
for (int i = 0; i < c.length; i++) {
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
unique--;
}
}
return unique;
}
Then step 3b, take the unique count and build your result with the previous methods. Like,
public static int[] mergeDedupSort(int[] a, int[] b) {
int[] c = mergeArrays(a, b);
sortArray(c);
int unique = countUniqueValues(c);
int[] d = new int[unique];
int p = 0;
for (int i = 0; i < c.length; i++) {
d[p++] = c[i];
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
}
}
return d;
}
Then you can test it with your arrays like
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 8, 5, 7, 9, 6, 0 };
int[] b = { 0, 2, 11, 12, 5, 6, 8 };
int[] c = mergeDedupSort(a, b);
System.out.println(Arrays.toString(c));
}
And I get
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12]
Merge Two Arrays without Duplicates and Sort it (No libraries used).
Using an object.
public class MergeRemoveDupSort {
public int[] mergeRemoveDupSortIt(int[] a, int[] b) {
int [] c = mergeIt(a,b);
int [] d = removeIt(c);
int [] e = sortIt(d);
return e;
}
private int[] mergeIt(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int k=0;
for (int n : a) c[k++]=n;
for (int n : b) c[k++]=n;
return c;
}
private int[] removeIt(int[] c) {
int len=c.length;
for (int i=0;i<len-1;i++)
for (int j=i+1;j<len;j++)
if (c[i] == c[j]) {
for (int k=j;k<len-1;k++)
c[k]=c[k+1];
--len;
}
int [] r = new int[len];
for (int i=0;i<r.length;i++)
r[i]=c[i];
return r;
}
private int[] sortIt(int[] a) {
for(int index=0; index<a.length-1; index++)
for(int i=index+1; i<a.length; i++)
if(a[index] > a[i]){
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
return a;
}
public void printIt(int[] a) {
System.out.print("[");
for (int i=0;i<a.length;i++){
System.out.print(a[i]);
if (i!=a.length-1) System.out.print(",");
else System.out.print("]");
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
MergeRemoveDupSort array = new MergeRemoveDupSort();
int [] r = array.mergeRemoveDupSortIt(a, b);
array.printIt(r);
}
}
You should use IntStream like this.
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] merged = IntStream
.concat(IntStream.of(a), IntStream.of(b))
.distinct()
.sorted()
.toArray();
System.out.println(Arrays.toString(merged));
Assuming that array a and array b are sorted, the following code will merge them into a third array merged_array without duplicates :
public static int[] get_merged_array(int[] a, int[] b, int a_size, int b_size)
{
int[] merged_array = new int[a_size + b_size];
int i = 0 , j = 0, x = -1;
for(; i < a_size && j < b_size;)
{
if(a[i] <= b[j])
{
merged_array[++x] = a[i];
++i;
}
else
{
if(merged_array[x] != b[j])
{
merged_array[++x] = b[j]; // avoid duplicates
}
++j;
}
}
--i; --j;
while(++i < a_size)
{
merged_array[++x] = a[i];
}
while(++j < b_size)
{
merged_array[++x] = b[j];
}
return merged_array;
}
Hope this may help, all the best :)
try{
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] c = new int[a.length+b.length];
int[] final = new int[a.length+b.length];
int i = 0;
for(int j : final){
final[i++] = -1;
}
i = 0;
for(int j : a){
c[i++] = j;
}
for(int j : b){
c[i++] = j;
}
boolean check = false;
for(int j = 0,k = 0; j < c.length; j++){
for(int l : fin){
if( l == c[j] )
check = true;
}
if(!check){
final[k++] = c[j];
} else check = false;
}
} catch(Exception ex){
ex.printStackTrace();
}
I prefer you to use Hashset for this cause it never allow duplicates
and there is another method in java 8 for arraylist to remove duplicates
after copying all elements to c follow this code
List<Integer> d = array.asList(c);
List<Integer> final = d.Stream().distinct().collect(Collectors.toList());
final.forEach(System.out::println());
This code is lot much better than previous one and you can again transform final to array like this
int array[] = new int[final.size()];
for(int j =0;j<final.size();j++){
array[j] = final.get(j);
}
Hope my work will be helpful .
Let me restate your question.
You want a program that takes two arbitrary arrays, merges them removing any duplicates, and sorts the result.
First of all, if you have access to any data structure, there are much better ways of doing this. Ideally, you would use something like a TreeSet.
However, assuming all you have access to is arrays, your options are much more limited. I'm going to go ahead and assume that each of the two arrays initially has no duplicates.
Let's assume the first array is of length m and the second array is of length n.
int[] array1; // length m
int[] array2; // length n
First, let's sort both arrays.
Arrays.sort(array1);
Arrays.sort(array2);
This assumes you have access to the Arrays class which is part of the standard Java Collections Framework. If not, any reasonable merge implementation (like MergeSort) will do the trick.
The sorts will take O(n log n + m log m) with most good sort implementations.
Next, let's merge the two sorted arrays. First, we need to allocate a new array big enough to hold all the elements.
int[] array3 = new int[size];
Now, we will need to insert the elements of array1 and array2 in order, taking care not to insert any duplicates.
int index=0, next=0, i=0, j=0;
int last = Integer.MAX_INT;
while(i < m || j < n) {
if(i == m)
next = array2[j++];
else if(j == n)
next = array1[i++];
else if(array1[i] <= array2[j])
next = array1[i++];
else
next = array2[j++];
if(last == next)
continue;
array3[index++] = next;
}
Now, you have your array. Just one problem - it could have invalid elements at the end. One last copy should take care of it...
int[] result = Arrays.copyOf(array3, index + 1);
The inserts and the final copy will take O(n + m), so the overall efficiency of the algorithm should be O(n log n + m log n).
I tried:
public static void main(String[] args) {
int array [] = {2, 5, 1, 4, 7, 9, 0};
for (int i = 0; i < array.length-2; i++) {
swapNum(array[i], array[i+2]);
System.out.println(Arrays.toString(array));
}
System.out.println(Arrays.toString(array));
}
public static void swapNum(int a, int b){
int tmp = a;
a = b;
b = tmp;
}
But found that it is not swapping values. Then I took help from here
https://codereview.stackexchange.com/questions/86016/left-shifting-an-array-of-ints
public void anotherTry() {
int nums [] = {4, 5, 2, 1, 6, 8};
for (int i = 0, start = 0; i < nums.length; i++) {
if (i == 0)
start = nums[i];
if (i == (nums.length - 1)) {
nums[i] = start;
break;
}
nums[i+2] = nums[i];
System.out.println(Arrays.toString(nums));
}
System.out.println(Arrays.toString(nums));
}
Its gives array out of bound of exception.
Where I am wrong?
Role of start variable. If start always will be equal to nums[i]?
You can't swap values like that in Java. However, since you are using an array and want to swap values within the array, you can rewrite your swap method to work with indexes:
public static void main(String[] args) {
int array [] = {2, 5, 1, 4, 7, 9, 0};
for (int i = 0; i < array.length-2; i++) {
swapNum(array, i, i+2);
System.out.println(Arrays.toString(array));
}
System.out.println(Arrays.toString(array));
}
public static void swapNum(int[] values, int i, int j){
int tmp = values[i];
values[i] = values[j];
values[j] = tmp;
}