how to write a method to reverse a 2D array - java

I got this question to solve
Write a method that takes a two-dimensional array of type integer as a parameter and return
the inverse of the array (the rows become the columns and vice versa).
that is what I did through searching, but it shows a bunch of errors
public static class inverse{
public static int[][] arrayInverse(int[][] A){
int[][] B = new int[3][3];
for(int i=0; i<B.length/2;i++){
for (int j=0; j<B[i].length/2;j++) {
int swap = B[i][j];
B[B.length - i - 1] = swap;
}
}
return swap;
}
}
}

First, as mentioned in the comments, the task is to transpose the input array the rows become the columns and vice versa
If the input 2D array is square (the number of the rows is the same as the number of columns), the most efficient way would be to swap the elements below and over the main diagonal: a[i][j] ⇄ a[j][i] without using extra array:
public static int[][] transposeSquare(int[][] arr) {
for (int i = 0, n = arr.length; i < n; i++) {
// select the elements only above the main diagonal
for (int j = i + 1, m = arr[i].length; j < m; j++) {
int tmp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = tmp;
}
}
return arr;
}
However, in general case of a rectangular matrix it may be needed to create a new array/matrix of size M x N instead of N x M, and copy the values from the input in appropriate order (no swap is needed then):
public static int[][] transpose(int[][] arr) {
int[][] result = new int[arr[0].length][arr.length];
for (int i = 0, n = arr.length; i < n; i++) {
for (int j = 0, m = arr[i].length; j < m; j++) {
result[j][i] = arr[i][j];
}
}
return result;
}

You need to replace between columns and rows
public class inverse {
/**
* The entry point of application.
*
* #param args the input arguments
*/
public static void main(String[] args) {
int ints[][] = {{1, 2, 3},
{5, 6, 7},
{9, 10, 11},
{12, 13, 14}
};
print2D(ints);
System.out.println("\n");
print2D(arrayInverse(ints));
}
/**
* Array inverse int [ ] [ ].
*
* #param A the a
* #return the int [ ] [ ]
*/
public static int[][] arrayInverse(int[][] A) {
if (A.length == 0 || A[0].length == 0) {
System.out.println("A.length==0 || A[0].length==0");
return A;
}
int[][] B = new int[A[0].length][A.length];
for (int i = 0; i < B.length; i++) {
for (int j = 0; j < B[i].length; j++) {
B[i][j] = A[j][i];
}
}
return B;
}
/**
* Print 2 d.
*
* #param mat the mat
*/
public static void print2D(int mat[][]) {
// Loop through all rows
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println(" ");
}
}
}
Output:
1 2 3
5 6 7
9 10 11
12 13 14
1 5 9 12
2 6 10 13
3 7 11 14

Here is a general solution. It will transpose any matrix, including a ragged one.
List<int[][]> demo = List.of(
new int[][] { { 1 }, { 2, 3, 4 }, { 5, 6 } },
new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } },
new int[][] { { 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 } });
for (int[][] arr : demo) {
System.out.println("Original");
for (int[] b : arr) {
System.out.println(Arrays.toString(b));
}
System.out.println("Transposed");
for (int[] b : transpose(arr)) {
System.out.println(Arrays.toString(b));
}
System.out.println();
}
prints
Original
[1]
[2, 3, 4]
[5, 6]
Transposed
[1, 2, 5]
[3, 6]
[4]
Original
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transposed
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Original
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
Transposed
[1, 6]
[2, 7]
[3, 8]
[4, 9]
[5, 10]
first, find the resulting number of rows, which is the maximum number of columns in the source matrix.
Then simply iterate thru the matrix, creating the new rows and copying the appropriate values of each column to their new row. Since the rows may be of different lengths, a check is made to ensure the value exists in the current row.
then copy that row of the proper length to the transposed row.
public static int[][] transpose(int[][] nums) {
int maxRows = nums[0].length;
for (int[] ar : nums) {
maxRows = Math.max(maxRows, ar.length);
}
int[][] trans = new int[maxRows][];
for (int r = 0; r < maxRows; r++) {
int[] row = new int[nums.length];
int cc = 0;
for (int c = 0; c < row.length; c++) {
if (r < nums[c].length) {
row[cc++] = nums[c][r];
}
}
trans[r] = Arrays.copyOf(row, cc);
}
return trans;
}
prints

