how to return equivalent Arrays - java

A function named equivalentArrays that has two array arguments and returns 1 if the two arrays contain the same values (but not necessarily in the same order), otherwise it returns 0. Note that the arrays do not have to have the same number of elements, they just have to have one of more copies of the same values.
public class Equavalenarray {
public static void main(String[] args) {
int result= equivalentArrays(new int[] {}, new int[] {});
System.out.println(result);
result=equivalentArrays (new int [] {0,2,1,2}, new int [] {0,2,1,2,1});
System.out.println(result);
result=equivalentArrays (new int [] {3,1,2,0}, new int [] {0,2,1,0});
System.out.println(result);
}
public static int equivalentArrays(int[ ] a1, int[ ] a2) {
if(a1==null || a2==null) return 0;
for(int i=0; i<a1.length; i++) {
for(int j=0; j<a2.length; j++) {
if(a1[i]==a2[j] )
{
return 1;
}
}
}
return 0;
}
}

You're almost there with your function. To finish, we'll need to do some workarounds here.
You can check each value within the smaller array and remove the compared value in the bigger array (in case of repeated values).
if in some comparison they're different, it returns 0. If it reach the end of smaller array, they are equals.
Replace your for loops by this snippet:
// converted the values to ArrayList to remove values easily.
// PS: to convert them to ArrayList, the array types must of the Integer
List<Integer> l1 = new ArrayList<Integer>(Arrays.asList(a1.length <= a2.length ? a1 : a2)); // to save in l1 the smaller array
List<Integer> l2 = new ArrayList<Integer>(Arrays.asList(a2.length >= a1.length ? a2 : a1)); // to save in l2 the bigger array
for(int i=0; i<l1.size(); i++) {
if(!l2.contains(l1.get(i)))
return 0;
else
l2.remove(l2.indexOf(l1.get(i)));
}
return 1;
Updated live example here.

public class Equavalenarray {
public static void main(String[] args) {
System.out.println(equivalentArrays(new int[]{0,1,2}, new int[]{2,0,1}));
System.out.println(equivalentArrays(new int[]{0,1,2,1}, new int[]{2,0,1}));
System.out.println(equivalentArrays( new int[]{2,0,1}, new int[]{0,1,2,1}));
System.out.println(equivalentArrays( new int[]{0,5,5,5,1,2,1}, new int[]{5,2,0,1}));
System.out.println(equivalentArrays( new int[]{5,2,0,1}, new int[]{0,5,5,5,1,2,1}));
System.out.println(equivalentArrays( new int[]{0,2,1,2}, new int[]{3,1,2,0}));
System.out.println(equivalentArrays( new int[]{3,1,2,0}, new int[]{0,2,1,2}));
System.out.println(equivalentArrays( new int[]{1,1,1,1,1,1}, new int[]{1,1,1,1,1,2}));
System.out.println(equivalentArrays( new int[]{ }, new int[]{3,1,1,1,1,2}));
System.out.println(equivalentArrays( new int[]{ }, new int[]{ }));
}
public static int equivalentArrays(int[] a1, int[] a2) {
if(a1==null && a2==null) return 0;
boolean found;
for(int i : a1) {
found = false;
for(int j : a2) {
if(i==j) {
found = true;
break;
}
}
if(found==false) {
return 0;
}
}
for(int i : a2) {
found = false;
for(int j : a1) {
if(i==j) {
found = true;
break;
}
}
if(found==false) {
return 0;
}
}
return 1;
}
}
}

Related

We can't add a primitive type value to a ArrayList<Integer> right?? Why is this code working ?? (arrayList should only contain only objects right? )

We can't add a primitive type value to a ArrayList right?? Why is this code working ?? (arrayList should only contain only objects right? )
static List<Integer> compareTriplets(List<Integer> a, List<Integer> b) {
int aPoints = 0;
int bPoints =0;
for(int i=0;i<a.size();i++){
if(a.get(i)>b.get(i)){
aPoints++;
} else {
if(a.get(i)<b.get(i)) {
bPoints++;
} else {
if(a.get(i)==b.get(i)){
aPoints = aPoints + 0;
bPoints = bPoints + 0;
}
}
}
}
ArrayList<Integer>points = new ArrayList<>();
points.add(aPoints);
points.add(bPoints);
return points;
}

