Java Client Server with RMI - java

Write a Java client-server program applying RMI. The client program generate two arrays of type class Integer. The client calls method that is on the server side in a remote object. The server put these two arrays into one array, sort the array and returns the sorted array to the client. The client displays the sorted array on the console. Use the following interface. Do not change it.
import java.util.ArrayList;
import java.rmi.*;
public interface MergeInterface extends Remote {
public ArrayList mergeAndSort(ArrayList a, ArrayList b) throws RemoteException;
}
The following sequential program is putting two arrays together, sorting array and display:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
Random r = new Random();
int m = r.nextInt(900) + 100;
for (int i = 0; i < m; i++) {
a.add(r.nextInt(500) + 10);
}
int n = r.nextInt(900) + 100;
for (int i = 0; i < n; i++) {
b.add(r.nextInt(500) + 10);
}
a.addAll(b);
Collections.sort(a);
for (Integer i : a) {
System.out.println(i);
}
}
}

This is how to implement an interface on a class. I would also consider creating a generic class for this or strongly typing the ArrayLists, but that requires a change to the interface.
public interface MergeInterface extends Remote {
public ArrayList mergeAndSort(ArrayList a, ArrayList b) throws RemoteException;
}
public static void main(String[] args) {
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
Random r = new Random();
int m = r.nextInt(900) + 100;
for (int i = 0; i < m; i++) {
a.add(r.nextInt(500) + 10);
}
int n = r.nextInt(900) + 100;
for (int i = 0; i < n; i++) {
b.add(r.nextInt(500) + 10);
}
for (Integer i : (ArrayList<Integer>)new MergeImpl().mergeAndSort(a, b)) {
System.out.println(i);
}
}
public static class MergeImpl implements MergeInterface {
#Override
public ArrayList mergeAndSort(ArrayList a,
ArrayList b) {
ArrayList merged = new ArrayList();
merged.addAll(a);
merged.addAll(b);
Collections.sort(merged);
return merged;
}
}

Related

Adding multiple "randomly generated" objects to ArrayList results in adding the same object multiple times

I have a class Ttp which has a ArrayList<City>loaded from file. In constructor of Ttp I randomly shuffle a list read from file and assign it to the object.
public class Ttp {
private ArrayList<City> cities;
public Ttp() {
cities = Utils.shuffleArray(Loader.getCities());
}
}
This way I get 10 objects with nicely shuffled arrays:
public static void main(String args[]) {
Loader.readFile("easy_0.ttp");
for(int i=0; i<10; i++){
System.out.println(new Ttp());
}
}
But in this scenario, when I try to create ArrayList<Ttp> I get a collection full of the same objects (instances of Ttp with the same arrays of cities)
public static void main(String args[]) {
Loader.readFile("easy_0.ttp");
ArrayList<Ttp> arrayList = new ArrayList<>();
for(int i=0; i<10; i++){
arrayList.add(new Ttp());
}
arrayList.forEach(System.out::println);
}
Shuffle function:
public static <T> ArrayList<T> shuffleArray(ArrayList<T> arrayList) {
if (arrayList != null && arrayList.size() > 0) {
int numberOfRolls = Random.getGenerator().nextInt((arrayList.size() - arrayList.size() / 3) + 1) + arrayList.size() / 3;
int indexA;
int indexB;
T objectA;
for (int i = 0; i < numberOfRolls; i++) {
indexA = Random.getGenerator().nextInt(arrayList.size());
indexB = Random.getGenerator().nextInt(arrayList.size());
objectA = arrayList.get(indexA);
arrayList.set(indexA, arrayList.get(indexB));
arrayList.set(indexB, objectA);
}
}
return arrayList;
}
To pick random indexes in shuffle function I am using java.util.Random:
public class Random {
private static final java.util.Random generator = new java.util.Random();
public static java.util.Random getGenerator() {
return generator;
}
}
If Loader.getCities() returns the same list every time that means shuffleArray() is shuffling the same list over and over and every Ttp.cities has a reference to the same unitary list.
The fix is to make a copy somewhere. It could be in getCities(), it could be in shuffleArray(), or it could be in the Ttp constructor:
cities = Utils.shuffleArray(new ArrayList<>(Loader.getCities()));

Create sorted array from unsorted ArrayList