Related

How do I return such an multi-dimensional array?

The method int[][] labelPath(int n, int[][] points) creates a new square array of length n and returns it back. Each line in data0 describes a point in a two-dimensional array. The column 0 is here always for the column index and column 1 for the row index of a point. If the return array reaches each point in data0 returns the value -1. At all other points, the return array contains the value n.
For example: n = 4 and data0 = {{3, 0}, {0, 1}, {2, 2}} should return:
[[4, 4, 4, -1], [-1, 4, 4, 4], [4, 4, -1, 4], [4, 4, 4, 4]]
My code so far:
int[][] labelPath(int n, int[][] points) {
int[][] help = new int[n][n];
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
int row = input[1].length;
int column = input[0].length;
for (int k = 0; k < help.length; k++) {
for (int l = 0; l < help[k].length; l++) {
if (help[i][j] == input[row][column]) {
help[i][j] = -1;
} else {
help[i][j] = n;
}
}
}
}
}
return help;
}
You can do this very simply as follows:
int[][] nPoints = { { 3, 0 }, { 0, 1 }, { 2, 2 } };
int[][] ret = labelPath(4, nPoints);
for (int[] r : ret) {
System.out.println(Arrays.toString(r));
}
Prints
[4, 4, 4, -1]
[-1, 4, 4, 4]
[4, 4, -1, 4]
[4, 4, 4, 4]
public static int[][] labelPath(int n, int[][] nPoints) {
int[][] arr = new int[n][n];
int[] row = new int[n];
for (int i = 0; i < n; i++) {
row[i] = 4;
}
// set each row to an array of n elements.
for (int i = 0; i < n; i++) {
arr[i] = row.clone(); // new instance each time.
}
// make the changes
for (int[] p : nPoints) {
arr[p[1]][p[0]] = -1;
}
return arr;
}
You can use streams to create such an array:
public static int[][] labelPath(int n, int[][] points) {
// create a new empty 2d array filled with zeros
int[][] matrix = new int[n][n];
// set all array elements to 'n'
Arrays.setAll(matrix, row -> {
Arrays.fill(matrix[row], n);
return matrix[row];
});
// iterate over the points array and set the corresponding elements to '-1'
Arrays.stream(points).forEach(row -> matrix[row[1]][row[0]] = -1);
return matrix;
}
// test
public static void main(String[] args) {
int n = 4;
int[][] data0 = {{3, 0}, {0, 1}, {2, 2}};
int[][] matrix = labelPath(n, data0);
// output
Arrays.stream(matrix).map(Arrays::toString).forEach(System.out::println);
}
[4, 4, 4, -1]
[-1, 4, 4, 4]
[4, 4, -1, 4]
[4, 4, 4, 4]
See also: What is the most efficient way to create a 2d string array of initally repetitive data?
Create help[n][n] array of 4's.
int[][] help = new int[n][n];
for(int row = 0; row < help.length; row++){
for(int col = 0; col < 4; col++){
help[row][col] = 4;
}
}
Change the value according to data0 array.
int [][]data0 = {{3, 0}, {0, 1}, {2, 2}} ;
for(int row = 0; row < data0.length; row++){
int ar[] = new int[2];
for(int col = 0, i = 0; col < data0[row].length; col++, i++){
ar[i] = data0[row][col];
}
help[ar[1]][ar[0]] = -1;
}
Print help[][] array.
for(int row = 0; row < help.length; row++){
for(int col = 0; col < help.length; col++){
System.out.print(help[row][col] + " ");
}
System.out.println();
}
Output:
4 4 4 -1
-1 4 4 4
4 4 -1 4
4 4 4 4

Checking if two int arrays have duplicate elements, and extract one of the duplicate elements from them

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;
}

Printing diagonal elements of a 2D array