How to order a matrix of object

I'm working on an application that read a file Excel with Apache POI. I put the cells value inside a matrix of String object.
[title 1][title 2][title 3]
[mark] [smith] [34]
[simon] [black] [24]
I've been ask to allow to order the matrix according to the selected column.
How can I order a matrix of String object?
Thank you
If you have only few columns you can create some comparators with a meaningful name and sort like below:
public static void main(String[] args) {
String[][] matrix = {{"mark","smith","34"},
{"simon","black","24"},
{"foo","bar","44"}
};
Comparator<String[]> firstNameComparator = new Comparator<String[]>() {
#Override
public int compare(String[] row1, String[] row2) {
return row1[0].compareTo(row2[0]);
}
};
Comparator<String[]> lastNameComparator = new Comparator<String[]>() {
#Override
public int compare(String[] row1, String[] row2) {
return row1[1].compareTo(row2[1]);
}
};
Comparator<String[]> ageComparator = new Comparator<String[]>() {
#Override
public int compare(String[] row1, String[] row2) {
return Integer.compare(Integer.parseInt(row1[2]), Integer.parseInt(row2[2]));
}
};
Arrays.sort(matrix, firstNameComparator);// pass the desired comparator
for(String[] row:matrix){
System.out.println(Arrays.toString(row));
}
}
or create a class that extends Comparator and pass the column index:
public class NewClass5 {
public static void main(String[] args) {
String[][] matrix = {{"mark","smith","34"},
{"simon","black","24"},
{"foo","bar","44"}
};
Arrays.sort(matrix, new CompareByColumn(1));// pass the desired index
for(String[] row:matrix){
System.out.println(Arrays.toString(row));
}
}
static class CompareByColumn implements Comparator {
int columnToSort;
CompareByColumn(int columnToSort) {
this.columnToSort = columnToSort;
}
public int compare(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
return row1[columnToSort].compareTo(row2[columnToSort]);
}
}
}
With java 8 and streams you can write it even more compactly:
String[][] sorted = Arrays.stream(matrix)
.sorted((s1,s2)->s1[1].compareTo(s2[1])) // pass the desired index
.toArray(String[][]::new);
for(String[] row: sorted){
System.out.println(Arrays.toString(row));
}
EDIT
Since you prefer the stream approach, I have only reworked this one. But you can use it for the other approaches as well. You can check before the comparison if the corresponding column contains numbers and make your comparison in a simple if-else either for numbers or strings.
int colIndex = 2;
String[][] sorted = Arrays.stream(matrix).sorted((s1,s2)-> {
if(s1[colIndex].matches("(\\d+(?:\\.\\d+)?)")){
return Double.compare(Double.parseDouble(s1[colIndex]), Double.parseDouble(s2[colIndex]));
}
else{
return s1[2].compareTo(s2[2]);
}})
.toArray(String[][]::new);
for(String[] row: sorted){
System.out.println(Arrays.toString(row));
}
Used this (\d+(?:\.\d+)?) regex to match both integer and floating point numbers.
First of all thank you for this question, it proved to be quite a mental challenge to visualize and implement this solution. I hope the following solution is what you wanted.
I've written a method that will sort the matrix for you. The method takes a String matrix as an argument and returns a new String matrix with each column sorted by alphabetic older. The sorting is done independent of other columns so each column is sorted without external context.
Unfortunately it doesn't exclude the titles from the sorting process so if you need that to happen please let me know and I will do my best to implement that.
public static boolean isNumeric(String str) {
return str.matches("^[0-9]+$");
}
public static String[][] sortMatrix(String[][] matrix)
{
int matrixLength = matrix[0].length;
String[][] sortedMatrix = new String[matrixLength][];
java.util.List<String[]> columns = new java.util.ArrayList<>();
for (int i1 = 0; i1 < matrixLength; i1++)
{
String[] column = new String[matrixLength];
for (int i2 = 0; i2 < matrixLength; i2++) {
column[i2] = matrix[i2][i1];
}
columns.add(column);
}
// First sort the column before proceeding
columns.forEach(column -> Arrays.sort(column, new Comparator<String>()
{
public int compare(String s1, String s2)
{
boolean i1 = isNumeric(s1);
boolean i2 = isNumeric(s2);
if (i1 && i2) {
return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
}
else if (!i1) {
return 1;
}
else return -1;
}
}));
for (int i1 = 0; i1 < columns.size(); i1++)
{
String[] row = new String[matrixLength];
for (int i2 = 0; i2 < matrixLength; i2++) {
row[i2] = columns.get(i2)[i1];
}
sortedMatrix[i1] = row;
}
return sortedMatrix;
}
public static void main(String[] args) throws IOException {
String[][] matrix = new String[3][] ;
matrix[0] = new String[] { "title 1", "title 2", "title 3" };
matrix[1] = new String[] { "simon", "1", "10" };
matrix[2] = new String[] { "mark", "35", "2" };
matrix = sortMatrix(matrix);
for (String[] row : matrix) {
System.out.println(Arrays.toString(row));
}
}
EDIT: Implemented a custom comparator that takes number into account.