I have an ArrayList filled with objects of the class result, each result has an attribute named value. I now want to create an Array which is filled with references to the same memory location as in the ArrayList but now in order where to object with the highest value is in the first location, the second highest in the second location and so forth.
I have searched here but haven't found any other post like it.
There are multiple ways to solve it using Gauava or lambda expressions.
Hope this implementation solve your problem.
package com;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestDemo {
public static void main(String[] args) {
List < HockeyPlayer > players = new ArrayList < HockeyPlayer > ();
HockeyPlayer obj1 = new HockeyPlayer();
obj1.goalsScored = 22;
players.add(obj1);
HockeyPlayer obj2 = new HockeyPlayer();
obj2.goalsScored = 11;
players.add(obj2);
HockeyPlayer obj3 = new HockeyPlayer();
obj3.goalsScored = 111;
players.add(obj3);
HockeyPlayer obj4 = new HockeyPlayer();
obj4.goalsScored = 3;
players.add(obj4);
Collections.sort(players, new Comparator < HockeyPlayer > () {
#Override public int compare(HockeyPlayer player1, HockeyPlayer player2) {
return player1.goalsScored - player2.goalsScored;
}
});
for (int i = 0; i < players.size(); i++) {
System.out.println(players.get(i).goalsScored);
}
HockeyPlayer array[] = new HockeyPlayer[players.size()];
players.toArray(array); // contains reference
for (int i = 0; i < array.length; i++) {
System.out.println(array[i].goalsScored);
}
}
}
class HockeyPlayer {
public int goalsScored;
}

How to make generic Counting Sort Method?