l'm trying to print the diagonal numbers of a square 2D array but l'm having a hard time with it.It's because of how l create the array isn't it? What l am doing wrong?
int[][] arr1 = { { 1, 2,6}, { 3, 4,5} }; // l'm stuck here
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j <arr1.length; j++) {
System.out.print(arr1[i][j] + " ");
}
System.out.println();
}
for (int k = 0; k < arr1.length; k++) {
System.out.println( arr1[k][k]);
}
l expected to see 1 2 3
4 5 6
7 8 9
And for the actual results? l have being stuck
Your array declaration should look like this:
int[][] arr1 = { { 1, 2, 3}, { 4, 5, 6}, {7, 8, 9} };
assuming you want an ordered 3 x 3 matrix.

Shift all elements in a 2-dimensional array by column index

How to shift 2-dimensional array from index position
int[][] x =
{
{ 1, 2, 3, 4, 5, 6, 7 },
{ 1, 2, 3, 4, 5, 6, 7 },
{ 1, 2, 3, 4, 5, 6, 7 },
{ 1, 2, 3, 4, 5, 6, 7 }
};
index = 3
int[][] y =
{
{ 5, 6, 7, 1, 2, 3, 4 },
{ 5, 6, 7, 1, 2, 3, 4 },
{ 5, 6, 7, 1, 2, 3, 4 },
{ 5, 6, 7, 1, 2, 3, 4 }
};
Any Idea? thanks
This program uses a logic in which we rotate an array by reversing array in parts. First we will reverse array upto index location and then reverse remaining array ( index+1 to last element of array).
After completing above two steps we call again reverse function but this time on whole of the array that gives us the required output.
Below is the code that will help in understanding above logic described.
public class ShiftTwoDArray {
public static void main(String[] args) {
int[][] x = { { 1, 2, 3, 4, 5, 6, 7 },
{ 1, 2, 3, 4, 5, 6, 7 },
{ 1, 2, 3, 4, 5, 6, 7 },
{ 1, 2, 3, 4, 5, 6, 7 }
};
int index = 3;
int i, j;
// System.out.println(x.length);
System.out.println("Before");
for (i = 0; i < x.length; i++) {
for (j = 0; j < x[i].length; j++) {
System.out.print(x[i][j] + " ");
}
System.out.println();
}
rotate(x, index);
System.out.println("\nAfter");
for (i = 0; i < x.length; i++) {
for (j = 0; j < x[i].length; j++) {
System.out.print(x[i][j] + " ");
}
System.out.println();
}
}
/**
* #param x
* #param index
* calls rotateUtil on each row
*/
private static void rotate(int[][] x, int index) {
for (int i = 0; i < x.length; i++) {
rotateUtil(x[i], index);
}
}
/**
* #param x
* #param index
* reverse array in parts and then reverse whole array
*/
private static void rotateUtil(int[] x, int index) {
reverse(x, 0, index);
reverse(x, index + 1, x.length - 1);
reverse(x, 0, x.length - 1);
}
/**
* #param x
* #param start
* #param end
* reverse an array
*/
private static void reverse(int[] x, int start, int end) {
int temp = 0;
while (start < end) {
temp = x[start];
x[start] = x[end];
x[end] = temp;
start++;
end--;
}
}
}
Here's one way to do it, using Guava and Java 8:
Arrays.stream(x)
.map(Ints::asList)
.forEach(list -> Collections.rotate(list, index));
Or the Java 7 version:
for (int[] array : x) {
Collections.rotate(Ints.asList(array), index);
}
This should do what you want:
int[][] x = { { 1, 2, 3, 4, 5, 6, 7 },
{ 1, 2, 3, 4, 5, 6, 7 },
{ 1, 2, 3, 4, 5, 6, 7 },
{ 1, 2, 3, 4, 5, 6, 7 } };
int index = 3;
// Create 2D array of matching size
int[][] y = new int[x.length][x[0].length];
// Loop through each row of x
for (int r = 0; r < x.length; r++) {
// Loop through each column of x[r][]
for (int c = 0; c < x[0].length; c++) {
// Put x's value in y, shifting to the right by index.
// See comment outside of code regarding %
y[r][(c + index) % x[0].length] = x[r][c];
}
}
// Print out y to see if it worked
for (int r = 0; r < y.length; r++) {
for (int c = 0; c < y[0].length; c++) {
System.out.print(y[r][c] + " ");
}
System.out.println();
}
The key here is the % x[0].length in y[r][(c + index) % x[0].length] = x[r][c];. The c + index shifts the column to the right. However, the % x[0].length handles wrapping the columns around to the start of the row, if necessary.