Java Sorting Algorithms

I have a class called ThreeSorts.java
The aim is to generate a random arraylist of size n - this works.
Then display the array - this works.
Then I have to prove that these sorting algorithms work, however when I pass the random generated array into one of the sorts like SortA(a);
and then display the array it does not get sorted the output is the same:
Generated ArrayList : (153),(209),(167),(117),(243),(67),(0),(148),(39),(188),
SortA ArrayList : (153),(209),(167),(117),(243),(67),(0),(148),(39),(188),
ThreeSorts.java:
import java.util.*;
public class ThreeSorts
{
private static ArrayList<Integer> CopyArray(ArrayList<Integer> a)
{
ArrayList<Integer> resa = new ArrayList<Integer>(a.size());
for(int i=0;i<a.size();++i) resa.add(a.get(i));
return(resa);
}
public static ArrayList<Integer> SortA(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
int n = a.size(),i;
boolean noswaps = false;
while (noswaps == false)
{
noswaps = true;
for(i=0;i<n-1;++i)
{
if (array.get(i) < array.get(i+1))
{
Integer temp = array.get(i);
array.set(i,array.get(i+1));
array.set(i+1,temp);
noswaps = false;
}
}
}
return(array);
}
public static ArrayList<Integer> SortB(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
Integer[] zero = new Integer[a.size()];
Integer[] one = new Integer[a.size()];
int i,b;
Integer x,p;
//Change from 8 to 32 for whole integers - will run 4 times slower
for(b=0;b<8;++b)
{
int zc = 0;
int oc = 0;
for(i=0;i<array.size();++i)
{
x = array.get(i);
p = 1 << b;
if ((x & p) == 0)
{
zero[zc++] = array.get(i);
}
else
{
one[oc++] = array.get(i);
}
}
for(i=0;i<oc;++i) array.set(i,one[i]);
for(i=0;i<zc;++i) array.set(i+oc,zero[i]);
}
return(array);
}
public static ArrayList<Integer> SortC(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
SortC(array,0,array.size()-1);
return(array);
}
public static void SortC(ArrayList<Integer> array,int first,int last)
{
if (first < last)
{
int pivot = PivotList(array,first,last);
SortC(array,first,pivot-1);
SortC(array,pivot+1,last);
}
}
private static void Swap(ArrayList<Integer> array,int a,int b)
{
Integer temp = array.get(a);
array.set(a,array.get(b));
array.set(b,temp);
}
private static int PivotList(ArrayList<Integer> array,int first,int last)
{
Integer PivotValue = array.get(first);
int PivotPoint = first;
for(int index=first+1;index<=last;++index)
{
if (array.get(index) > PivotValue)
{
PivotPoint = PivotPoint+1;
Swap(array,PivotPoint,index);
}
}
Swap(array,first,PivotPoint);
return(PivotPoint);
}
/////////////My Code////////////////
public static ArrayList<Integer> randomArrayList(int n)
{
ArrayList<Integer> list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(255));
}
return list;
}
private static void showArray(ArrayList<Integer> a) {
for (Iterator<Integer> iter = a.iterator(); iter.hasNext();)
{
Integer x = (Integer)iter.next();
System.out.print(("("+x + ")"));
System.out.print(",");
//System.out.print(GetAge());
//System.out.print(") ");
}
System.out.println();
}
static void test(int n) {
//int n = 13;
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
SortA(a);
showArray(a);
}
}
Test is called in main like this ThreeSorts.test(10);
Why is it not getting sorted even tho the random array is passed and there are no errors?
In your sample code you are only testing SortA which reads:
ArrayList<Integer> array = CopyArray(a);
...
return(array);
so actually it is taking a copy of your array, sorting it, and then returning you the sorted array.
So when you test it, instead of using:
SortA(a);
you need to use
a = SortA(a);
The type of data your function SortA returns is ArrayList<Integer>, which means it returns an array list of integers. You need to change the line SortA(a); to a = SortA(a);: this way a variable will receive the results of this function's work.
You have to set the returned value, otherwise a will not be sorted in test method. Change the way you call SortA(a) to:
static void test(int n) {
//int n = 13;
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
a = SortA(a);
showArray(a);
}
instead of the method SortA(a); just use Collections.sort(a); inside static block. Like
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
Collections.sort(a);
showArray(a);
Thats it.

