You are given a list of n products, each with a name, price and weight.
Find out how many duplicates of a product are present within the list. A duplicate is a product with all parameters, equal to some other product.
input is 3 lists
Name Price Weight
1. ball 2 1
2. box 2 2
3. ball 2 1
4. ball 2 1
5. box 2 3
output:
2
explanation:
(1.) is same as (3.) and is also same as (4.) so there is 2... 1->3 and 1->4
Function Description
numDuplicates has the following parameter(s):
name: string array of size n, where names[i] denotes the name of the ith product
price: int array of size n, where prices[i] denotes the price of the ith product
weight: int array of size n, where weights[i] denotes the weight of the ith product
function you need to fill out:
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
// Write your code here
//return an int
}
this is what i wrote for my code and is O(n^2) but some test-cases are running out of time so i think it wants an O(n) solution but i cant think of it...
class Result {
/*
* Complete the 'numDuplicates' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. STRING_ARRAY name
* 2. INTEGER_ARRAY price
* 3. INTEGER_ARRAY weight
*/
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
int count = 0;
List<obj> classList = new ArrayList<obj>();
for(int i=0; i<name.size(); i++){
obj holder = new obj(name.get(i),price.get(i),weight.get(i));
classList.add(holder);
}
for(int i=0; i<classList.size(); i++){
for(int j=i+1; j<classList.size();j++){
if(classList.get(i).isDuplicate(classList.get(j))){
count++;
classList.remove(classList.get(j));
j--;
}
}
}
return count;
}
}
class obj{
String name;
int price;
int weight;
public obj(String name, int price, int weight){
this.name = name;
this.price = price;
this.weight = weight;
}
public boolean isDuplicate(obj x){
if(this.name.equals(x.name) && this.price == x.price && this.weight == x.weight){
return true;
}
return false;
}
}
i created my own object class, and i created a compare method but i think it might be inefficent
For :
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
// Write your code here
//return an int
}
Use Like below:
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
List<String> f1 = new ArrayList<String>();
int countTotal = name.size();
for (int i = 0; i < countTotal; i++) {
f1.add(name.get(i) + price.get(i) + weight.get(i));
}
//Unique List item
Set<String> uniqueItemSet = new HashSet<String>(f1);
Integer uniqueItems = uniqueItemSet.size();
int countAll = f1.size();
return(countAll-uniqueItems);
}
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
Set<String> uniqueProducts = new HashSet<String>();
for (int i = 0; i < name.size(); i++)
uniqueProducts.add(name.get(i) + " " + price.get(i) + " " + weight.get(i));
return name.size() - uniqueProducts.size();
}
public static int numDuplicates(List<String> names, List<Integer> price,
List<Integer> weight) {
int count = 0;
String product = "";
Map<String, Integer> dupMap = new HashMap<String, Integer>();
for (int i = 0; i < names.size(); i++) {
product = names.get(i) + price.get(i) + weight.get(i);
if (dupMap.get(product) != null) {
count++;
} else {
dupMap.put(product, 1);
}
}
return count;
}
List<string> final = new List<string>();
int countTotal = name.Count;
for (int i = 0; i < countTotal; i++) {
final.Add(name.ElementAt(i) + price.ElementAt(i) + weight.ElementAt(i));
}
var uniqueItems = final.Distinct();
int countDistinct = uniqueItems.Count();
return(countTotal-countDistinct);
public static int numDuplicates(List<String> name, List<Integer> price, List<Integer> weight) {
int res=0;
HashSet<String> set = new HashSet<String>();
for(int i=0;i<name.size();i++){
String cmb = name.get(i) + "_" + price.get(i)+ "_" + weight.get(i);
if(set.contains(cmb)){
res++;
}
else{
set.add(cmb);
}
}
return res;
}
}
Or you may put the values in a pandas dataframe, then take the length of that data frame, use drop_duplicate function on to the dataframe to drop duplicates, take the revised dataframe's length, and then calculate the difference in length and print.
Related
I have an array and I want to assign values in group of 3s
Name, Id, Population, Name, Id, Population, Name, Id, Population etc.
Is there a way to do that?
This is what I have
while (scanner.hasNext()) { `
scanner.useDelimiter(",");`
list.add(scanner.nextLine());}`
for(int i=0; i<list.size(); i++){
String n = list.get(i);
System.out.println("Hopefully going thru " + n);} //for me to check
String ar =list.toString();
Object [] a = ar.split(",");// splitting the array for each string
for(int h=0;h<a.length;h+=3) { // for [0] += 3 is Name
for(int j=1;j<a.length; j+=3) { // for [1] += 3 is Id
for(int k=2; k<a.length;k+=3) { //for[2]+= is Population
String name = a[h].toString();
String id = a[j].toString();
String population = a[k].toString();
System.out.println("name is "+ name);// this is just to check correct values
System.out.println("id is "+ id);// this is just to check correct values
System.out.println("population is " +population);// this is just to check correct values
CityRow cityRow = new CityRow(name,id,population); //?? I want every set of [0][1][2] to create a new object`
I don‘t think that ar has the correct data and I don‘t understand why you don’t work with list directly, but assuming that ar has the correct data, it should be possible to use:
for(int = 0; i < ar.length ; ) {
var cityRow = new CityRow(
ar[i++],
ar[i++],
ar[i++]
);
// remember to add cityRow to an
// appropriate list
}
You use Scanner so no need to split an array. You can read each separate value one-by-one directly from it.
public class Main {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\n|,");
System.out.print("Total groups: ");
int total = scan.nextInt();
List<City> cities = readCities(scan, total);
printCities(cities);
}
private static List<City> readCities(Scanner scan, int total) {
List<City> cities = new ArrayList<>(total);
System.out.println("Enter each city on a new line. Each line should be: <id>,<name>,<population>");
for (int i = 0; i < total; i++) {
String id = scan.next();
String name = scan.next();
int population = scan.nextInt();
cities.add(new City(id, name, population));
}
return cities;
}
private static void printCities(List<City> cities) {
System.out.println();
System.out.format("There are total %d cities.\n", cities.size());
int i = 1;
for (City city : cities) {
System.out.format("City №%d: id=%s, name=%s, population=%d\n", i++, city.id, city.name, city.population);
}
}
static class City {
private final String id;
private final String name;
private final int population;
public City(String id, String name, int population) {
this.id = id;
this.name = name;
this.population = population;
}
}
}
My findmaxprice method returns the index of the first Car in the array with the maximum price. If it is not found, -1 is returned.
As far as I know, return will stop the for loop. Any advice on how to avoid it while keep the loop search for max price?
public int findmaxprice() {
double max =0;
for(int i =0; i < nCars; i++) {
if(max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
return i; //the problem is here
}
}
return -1;
}
You almost answered yourself - just don't return in the for loop.
public int findmaxprice() {
double max =0;
int maxIndex = -1;
for( int i =0; i < nCars; i++) {
if(max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
maxIndex = i;
}
}
return maxIndex;
}
Move the return statement outside of the loop
findmaxprice method: returns the index of the first Car in the array with the maximum price. If it is not found, -1 is returned. as far as i know, return will stop the for loop , any advice on how to avoid it while keep the loop search for max price ?
public int findmaxprice() {
double max =0;
for( int i =0; i < nCars; i++) {
if(max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
}
}
if(max != 0){
return max;
} else {
return -1;
}
}
The below method will fix your issue. Also, it gives you ability to specify a minimum price above which the car price will be considered for max calculation. You can keep this 0 in function call like findMaxPrice(0)if no such boundation needed.
public int findMaxPrice(int min) {
double max = min;
int maxPriceCarIndex = -1;
for (int i = 0; i < nCars; i++) {
if (max <= Cars[i].getPrice()) {
max = Cars[i].getPrice();
maxPriceCarIndex = i; //reassign the index here
}
}
return maxPriceCarIndex;
}
Maybe you just need the "most expensive" car and not the index of the car, then you could consider using streams
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
public class Test {
public static void main(String[] args) {
new Test().testGetMostExpensiveCar();
}
private void testGetMostExpensiveCar() {
// test null array
Car[] cars = null;
Car mostExpensive = getMostExpensiveCar(cars);
System.out.println(mostExpensive); // prints null
// test empty array
cars = new Car[10];
mostExpensive = getMostExpensiveCar(cars);
System.out.println(mostExpensive); // prints null
//test array with cars
cars[0] = new Car(10.0);
cars[5] = new Car(20.0);
cars[8] = new Car(30.0);
cars[8] = new Car(30.0);
mostExpensive = getMostExpensiveCar(cars);
System.out.println(mostExpensive);// prints Car [price=30.0]
}
/**
* #param cars
* #return the most Expensive car, null if the array is empty or no car is in
* the array
*/
public Car getMostExpensiveCar(Car[] cars) {
if (cars == null) {
return null;
}
return Arrays.stream(cars) // creates a Stream<Car> (take a look at e.g. https://www.baeldung.com/java-8-streams)
.filter(Objects::nonNull) // because there can be "null" values in the array
.max(Comparator.comparing(Car::getPrice)) // compares the car by price asc
.orElse(null); // return null if no element is found
}
private class Car {
private double price;
public Car(double price) {
super();
this.price = price;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
return "Car [price=" + price + "]";
}
}
}
Problem Statement: I have a 2D array of strings containing student names and respective marks as below
String[][] scores = {{"Bob","85"},{"Mark","100"},{"Charles","63"},{"Mark","34"}};
I want to calculate the best average among all the students available, i.e with the above input the best average should be 85.
My Attempt:
I tried to solve this using HashMap as below.
public int bestAverageCalculator(String[][] scores) {
// This HashMap maps student name to their list of scores
Map<String,List<Integer>> scoreMap = new HashMap<String,List<Integer>>();
for(String[] score:scores) {
String name = score[0];
int currentScore =Integer.parseInt(score[1]);
if(scoreMap.containsKey(name)) {
List<Integer> scoreList = scoreMap.get(name);
scoreList.add(currentScore);
scoreMap.put(name, scoreList);
}
else {
List<Integer> scoreList = new ArrayList<Integer>();
scoreList.add(currentScore);
scoreMap.put(name, scoreList);
}
}
//scoreMap will be {Charles=[63], Bob=[85], Mark=[100, 34]}
//After Map is formed i am iterating though all the values and finding the best average as below
int bestAverage = 0;
for(List<Integer> value:scoreMap.values()) {
int sum = 0;
int count = 0;
for(int i:value) {
sum+=i;
count++;
}
int average = (int)Math.floor(sum/count);
if(average>bestAverage)
bestAverage = average;
}
return bestAverage;// returns 85
}
The implementation is correct and i am getting the answer as expected, but i was told the space complexity of the program is more and it can be achieved without using the List<Integer> for marks, i am not able to understand how average can be calculated on fly without storing list of marks.
Please suggest if any other methods can solve this other than HashMap.
Any help would be appreciated.
You could store for each student a constant amount of data :
the student's name
the sum of all the student's marks
the number of the student's marks
This will make the space complexity O(m) where m is the number of unique students (instead of your O(n) where n is the number of marks).
For example, you can have a Student class with these 3 properties (and store the data in a List<Student>), or you can have a Map<String,int[]> with the key being the student's name and the value being an array of two elements containing the sum of the marks and the number of marks.
You can construct this data while iterating over the input.
Now you can compute the average for each student and find the highest average.
Well for space saving you can store two numbers per person
avgSum and count and calculate average on the end.
I have implemented #Eran 's approach based on your code with a Map<String,int[]> with
key: student's name
value: an array of two elements [the sum of the scores, the number of scores]
public int bestAverageCalculator(String[][] scores) {
// This HashMap maps student name to their total scores and count in an int array format of [totalScores, count]
Map<String,int[]> scoreMap = new HashMap<String,int[]>();
for(String[] score:scores) {
String name = score[0];
int currentScore =Integer.parseInt(score[1]);
if(scoreMap.containsKey(name)) {
int[] scoreCount = scoreMap.get(name);
scoreCount[0] += currentScore;
scoreCount[1] ++;
scoreMap.put(name, scoreCount);
}
else {
int[] scoreCount = new int[]{currentScore, 1};
scoreMap.put(name, scoreCount);
}
}
int bestAverage = 0;
for(int[] value:scoreMap.values()) {
int average = (int)Math.floor(value[0]/value[1]);
if(average>bestAverage)
bestAverage = average;
}
return bestAverage;// returns 85
}
#Eran's idea but with Student class, at least for me it's much more clear
import java.util.*;
public class Main {
static String[][] scores = {{"Bob", "85"}, {"Mark", "100"}, {"Charles", "63"}, {"Mark", "34"}};
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
for (String[] score : scores) {
String name = score[0];
int currentScore = Integer.parseInt(score[1]);
Student student = findStudentByName(name, students);
if (student != null) {
student.setNumberOfScores(student.getNumberOfScores() + 1);
student.setSumOfScores(student.getSumOfScores() + currentScore);
} else {
student = new Student(name, 1, currentScore);
students.add(student);
}
}
findStudentWithBestAverage(students);
}
private static void findStudentWithBestAverage(List<Student> students) {
Student bestStudent = null;
int bestAverage = 0;
for (int i = 0; i < students.size(); i++) {
if ((students.get(i).getSumOfScores() / students.get(i).getNumberOfScores()) > bestAverage) {
bestStudent = students.get(i);
bestAverage = (students.get(i).getSumOfScores() / students.get(i).getNumberOfScores());
}
}
System.out.println(bestStudent + " with average: " + bestAverage);
}
private static Student findStudentByName(String name, List<Student> students) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getName().equals(name)) {
return students.get(i);
}
}
return null;
}
public static class Student {
private String name;
private int numberOfScores;
private int sumOfScores;
public Student(String name, int numberOfScores, int sumOfScores) {
this.name = name;
this.numberOfScores = numberOfScores;
this.sumOfScores = sumOfScores;
}
public String getName() {
return name;
}
public int getNumberOfScores() {
return numberOfScores;
}
public void setNumberOfScores(int numberOfScores) {
this.numberOfScores = numberOfScores;
}
public int getSumOfScores() {
return sumOfScores;
}
public void setSumOfScores(int sumOfScores) {
this.sumOfScores = sumOfScores;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return name.equals(student.name);
}
#Override
public int hashCode() {
return Objects.hash(name);
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", numberOfScores=" + numberOfScores +
", sumOfScores=" + sumOfScores +
'}';
}
}
}
I've searched up and down for the fix to my issue, but none seem to work. One particular reference-- this and this, and especially this. However, no matter how I implement them, I receive an OutOfBoundsError, which I can't understand.
The program is extra credit for a class. In truth, it is very simple--
Program Description: Use a two dimensional array to solve the following problem. A company has four sales persons (1 to 4) who sell five different products (1 to 5). Once a day, each salesperson passes in a slip for each different type of product sold. Each slip contains:
The sales persons numberThe product numberThe total dollar value of that product sold that day
Thus, each salesperson passes in between 0 and 5 sales slips per day. Assume that the information from all of the slips for last month is available. Each data line contains 3 numbers (the sales person number, product number, sales).
Write a program that will read all this information for last month’s sales, and summarize the total sales by salesperson by product.
The data provided:
1 2 121.77
1 4 253.66
1 5 184.22
1 1 97.55
2 1 152.44
2 2 104.53
2 4 189.97
2 5 247.88
3 5 235.87
3 4 301.33
3 3 122.15
3 2 301.00
3 1 97.55
4 1 125.66
4 2 315.88
4 4 200.10
4 3 231.45
The error only comes when it tries to calculate the columns. My rows work; no matter how I change the for-loop or any of the indeces in the row or column of the array, it doesn't work. I at first had my rows calculated separately, then my column sums, and it didn't work either. There is something that I'm missing that I'm clearly overlooking.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class prog480u {
static Scanner inFile = null;
public static void main(String[] args) {
try {
// create scanner to read file
inFile = new Scanner(new File ("prog480u.dat"));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(0);
}
// make the array
int x = 0;
int y = 0;
double[][] profits = new double[4][5];
while (inFile.hasNext()) {
x = inFile.nextInt(); // use sales numbers as coordinates
y = inFile.nextInt();
profits[x - 1][y - 1] = inFile.nextDouble();
}
// check if it's okay
System.out.println("");
double[][] columnProfits = sums(profits);
for (int a = 0; a < columnProfits.length; a++) {
System.out.print((a+1) + "\t");
for (int b = 0; b < columnProfits[a].length; b++) {
System.out.print(columnProfits[a][b] + "\t");
}
System.out.println("");
}
double[] bottomRow = columnSums(columnProfits);
for (int a = 0; a < bottomRow.length; a++) {
System.out.print("Total:" + bottomRow + "\t");
}
}
public static double[][] sums (double[][] q) {
double[][] array = new double[5][6];
array = q;
double sum = 0;
for (int a = 0; a < array.length; a++) {
for (int b = 0; b < array[0].length; b ++) {
sum += array[a][b]; // add everything in the row
}
array[a][4] = sum; // set that row to the last column
sum = 0; // reset sum to 0
}
return array;
}
public static double[] columnSums (double[][]q) {
double[][] array = new double[5][6];
array = q;
double sum2 = 0;
double[] columns = new double [5];
for (int a = 0; a < array.length; a++) {
for (int b = 0; b < array[0].length; b ++) {
sum2 += array[b][a];
columns[b] = sum2;
}
sum2 = 0; // reset sum to 0
}
return columns;
}
}
Thank you very much for your time. I have a feeling my program is close to working, but this small mistake is pushing me over the edge.
Here's the working code (I cleaned it up a bit):
You were very close, you just needed to swap your max indicies in the for loops. That's why you were getting a java.lang.ArrayIndexOutOfBoundsException
public static double[] columnSums(double[][] q)
{
double[][] array = q;
double[] columns = new double[5];
for (int a = 0; a < array[0].length; a++)
{
for (int b = 0; b < array.length; b++)
{
columns[a] += array[b][a];
}
}
return columns;
}
Just for fun, I wrote the object oriented version for that.
Easier to handle once the system requires additional functionalities:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
class Sale {
static public ArrayList<Sale> readSales(final String pSalesFileName) throws FileNotFoundException, IOException {
final ArrayList<Sale> ret = new ArrayList<>();
try (final BufferedReader br = new BufferedReader(new FileReader(pSalesFileName))) {
int lineIndex = 0;
while (true) {
++lineIndex;
final String line = br.readLine();
if (line == null) {
System.out.println("Line #" + lineIndex + " is empty, skipping...");
break;
}
try {
final String[] values = line.split("\\s");
final int salesPersonId = Integer.parseInt(values[0]);
final int productId = Integer.parseInt(values[1]);
final float sales = Float.parseFloat(values[2]);
final Sale sale = new Sale(salesPersonId, productId, sales);
ret.add(sale);
} catch (final ArrayIndexOutOfBoundsException e) {
System.err.println("Parse error in line #" + lineIndex + ": '" + line + "'");
}
}
}
return ret;
}
private final int mSalesPersonId;
private final int mProductId;
private final float mSales;
public Sale(final int pSalesPersonId, final int pProductId, final float pSales) {
mSalesPersonId = pSalesPersonId;
mProductId = pProductId;
mSales = pSales;
}
public Integer getSalesPersonId_R() {
return Integer.valueOf(mSalesPersonId);
}
public Integer getProductId_R() {
return Integer.valueOf(mProductId);
}
public float getSales() {
return mSales;
}
}
class SalesPerson {
private final HashMap<Integer, ArrayList<Sale>> mSalesMap = new HashMap<>();
private final int mId;
public SalesPerson(final int pId) {
mId = pId;
}
#Override public boolean equals(final Object pObj) {
if (!(pObj instanceof SalesPerson)) return false;
return ((SalesPerson) pObj).mId == mId;
}
#Override public int hashCode() {
return mId;
}
public void addSale(final Sale pSale) {
final Integer productId = pSale.getProductId_R();
ArrayList<Sale> salesList = mSalesMap.get(productId);
if (salesList == null) {
salesList = new ArrayList<>();
mSalesMap.put(productId, salesList);
}
salesList.add(pSale);
}
public Integer getId_R() {
return Integer.valueOf(mId);
}
public HashMap<Integer, ArrayList<Sale>> getSalesMap() {
return mSalesMap;
}
public float getSalesTotalByProductId(final Integer pProductId) {
final ArrayList<Sale> sales = mSalesMap.get(pProductId);
float accumulator = 0;
for (final Sale sale : sales) {
accumulator += sale.getSales();
}
return accumulator;
}
}
public class SalesFun {
public static void main(final String[] args) throws FileNotFoundException, IOException {
final ArrayList<Sale> sales = Sale.readSales("test/sales.txt");
final HashMap<Integer, SalesPerson> personMap = new HashMap<>();
for (final Sale sale : sales) {
// find right salesperson or create new, then add sale to it
final Integer salesPersonId = sale.getSalesPersonId_R();
SalesPerson person = personMap.get(salesPersonId);
if (person == null) {
person = new SalesPerson(salesPersonId.intValue());
personMap.put(salesPersonId, person);
}
person.addSale(sale);
}
printSales(personMap);
}
static private void printSales(final HashMap<Integer, SalesPerson> pPersonMap) {
for (final SalesPerson person : pPersonMap.values()) {
System.out.println("SalesMan ID: " + person.getId_R());
for (final Entry<Integer, ArrayList<Sale>> entry : person.getSalesMap().entrySet()) {
final Integer productId = entry.getKey();
final float sales = person.getSalesTotalByProductId(productId);
System.out.println("\tProduct ID: " + entry.getKey() + "\tSales: " + sales);
}
}
}
}
I am trying to output the names and corresponding scores in descending order. Having an array of strings and another array of integers, I am trying to relate the two arrays. I used Arrays.sort and tries to get the indices. The indices is then to be used to arrange the names in similar location as the corresponding scores. I have this code but I get run time error saying unfortunately, your app has stopped. Can anyone please help me on what to be done to achieve my goal here? Thank you so much!
int score[]= new int[4];
score[0]= 10;
score[1]= 50;
score[2]= 20;
score[3]= 60;
String names[] = new String[4];
names[0]= "player1";
names[1]= "player2";
names[2]= "player3";
names[3]= "player4";
Arrays.sort(score);
int index_array[] = new int[4];
int m = 0;
for(m = 0; m <4; m++){
index_array[m]=Arrays.binarySearch(score ,score[m]);
l = index_array[0];
}
for(int i = 0; i<4; i++){
if(l == score[i]){
j = i;
}
}
String name = names[m];
show.setText(name + " " + Integer.toString(l));
Create Player model which holds player's name and score and then use Comparator to sort players by score.
Player model:
class Player {
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public String toString() {
return "name=" + name + "; score=" + score;
}
}
Comparator:
class PlayerComparator implements Comparator<Player> {
public int compare(Player p1, Player p2) {
return p1.getScore() < p2.getScore() ? -1
: p1.getScore() > p2.getScore() ? 1 : 0;
}
}
And an example of usage:
public class PlayerTest {
public static void main(String[] args) {
int score[]= new int[4];
score[0]= 10;
score[1]= 50;
score[2]= 20;
score[3]= 60;
String names[] = new String[4];
names[0]= "player1";
names[1]= "player2";
names[2]= "player3";
names[3]= "player4";
Player[] players = new Player[names.length];
for(int i = 0; i < names.length; i++) {
players[i] = new Player(names[i], score[i]);
}
Arrays.sort(players, new PlayerComparator());
}
}
you need to associate the score and the user name. Currently, you are associating them by array index. when you sort the scores, the indices of the scores will change.
Try something like this:
class Score implements Comparable<Score>
{
int score;
String player;
public Score(int theScore, String thePlayer)
{
score = theScore;
player = thePlayer;
}
public int compareTo(Score)
{
... compare based on the int score value ...
}
... getters. setters optional ...
}
List<Score> scoreList = new ArrayList<Score>();
... fill scoreList with Score objects. ...
Collections.sort(scoreList);
This is a design smell. You shouldn't have two parallel arrays. Instead, you should have a single array of Player objects, where each Player would have a name and a score.
Storing the arra of players by name or by score would then be extremely simple.
Java is an OO language. Use objects.
public class Player
private final String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
...
Player[] players = new Player[4];
players[0] = new Player("player1", 10);
...