How to get unique items from an array?

I am Java beginner, I found a few topics regarding this theme, but none of them worked for me.
I have an array like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
and I would need to get this output:
1, 2, 3, 4, 5
Every item from that array just once.
But how to get it?
The simpliest solution without writing your own algorithm:
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);
Set interface guarantee uniqueness of values. TreeSet additionally sorts this values.
You can use a Set<Integer> and save lot of time since it holds unique elements. If you aren't allowed to use any class from Java Collections, sort the array and count the unique elements. You can sort the array manually or use Arrays#sort.
I'll post the Set<Integer> code:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for(int x : numbers) {
setUniqueNumbers.add(x);
}
for(Integer x : setUniqueNumbers) {
System.out.println(x);
}
Note that I prefer to use LinkedHashSet as Set implementation since it maintains the order of how the elements were inserted. This means, if your array was {2 , 1 , 2} then the output will be 2, 1 and not 1, 2.
In Java 8:
final int[] expected = { 1, 2, 3, 4, 5 };
final int[] numbers = { 1, 1, 2, 1, 3, 4, 5 };
final int[] distinct = Arrays.stream(numbers)
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinct), expected, distinct);
final int[] unorderedNumbers = { 5, 1, 2, 1, 4, 3, 5 };
final int[] distinctOrdered = Arrays.stream(unorderedNumbers)
.sorted()
.distinct()
.toArray();
Assert.assertArrayEquals(Arrays.toString(distinctOrdered), expected, distinctOrdered);
//Running total of distinct integers found
int distinctIntegers = 0;
for (int j = 0; j < array.length; j++)
{
//Get the next integer to check
int thisInt = array[j];
//Check if we've seen it before (by checking all array indexes below j)
boolean seenThisIntBefore = false;
for (int i = 0; i < j; i++)
{
if (thisInt == array[i])
{
seenThisIntBefore = true;
}
}
//If we have not seen the integer before, increment the running total of distinct integers
if (!seenThisIntBefore)
{
distinctIntegers++;
}
}
Below code will print unique integers have a look:
printUniqueInteger(new int[]{1, 1, 2, 1, 3, 4, 5});
static void printUniqueInteger(int array[]){
HashMap<Integer, String> map = new HashMap();
for(int i = 0; i < array.length; i++){
map.put(array[i], "test");
}
for(Integer key : map.keySet()){
System.out.println(key);
}
}
Simple Hashing will be far efficient and faster than any Java inbuilt function:
public class Main
{
static int HASH[];
public static void main(String[] args)
{
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
HASH=new int[100000];
for(int i=0;i<numbers.length;i++)
{
if(HASH[numbers[i]]==0)
{
System.out.print(numbers[i]+",");
HASH[numbers[i]]=1;
}
}
}
}
Time Complexity: O(N), where N=numbers.length
DEMO
public class Practice {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>(Arrays.asList(3,7,3,-1,2,3,7,2,15,15));
countUnique(list);
}
public static void countUnique(List<Integer> list){
Collections.sort(list);
Set<Integer> uniqueNumbers = new HashSet<Integer>(list);
System.out.println(uniqueNumbers.size());
}
}
In JAVA8, you can simply use
stream()
and
distinct()
to get unique elements.
intArray = Arrays.stream(intArray).distinct().toArray();
There is an easier way to get a distinct list:
Integer[] intArray = {1,2,3,0,0,2,4,0,2,5,2};
List<Integer> intList = Arrays.asList(intArray); //To List
intList = new ArrayList<>(new LinkedHashSet<>(intList)); //Distinct
Collections.sort(intList); //Optional Sort
intArray = intList.toArray(new Integer[0]); //Back to array
Outputs:
1 2 3 0 0 2 4 0 2 5 2 //Array
1 2 3 0 0 2 4 0 2 5 2 //List
1 2 3 0 4 5 //Distinct List
0 1 2 3 4 5 //Distinct Sorted List
0 1 2 3 4 5 //Distinct Sorted Array
See jDoodle Example
You could do it like this:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
ArrayList<Integer> store = new ArrayList<Integer>(); // so the size can vary
for (int n = 0; n < numbers.length; n++){
if (!store.contains(numbers[n])){ // if numbers[n] is not in store, then add it
store.add(numbers[n]);
}
}
numbers = new int[store.size()];
for (int n = 0; n < store.size(); n++){
numbers[n] = store.get(n);
}
Integer and int can be (almost) used interchangeably. This piece of code takes your array "numbers" and changes it so that all duplicate numbers are lost. If you want to sort it, you can add Collections.sort(store); before numbers = new int[store.size()]
I don't know if you've solved your issue yet, but my code would be:
int[] numbers = {1, 1, 2, 1, 3, 4, 5};
int x = numbers.length;
int[] unique = new int[x];
int p = 0;
for(int i = 0; i < x; i++)
{
int temp = numbers[i];
int b = 0;
for(int y = 0; y < x; y++)
{
if(unique[y] != temp)
{
b++;
}
}
if(b == x)
{
unique[p] = temp;
p++;
}
}
for(int a = 0; a < p; a++)
{
System.out.print(unique[a]);
if(a < p-1)
{
System.out.print(", ");
}
}
String s1[]= {"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee"};
int c=0;
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
}
}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
c=0;
}
}
}
}
To find out unique data:
public class Uniquedata
{
public static void main(String[] args)
{
int c=0;
String s1[]={"hello","hi","j2ee","j2ee","sql","jdbc","hello","jdbc","hybernet","j2ee","hello","hello","hybernet"};
for(int i=0;i<s1.length;i++)
{
for(int j=i+1;j<s1.length;j++)
{
if(s1[i]==(s1[j]) )
{
c++;
s1[j]="";
}}
if(c==0)
{
System.out.println(s1[i]);
}
else
{
s1[i]="";
c=0;
}
}
}
}
you can use
Object[] array = new HashSet<>(Arrays.asList(numbers)).toArray();
Here is my piece of code using counting sort (partially)
Output is a sorted array consiting of unique elements
void findUniqueElementsInArray(int arr[]) {
int[] count = new int[256];
int outputArrayLength = 0;
for (int i = 0; i < arr.length; i++) {
if (count[arr[i]] < 1) {
count[arr[i]] = count[arr[i]] + 1;
outputArrayLength++;
}
}
for (int i = 1; i < 256; i++) {
count[i] = count[i] + count[i - 1];
}
int[] sortedArray = new int[outputArrayLength];
for (int i = 0; i < arr.length; i++) {
sortedArray[count[arr[i]] - 1] = arr[i];
}
for (int i = 0; i < sortedArray.length; i++) {
System.out.println(sortedArray[i]);
}
}
Reference - discovered this solution while
trying to solve a problem from HackerEarth
If you are a Java programmer, I recommend you to use this.
It will work.
public class DistinctElementsInArray {
//Print all distinct elements in a given array without any duplication
public static void printDistinct(int arr[], int n) {
// Pick all elements one by one
for (int i = 0; i < n; i++) {
// Check if the picked element is already existed
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
// If not printed earlier, then print it
if (i == j)
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int array[] = { 4, 5, 9, 5, 4, 6, 6, 5, 4, 10, 6, 4, 5, 3, 8, 4, 8, 3 };
// 4 - 5 5 - 4 9 - 1 6 - 3 10 - 1 3 - 2 8 - 2
int arrayLength = array.length;
printDistinct(array, arrayLength);
}
}
public class DistinctArray {
public static void main(String[] args) {
int num[]={1,2,5,4,1,2,3,5};
for(int i =0;i<num.length;i++)
{
boolean isDistinct=false;
for(int j=0;j<i;j++)
{
if(num[j]==num[i])
{
isDistinct=true;
break;
}
}
if(!isDistinct)
{
System.out.print(num[i]+" ");
}
}
}
}

Categories