Okay I am a pretty beginner java coder, and I am doing an assignment where I am stuck. I need to create a generic method (sort) that sorts a Type array according to frequency, basically, I am taking the CountingSort Algorithm and making it a generic method. This is where I am lost. I can't seem to figure out how to do this.
Here is a link to my instructions,
https://classes.cs.siue.edu/pluginfile.php/7068/mod_assign/intro/150mp08.pdf
Code:
Driver Class
package mp08;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Lists array = new Lists();
array.populateLists();
System.out.println("Original Int List: \n");
array.sort(Lists.intList);
System.out.println("Sorted Int List: \n");
}
}
Lists Class
package mp08;
import java.util.Arrays;
import java.util.Random;
public class Lists {
public static Integer[] intList;
public static Integer[] sortedintList;
public static Integer[] frequency;
public static Character[] charList;
public static Character[] sortedcharList;
public static int MAX_SIZE = 101;
public static int lengthInt;
public static int lengthChar;
public Lists(){
this.intList = new Integer[MAX_SIZE];
this.sortedintList = new Integer[MAX_SIZE];
this.charList = new Character[MAX_SIZE];
this.sortedcharList = new Character[MAX_SIZE];
this.frequency = new Integer[MAX_SIZE];
this.lengthInt = 0;
this.lengthChar = 0;
}
//Makes random integer for populated lists method.
public int randomInt(int min, int max){
Random rand = new Random();
int randomNum = rand.nextInt((max-min)+1)+min;
return randomNum;
}
//Makes random character for populated lists method.
public char randomChar(){
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int N = alphabet.length();
Random rand = new Random();
char randomLet = alphabet.charAt(rand.nextInt(N));
return randomLet;
}
//Populates intList and charList with random values.
public void populateLists(){
for (int i = 0; i < MAX_SIZE; i++) {
intList[i] = randomInt(1,100);
lengthInt++;
}
for (int i = 0; i < MAX_SIZE; i++) {
charList[i] = randomChar();
lengthChar++;
}
}
//Returns sorted array
public Integer[] sorted(){
return intList;
}
public static <T> void sort(T[] array) {
// array to be sorted in, this array is necessary
// when we sort object datatypes, if we don't,
// we can sort directly into the input array
Integer[] aux = new Integer[array.length];
// find the smallest and the largest value
int min = 1;
int max = 101;
// init array of frequencies
int[] counts = new int[max - min + 1];
// init the frequencies
for (int i = 0; i < array.length; i++) {
counts[array[i] - min]++;
}
// recalculate the array - create the array of occurence
counts[0]--;
for (int i = 1; i < counts.length; i++) {
counts[i] = counts[i] + counts[i-1];
}
/*
Sort the array right to the left
1) Look up in the array of occurences the last occurence of the given value
2) Place it into the sorted array
3) Decrement the index of the last occurence of the given value
4) Continue with the previous value of the input array (goto set1),
terminate if all values were already sorted
*/
for (int i = array.length - 1; i >= 0; i--) {
aux[counts[array[i] - min]--] = array[i];
}
}
public static void main(String[] args) {
Integer [] unsorted = {5,3,0,2,4,1,0,5,2,3,1,4};
System.out.println("Before: " + Arrays.toString(unsorted));
Integer [] sorted = sort(unsorted);
System.out.println("After: " + Arrays.toString(sorted));
}
}
I obviously have not finished my driver class yet and I would appreciate any help I can get!
There's no generic way for any Comparable type to get its ordinal number. Sometimes such numbers do not exist at all (for example, String is Comparable, but you cannot map any String to the integer number). I can propose two solutions.
First one is to store counts not in the array, but in TreeMap instead creating new entries on demand (using Java-8 syntax for brevity):
public static <T extends Comparable<T>> void sort(T[] array) {
Map<T, Integer> counts = new TreeMap<>();
for(T t : array) {
counts.merge(t, 1, Integer::sum);
}
int i=0;
for(Map.Entry<T, Integer> entry : counts.entrySet()) {
for(int j=0; j<entry.getValue(); j++)
array[i++] = entry.getKey();
}
}
public static void main(String[] args) {
Integer[] data = { 5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4 };
System.out.println("Before: " + Arrays.toString(data));
sort(data);
System.out.println("After: " + Arrays.toString(data));
Character[] chars = { 'A', 'Z', 'B', 'D', 'F' };
System.out.println("Before: " + Arrays.toString(chars));
sort(chars);
System.out.println("After: " + Arrays.toString(chars));
}
Such solution looks clean, but probably not very optimal (though its advantage is that it does not care whether all numbers are from 1 to 100 or not).
Another possible solution is to create some additional interface which defines ordering for given type:
public interface Ordering<T> {
int toOrdinal(T obj);
T toObject(int ordinal);
}
public class IntegerOrdering implements Ordering<Integer> {
#Override
public int toOrdinal(Integer obj) {
return obj;
}
#Override
public Integer toObject(int ordinal) {
return ordinal;
}
}
public class CharacterOrdering implements Ordering<Character> {
#Override
public int toOrdinal(Character obj) {
return obj;
}
#Override
public Character toObject(int ordinal) {
return (char)ordinal;
}
}
Now you may make your sort method accepting the ordering parameter:
public static <T> void sort(T[] array, Ordering<T> ordering) { ... }
Every time you need to get counts array index by T object, just call ordering.toOrdinal(object). Every time you need to get object by array index, just use ordering.toObject(index). So, for example, instead of
counts[array[i] - min]++;
Use
counts[ordering.toOrdinal(array[i]) - min]++;
And call the sorting method like this:
sort(characterArray, new CharacterOrdering());
sort(integerArray, new IntegerOrdering());

android Arrange data in descending order