How to retrieve element from ArrayList containing long array

How to retrieve element from ArrayList<long[]>?
I wrote like this:
ArrayList<long []> dp=new ArrayList<>();
//m is no of rows in Arraylist
for(int i=0;i<m;i++){
dp.add(new long[n]); //n is length of each long array
//so I created array of m row n column
}
Now how to get each element?
every element in that list is an array... so you need to carefully add those by:
using anonymous arrays new long[] { 1L, 2L, 3L }
or especifying the size using the new keyword new long[5]
public static void main(String[] args) throws Exception {
ArrayList<long[]> dp = new ArrayList<>();
// add 3 arrays
for (int i = 0; i < 3; i++) {
dp.add(new long[] { 1L, 2L, 3L });
}
// add a new array of size 5
dp.add(new long[5]); //all are by defaul 0
// get the info from array
for (long[] ls : dp) {
for (long l : ls) {
System.out.println("long:" + l);
}
System.out.println("next element in the list");
}
}
You get the arrays the same way you get anything from an ArrayList. For example, to get the tenth long[] stored in the ArrayList, you'd use the get method:
long[] tenthArray = dp.get(9);
You could also have an ArrayList of objetcs that contain an array of longs inside. But the problem so far with your code is that you are not putting any values in each long array.
public class NewClass {
private static class MyObject {
private long []v;
public MyObject(int n) {
v = new long[n];
}
#Override
public String toString() {
String x = "";
for (int i = 0; i < v.length; i++) {
x += v[i] + " ";
}
return x;
}
}
public static void main(String[] args) {
ArrayList<MyObject> dp = new ArrayList();
int m = 3;
int n = 5;
for (int i = 0; i < m; i++) {
dp.add(new MyObject(n));
}
for (MyObject ls : dp) {
System.out.println(ls);
}
}
}

How to combine if statements in a loop

I have this class and in the printVotes method I had to do the if statement every time to print each votes. Is there any way to combine both the if statements. Could I print all the names of the candidates and the number of votes they got at the same time?
public class TestCandidate {
public static void main(String[] args)
{
Canidate[] canidate = new Canidate[5];
// create canidate
canidate[0] = new Canidate("John Smith", 5000);
canidate[1] = new Canidate("Mary Miller", 4000);
canidate[2] = new Canidate("Michael Duffy", 6000);
canidate[3] = new Canidate("Tim Robinson", 2500);
canidate[4] = new Canidate("Joe Ashtony", 1800);
printVotes(canidate) ;
}
public static void printVotes(Canidate [] List)
{
double max;
int index;
if (List.length != 0)
{
index = 0;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
}
if (List.length != 0)
{
index = 1;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
return;
}
}
}
If you pass in a List<Candidate> candidates; and assuming that each candidate has a List<Integer> Votes:
List<Integer> votes= new ArrayList<Integer>() ;
for(Candidate c:candidates)
{
votes.add(c.GetVote()) ;
}
for(Integer v:votes)
{
System.out.println(v);
}
You could override the Candidate class's toString() method like so:
public String toString() {
return "Candidate Name: " + this.name + "\nVotes: " + this.votes;
}
Then your printVotes method would look something like this:
public static void printVotes(Candidate[] list) {
for(Candidate c : list) {
System.out.println(c);
}
}
As someone else mentioned, avoid using capital letters in variable names especially in cases where words such as List are used. List is a collection type and can be easily confused.

Categories