I have following data in string(comma format) (Name,Mark)
A,20,B,10,C,30
I want to convert into Descending order like :
C,30,A,29,B,10
Please help me how can i implement in android ?
Here is code what i have prepared....
public class custom_sort {
public String name;
public int mark;
public custom_sort(String a, int b) {
// TODO Auto-generated constructor stub
name = a;
mark = b;
}
void setname(String s)
{
name=s;
}
void setmark(int s)
{
mark = s;
}
String getname()
{
return(name);
}
int getmark()
{
return(mark);
}
}
Thanks in Advance,
There are many ways of doing this. I see that you have already made a class: custom_sort. We can use this to sort it, if we just make it comparable. We do this by implementing the Comparable interface.
public class custom_sort implements Comparable{
Then all you need to do is implement the one required method:
#Override
public int compareTo(custom_sort cs) {
/*
This method should return 0 if the two objects are equal,
1 if this is biggest
and -1 if cs is biggest */
}
Then you can put all the custom_sorts in an List and just do Arrays.sort(yourArray).
You could also check out this post Android sort array
Use ArrayList rather than array of string.
This might not be the best solution but it works.
Initialize the ArrayList
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> scores = new ArrayList<>();
Fill data inside the ArrayList
names.add("A");
scores.add(20);
....
Now sort them
private void sortScoreAndName() {
for (int i = 0; i < scores.size(); i++) {
for (int j = 0; j < i; j++) {
if (scores.get(i) > scores.get(j))
swap(i, j);
}
}
}
private void swap(int i, int j) {
int tempSco = scores.get(i);
String tempName = names.get(i);
scores.remove(i);
names.remove(i);
scores.add(i, scores.get(j));
names.add(i, names.get(j));
scores.remove(j);
names.remove(j);
scores.add(j, tempSco);
names.add(j, tempName);
}
Now your ArrayList is in descending order. You can get the corresponding data using.
names.get(poition);
scores.get(position);
try this:
import android.support.v4.util.Pair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
String[] values = {"A", "20", "B", "10", "C", "30"};
List<Pair> pairs = new ArrayList<>();
for (int i = 0; i < values.length; i += 2) {
pairs.add(new Pair<>(values[i], Integer.parseInt(values[i + 1])));
}
Collections.sort(pairs, new Comparator<Pair>() {
#Override
public int compare(Pair lhs, Pair rhs) {
return ((Integer) rhs.second).compareTo((Integer) lhs.second);
}
});
The List pairs is now sorted like you wish. Check out the Pair class i used http://developer.android.com/reference/android/util/Pair.html
And if you want to convert it back following code will help you:
String[] newValues = new String[values.length];
int i = 0;
for (Pair pair : pairs) {
newValues[i] = (String) pair.first;
newValues[i + 1] = Integer.toString((Integer) pair.second);
i += 2;
}

How to sort Integer Vector using Comparator and iterator?

I want to create Integer vector type Vector and to insert random 10 numbers.
Then I want to sort the Vector by using compareTo and to send two arguments type numbers to compare it.
but I miss something.
Many thanks for any help.
import java.util.*;
public class SortNumeric implements Comparable<SortNumeric>
{
private int ind =0;
public static void main(String args[])
{
Vector<Integer> vec = new Vector<>();
System.out.println("Befor sorting");
for (int index = 0; index < 10; index++)
{
int rand = (int)(1000*Math.random());
vec.add(rand);
System.out.println(rand);
}
Arrays.sort(vec);
System.out.println("After sorting");
for(Integer intnum : vec)
{
System.out.println(intnum);
}
}
public int getNextCompar(){
if (vec.hasNext() && this.ind < 5){
this.ind++;
return vec.next();
}else{return 0;}
}
public int compareTo(SortNumeric other)
{
return (int) (vec.next() - this.getNextCompar());
}
}
class sortVectors implements Comparator<Integer>{
#Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
if(o1<02){
return -1;
}else if(o1>o2)
return 1;
return 0;
}
}
public class sortVector{
public static void main(String[] args) {
// TODO Auto-generated method stub
Vector<Integer> vect = new Vector<Integer>();
System.out.println("Befor sorting");
for (int index = 0; index < 10; index++) {
int rand = (int) (1000 * Math.random());
vect.add(rand);
System.out.println(rand);
}
Collections.sort(vect,new sortVectors());
System.out.println("After Sorting");
for (Integer num : vect) {
System.out.println(num);
}
}
}
You don't need to implement Comparable for Integer, hence no compareTo is required. Also use Collections.sort instead of Arrays.sort. Here is your modified code example:
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String args[]) {
Vector<Integer> vec = new Vector<>();
System.out.println("Befor sorting");
for (int index = 0; index < 10; index++) {
int rand = (int) (1000 * Math.random());
vec.add(rand);
System.out.println(rand);
}
Collections.sort(vec);
System.out.println("After sorting");
for (Integer intnum : vec) {
System.out.println(intnum);
}
}
}
Check this SO question for more details:
What function can be used to sort a Vector?
If you want to sort an array in a specific order, you need to create a Comparator.
Comparable is used when you want to sort the objects of a particular class when used in a collection or array.
In your case, you need to use a Comparator.
class MyComparator extends Compartor
{
public int compare(Integer a, Integer b)
{
return a - b;
}
}
In your Main class, call Arrays.sort(vec, new MyComparator());

Categories