I am trying to find he upper and lower bound of the data below
0,0
4,0
12,1
16,1
16,2
18,4
24,5
26,8
28,9
If my mid-range is 5 . I need to group my data as
1 st column = [0,4,12,16,16],[18,24,26,28] (rest of the values can be just added to list even if it is not of size 5)
But instead of storing every elements into an array. I would like to store only [0,16],[18,28].
Like wise for 2 nd column [0,2],[4,9].
But using my current code I am only getting [0,16].
Below is my code
import java.util.ArrayList;
public class Trail {
public static void main(String[] args) {
ArrayList<String> inputvalues = new ArrayList<String>();
inputvalues.add("0:0.0");
inputvalues.add("0:4.0");
inputvalues.add("0:12.0");
inputvalues.add("0:16.0");
inputvalues.add("0:16.0");
inputvalues.add("0:18.0");
inputvalues.add("0:24.0");
inputvalues.add("0:26.0");
inputvalues.add("0:28.0");
inputvalues.add("1:0.0");
inputvalues.add("1:0.0");
inputvalues.add("1:1.0");
inputvalues.add("1:1.0");
inputvalues.add("1:2.0");
inputvalues.add("1:4.0");
inputvalues.add("1:5.0");
inputvalues.add("1:8.0");
inputvalues.add("1:9.0");
/*
* Iterate through data
*/
int counter = 0 ;
double prevV = 0;
String currKey = "";
String prevKey = "";
ArrayList<Double> arr = new ArrayList<>();//REsult with upperbound and lower bount
int splitRange = 5;
for(String lst : inputvalues){
counter++;
System.out.println("\n*********lst********** "+lst);
String[] parts = lst.split(":");//key
currKey = parts[0];//value
double v = Double.parseDouble(parts[1]);
if(prevKey.equals ("")){
/*
* prev value empty.
* Initial value
*/
arr.add(v);
System.out.println("Initial range "+arr);
}
else if(prevKey.equals(currKey)){
/*
* Both incoming values are same
*/
System.out.println("----------same key-----------");
if(counter == splitRange){
arr.add(v);
System.out.println("RESULT-------->"+arr);
counter = 0;
}
else{
prevV = v;
// System.out.println("Previous v "+prevV);
}
/*
* initial counter
*/
if(counter == 1 ){
arr = new ArrayList<>();
arr.add(v);
// System.out.println("counter equals 1 "+arr);
}
}
else if (!prevKey.equals(currKey)){
if(counter != splitRange){
// System.out.println("In not equalls");
arr = new ArrayList<>();
arr.add(prevV);
// System.out.println("arrr "+arr);
}
counter = 0;
if(counter == 1 ){
arr = new ArrayList<>();
arr.add(prevV);
// System.out.println("counter equals 1 "+arr);
}
counter++;
/*
* previous value
*/
// System.out.println("Previous v "+prevV);
arr.add(prevV);
// System.out.println("prev not equal to current "+arr);
}
prevKey = currKey;
}
}
}
Please help me to figure out the same.
Related
I'm trying to write a class called RailwayStation that will print an array of train (using two different classes I wrote called TIME1and Train. My problem is that I can't understand why the output is arranged in the wrong order.
I assume the problem is in the method inside the class called addTrain, which supposed to add a train trip if there exists an empty cell in the array, and if the trip that wishes to be added does not exists already in the array. another method I used (and might be the problem) is called removeTrain, which receives a parameter of a train trip and removes that from the array. My methods addTrain, removerTrain, and toStringis as follows:
public class RailwayStation {
// declrations of final variables
private final int MAX_TRAINS = 100;
private final int MIN_VAL = 0;
// declrations of instant variables
private Train[] _station;
private int _noOfTrs;
/**
* Empty construter which initialize the instant variables of the class such that the trips array will be in a maximal size
*/
public RailwayStation() {
_station = new Train[MAX_TRAINS];
_noOfTrs = MIN_VAL;
}
/**
* adds a train trip to the trips array
*
* #param f the train trip
* #Returns true if a train trip has been added to the trips array
*/
public boolean addTrain(Train f) {
int i, j;
// boolean found = false;
if (isTrainOnSomeStation(f)) {
return false;
}
else {
for (j = MIN_VAL; j < _station.length; j++) {
if (_station[j] == null) {
_station[j] = f;
_noOfTrs++;
return true;
}
}
return false;
}
}
// a private method that checks if #param f is null
private boolean isTrainOnSomeStation(Train f) {
if (f == null) {
return false;
}
for (int i = MIN_VAL; i < _station.length; i++) {
if (_station[i] != null && _station[i].equals(f)) {
return true;
}
}
return false;
}
/**
* removes a trip from the trips array
* #param f the train trip
* #returns true if the train trip has been removed
*/
public boolean removeTrain(Train f) {
int i, j;
boolean found = false;
for (j = MIN_VAL; j < _station.length && !found; j++) {
if (_station[j] != null) {
for (i = MIN_VAL; i < _noOfTrs && !found; i++)
if (_station[i].equals(f)) {
_station[i] = _station[_noOfTrs];
_station[_noOfTrs] = null;
found = true;
_noOfTrs--;
}
}
}
return found;
}
/** Returns a string which describes all train in the array as apperas in the arrray
* #Returns a string of trains as appears in the arrat
*/
public String toString(){
String str = "The trains today are:" +"\n";
if(_noOfTrs == MIN_VAL){
return "There are no trains today.";
}
else {
String capacity = "";
for (int i = 0; i < _station.length; i++) {
if (_station[i] != null) {
if (_station[i].isFull() == true) {
capacity = "Train is full";
}
else {
capacity = "Train is not full";
}
str += _station[i].toString() + "\n";
}
}
}
return str;
}
}
In order to call the method addTrain I'll be writing:
//Check constructor
RailwayStation rs = new RailwayStation();
//AddTrain
Train f1 = new Train("Haifa",12,0,210,250,250,55);
Train f2 = new Train("Jerusalem",10,50,210,250,250,40);
rs.addTrain(f1);
rs.addTrain(f2);
System.out.println(rs);
//RemoveTrain
rs.removeTrain(f1);
System.out.println(rs);
//First Train to Destination
Train f3 = new Train("Tel-Aviv",11,35,180,100,200,35);
rs.addTrain(f3);
Train f3a = new Train("Tel-Aviv",7,15,180,200,200,35);
rs.addTrain(f3a);
I'm expecting to get the output:
The trains today are:
Train to Jerusalem departs at 10:50. Train is full.
Train to Tel-Aviv departs at 11:35. Train is not full.
Train to Tel-Aviv departs at 07:15. Train is full.
but what I get is:
The trains today are:
Train to Tel-Aviv departs at 11:35. Train is not full.
Train to Jerusalem departs at 10:50. Train is full.
Train to Tel-Aviv departs at 07:15. Train is full.
I've tried to use the debugger in order to understand in what part the order gets wrong, but I can't locate the problem.
When you add the first trains your array is like so:
Train[0] = Haifa...
Train[1] = Jerusalem..
Train[2] = null
Train[3] = null
...
Then you remove Haifa:
Train[0] = null
Train[1] = Jerusalem..
Train[2] = null
Train[3] = null
...
Then you add the other trains:
Train[0] = Tel Aviv..
Train[1] = Jerusalem..
Train[2] = Tel Aviv..
Train[3] = null
...
Does that explain it?
The data structure you're trying to build here is a Stack - but the good news is that java already has one, so no need to do what you are trying to do:
Stack<Train> trains = new Stack<>();
Train f1 = new Train("Haifa",12,0,210,250,250,55);
Train f2 = new Train("Jerusalem",10,50,210,250,250,40);
trains.push(f1);
trains.push(f2);
//RemoveTrain
trains.remove(f1);
//First Train to Destination
Train f3 = new Train("Tel-Aviv",11,35,180,100,200,35);
trains.push(f3);
Train f3a = new Train("Tel-Aviv",7,15,180,200,200,35);
trains.push(f3a);
String str = "The trains today are:" +"\n";
for(Train train: trains) {
str = str + train + "\n";
}
System.out.println(str);
I have to backtracking with numbers in a list that represent restrictions, such as: "x1 + x2> = 1". And if it meets all the conditions, that array is added to another array, in addition there is another list that represents the sum that I must make with all the variables "x1 + x2 + x3 + x4" and with that search for the one with the minimum value.
good what I should do in backtraking is to make a binary matrix with all the possibilities that the restrictions meet. What I have done is this but I get the error: "Exception in thread" main "java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 0" and I don't know where my problem is.
import java.util.ArrayList;
public class Pra_hacer_pruebas {
public static void main(String[] args) {
Pra_hacer_pruebas a = new Pra_hacer_pruebas();
ArrayList<Integer> conf1= new ArrayList<>(); // conf1 is the list that will contain one of the possibilities that may or may not be added to the binary matrix.
ArrayList<ArrayList<Integer>>pos_v = new ArrayList<>();// pos_v is where the possibilities will be added, binary matrix
int[][] restric = new int[2][2];// restric is the list with restrictions
restric[0][0]=2;
restric[0][1]=1;
restric[1][0]=4;
restric[1][1]=2;
for(int t=0;t<4;t++){
conf1.set(t, -1);
}
//System.out.println(conf.get(i));
a.binario(conf1,restric,0,0,0,pos_v,0,4,-1);
}
public void binario(ArrayList<Integer> conf1, int[][] restric, int suma,int filas,int columnas,ArrayList<ArrayList<Integer>> pos_validas,int posicion, int cont,int bin){
//filas = rows, suma= sum is to see if it meets the condition, columnas = columns, pos_validas = pos_v, posicion is to advance the rows of the matrix, cont: is the amount of different variables, bin is the binary variable
Boolean booleano = false; // booleano is the flag that if it is true it is because there was a null position (-1)
for (int[] restric1 : restric) {
suma=0;
for (int co = 0; co < restric1.length; co++) {
if ((conf1.get(restric1[co]) == 1) || (conf1.get(restric1[co]) == 0)) {
suma = suma + conf1.get(restric1[co]);
} else {
booleano = true;
}
}
if (booleano == false) {
if (suma < 1){
break;
}
}
}
if (booleano == false) {
pos_validas.set(posicion, conf1);
posicion++;
}
for (int f = 0; f < cont; f++) {
if (conf1.get(f) < 1) {
bin++;
conf1.set(f, bin);
binario(conf1,restric,suma,filas,columnas,pos_validas,posicion,cont,bin);
}
bin--;
}
}
}
Try add method. Even if you create ArrayList with initialCapacity, It won't works as you intended. If you print ArrayList size before set, You can check it.
System.out.println(conf1.size());
for(int t=0; t<4; t++){
conf1.set(t, Integer.valueOf(-1));
}
Modify code to use add
for(int t=0; t<4; t++){
conf1.add(-1);
}
your Arraylist objects start out as empty objects. YOu can't call .set() on them at all: Those UPDATE existing entries, they don't make new ones. Try add.
I 'm looking for a way to read a range of elements in an array of unknown dimension ( not length).
The client can send a read request for an object and specify the range to read. The input String could be like this : "1:2:3:2,2:3:1:4" for example. This would mean he wants to read the elements in the range from [1][2][3][2] to [2][3][1][4] of an array.
To read a concrete element I created this function:
public Object readValue(Object obj,int[] positions ) {
Object value = null; //Result
int objDimension = getDimension(obj); //Dimesion of the array
System.out.println("Dimension: " + objDimension );
try {
Object[] aux = (Object[]) obj;
for (int i = 0; i < objDimension - 1; i++) {
int pos = positions[i];
aux = (Object[]) aux[pos];
}
value = aux[positions[objDimension - 1]];
System.out.println("Result: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: Send a fault to the client.
System.out.println("Error: "+e.getMessage());
}
return value;
}
public static int getDimension(Object value) {
Class<?> clazz = value.getClass();
String className = clazz.getName();
int dimension = 0;
for (int i = 0; i < className.length(); i++) {
if (className.charAt(i) != '[') {
dimension = i;
break;
}
}
return dimension;
}
//Example.
public static void main(String[] args) {
// TODO code application logic here
TestMultiDimensioNRead test = new TestMultiDimensioNRead();
Integer[][][][] testSubject = new Integer[5][2][4][];
testSubject[0][0][2] = new Integer[8];
testSubject[0][0][0] = new Integer[15];
testSubject[0][0][1] = new Integer[20];
testSubject[0][0][3] = new Integer[2];
testSubject[1][1][2] = new Integer[7];
testSubject[1][1][2][0] = 80;
test.readValue(testSubject,new int[]{1, 1, 2, 0});
}
I was thinking a good way may be to calculate the differens between each dimension length.
If anyone can come with a good idea, I would really appreciatee.
Thanks in advance.
EDIT 1: The code posted in this question does read the value of a given position in an array of unknown dimension. My problem is to read all the elements that are between to given points. This might not have been clear in the initial question.
You could use a recursive solution:
public class Test {
private class TestMultiDimensioNRead {
public Integer readValue(Object testSubject, int[] coordinates) {
return readValue(testSubject, coordinates, 0);
}
private Integer readValue(Object testSubject, int[] coordinates, int which) {
if (testSubject instanceof Object[]) {
Object[] subject = (Object[]) testSubject;
if (coordinates.length > which + 1) {
return readValue(subject[coordinates[which]], coordinates, which + 1);
} else {
return (Integer) subject[coordinates[which]];
}
} else {
// Throw some sort of exception?
return -1;
}
}
public Iterator<Integer> readValues(Object testSubject, int[] coordinates, int count) {
return readValues(testSubject, coordinates, count, 0);
}
private Iterator<Integer> readValues(Object testSubject, int[] coordinates, int count, int level) {
if (testSubject instanceof Object[]) {
Object[] subject = (Object[]) testSubject;
if (coordinates.length > level + 1) {
return readValues(subject[coordinates[level]], coordinates, count, level + 1);
} else {
return new Iterator<Integer>() {
int i = 0;
Integer[] intSubject = (Integer[]) subject;
#Override
public boolean hasNext() {
return i <= count;
}
#Override
public Integer next() {
return intSubject[coordinates[level] + (i++)];
}
};
}
} else {
// Throw some sort of exception?
return null;
}
}
}
public void test() {
TestMultiDimensioNRead test = new TestMultiDimensioNRead();
Integer[][][][] testSubject = new Integer[5][2][4][];
testSubject[0][0][2] = new Integer[8];
testSubject[0][0][0] = new Integer[15];
testSubject[0][0][1] = new Integer[20];
testSubject[0][0][3] = new Integer[2];
testSubject[1][1][2] = new Integer[7];
testSubject[1][1][2][0] = 80;
testSubject[1][1][2][1] = 79;
testSubject[1][1][2][2] = 78;
Iterator<Integer> them = test.readValues(testSubject, new int[]{1, 1, 2, 0}, 3);
for (Integer x = them.next(); them.hasNext(); x = them.next()) {
System.out.println(x);
}
System.out.println();
}
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
}
Prints 80 as expected.
There's probably more to do in terms of sanity checks but this seems to work.
Found the way to do it, maybe it's helpfull at somepoint for someone.
I didn't include any checks, this is more a test case to see that is works.
public class TestReadMultiDimensionArray {
private int[] startPosition; //Start position.
private int[] endPosition; //End position.
private boolean inRange = false; //If the current position is in range.
private List<Object> result; //List to store the values we find.
public TestReadMultiDimensionArray() {
result = new ArrayList<>();
}
public static void main(String[] args) {
TestReadMultiDimensionArray test = new TestReadMultiDimensionArray();
Integer[][][][] testSubject = new Integer[2][2][4][];
//(0,0,y,z)
testSubject[0][0][0] = new Integer[]{1}; //(0,0,0,0)
testSubject[0][0][1] = new Integer[]{2}; //(0,0,1,0)
testSubject[0][0][2] = new Integer[]{3}; //(0,0,2,0)
testSubject[0][0][3] = new Integer[]{4}; //(0,0,3,0)
//(0,1,y,z)
testSubject[0][1][0] = new Integer[]{5}; //(0,1,0,0)
testSubject[0][1][1] = new Integer[]{6}; //(0,1,1,0)
testSubject[0][1][2] = new Integer[]{7, 8, 9}; //(0,1,2,0) (0,1,2,1) (0,1,2,2)
testSubject[0][1][3] = new Integer[]{10}; //(0,1,3,0)
//(1,0,y,z)
testSubject[1][0][0] = new Integer[]{11, 12}; //(1,0,0,0)..
testSubject[1][0][1] = new Integer[]{13, 14, 15};
testSubject[1][0][2] = new Integer[]{16, 17, 18};
testSubject[1][0][3] = new Integer[]{19, 20, 21}; //..(1,0,3,2)
//(1,1,y,z)
testSubject[1][1][0] = new Integer[]{22, 23}; //(1,1,0,0)..
testSubject[1][1][1] = new Integer[]{24, 25, 26};
testSubject[1][1][2] = new Integer[]{27, 28, 29, 30, 31, 32, 33, 34};
testSubject[1][1][3] = new Integer[]{35, 36}; //..(1,1,3,1)
//Launch the test.
test.readValue(testSubject);
}
/**
*
* #param obj The Array from where we want to get the data.
*/
public void readValue(Object obj) {
//Where should it start.
startPosition = new int[]{0, 1, 0, 0};
//Where should it stop.
endPosition = new int[]{1, 1, 1, 2};
System.out.println("Start Position:" + Arrays.toString(startPosition) + " End Position:" + Arrays.toString(endPosition));
int[] currentPosition = new int[]{-1, -1, -1, -1};
//Call to the method.
testRead((Object[]) obj, 0, currentPosition);
//Result to array.
Object[] arrayToReturn = result.toArray(new Object[0]);
System.out.println("Result: " + Arrays.toString(arrayToReturn));
}
/**
* Recursive method that looks for the values in a multi-dimensional array, in a given range. /!\ No checks are implemented here, wrong input can end in a
* StackOverFlow.
*
* #param obj The array in Object[] form.
* #param currentDimension The dimension we are currently in.
* #param result The reference to the list that will store all the values we found.
* #param currentPosition The current position we are in.
*/
private void testRead(Object[] obj, int currentDimension, int[] currentPosition) {
for (int i = 0; i < obj.length; i++) {
currentPosition[currentDimension] = i;
if (Arrays.equals(startPosition, currentPosition) && currentDimension == (currentPosition.length - 1)) {
//Found the start position.
System.out.println("############ START ############");
inRange = true;
}
if ((i >= startPosition[currentDimension] && i <= endPosition[currentDimension]) || inRange == true) {
//We are in the write track to get to the values we are looking for.
if (obj[i] instanceof Object[]) {
//The data contained in the cell is an array.
testRead((Object[]) obj[i], currentDimension + 1, currentPosition);
} else {
//The data contained in the cell is a scalar. This is what we where looking for.
System.out.println(Arrays.toString(currentPosition) + " Data: " + obj[i]);
result.add(obj[i]);
}
}
if (Arrays.equals(endPosition, currentPosition) && currentDimension == (currentPosition.length - 1)) {
//Found the end position.
System.out.println("############ END ############");
inRange = false;
}
}
}
}
Any question or idea to better the code is welcome.
I have an array that I want to sort in ascending order. However, I want to sort them with reference to a boolean array.I would like to sort the values that are true in ascending order, followed by the values that are false in ascending order.
Little stuck on how to get there.
This is what I have currently:
Object[] arr = new Object[6];
arr[0] = new Object(2);
arr[1] = new Object(5);
arr[2] = new Object(3);
arr[3] = new Object(1);
arr[4] = new Object(6);
arr[5] = new Object(4);
Available[] avalarr = new Available[6];
availarr[0] = new Available (true);
availarr[1] = new Available (false);
availarr[2] = new Available (false);
availarr[3] = new Available (true);
availarr[4] = new Available (true);
availarr[5] = new Available (false);
I need the output to be:
1 2 6 3 4 5
Code:
import java.util.Arrays;
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
Arrays.sort(items);
System.out.println("\n\nAfter Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
}
class Item implements Comparable<Item> {
private int _intValue;
private boolean _boolValue;
public Item(int intValue, boolean boolValue) {
_intValue = intValue;
_boolValue = boolValue;
}
public int getIntValue() { return _intValue; }
public boolean getBoolValue() { return _boolValue; }
#Override
public int compareTo(Item otherItem) {
// Using explicit comparison
int boolComparison = (_boolValue == otherItem._boolValue) ? 0 :
(_boolValue) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (_intValue == otherItem.getIntValue()) ? 0 :
(_intValue > otherItem.getIntValue()) ? 1 : -1);
}
}
Output:
Before Sorting:
2 5 3 1 6 4
After Sorting:
1 2 6 3 4 5
Explanation:
The idea is to let your "Item" implement Comparable, and override the compareTo(Item otherItem) function based on the desired order.
Once that is done, all you need to do is to call Arrays.sort() on your array of Item.
Version 2 (w/o Comparable/Comparator):
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
bubbleSort(items);
System.out.println("\n\nAfter Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
public static void bubbleSort(Item [] items) {
int n = items.length;
do {
int newN = 0;
for(int i = 1; i < n; i++) {
if(compareTo(items[i-1], items[i]) == 1) {
Item temp = items[i-1];
items[i-1] = items[i];
items[i] = temp;
newN = i;
}
}
n = newN;
} while (n != 0);
}
public static int compareTo(Item item1, Item item2) {
int boolComparison = (item1.getBoolValue() == item2.getBoolValue())
? 0 : (item1.getBoolValue()) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (item1.getIntValue() == item2.getIntValue()) ? 0 :
(item1.getIntValue() > item2.getIntValue()) ? 1 : -1);
}
}
(To expand on my comment:
You need a basic "thing":
class Thing {
boolean newAvailable;
int order;
public Thing(boolean newAvailable, int order) {
...
}
}
...and a Comparable...
class CompareThings implements Comparator<Thing> {
...
int compare(Thing t1, Thing t2) {
if (t1.newAvailable!=t2.newAvailable)
return t1.newAvailable==true ? 1 : -1;
return t1.order-t2.order;
}
}
(Note that t1.newAvailable==true is redundant, but I think it clarifies what's going on here.)
Now build an array of Thing and call Arrays.sort(Thing[] things, CompareThings);
I have an arraylist of arraylists, each arraylist within the outer arraylist holds the following values holidayId, country, countryValue, duration, durationValue, accType, accTypeValue, holSubType, holSubTypeValue, weather, weatherValue, pricePP, pricePPValue, recommendationScore. These are all held as objects, I want to know if there is a way to sort the arraylists using the recommendationScore by maybe converting it into a double type and sorting it that way? Or any other way I could approach this problem?
Thanks in advance
public class RecAlgorithmImpl {
public static ArrayList<Double> attRanking(ArrayList<Double> attRank){
ArrayList<Double> attWeight = new ArrayList<>();
double weight;
/*Loops through the rankings given in the questionnaire
* and sets a new number for better recommendation accuracy */
for(int i = 0; i < attRank.size();i++){
if(attRank.get(i) == 1){
attRank.set(i, 7.0);
}
else if(attRank.get(i) == 2){
attRank.set(i, 6.0);
}
else if(attRank.get(i) == 3){
attRank.set(i, 5.0);
}
else if(attRank.get(i) == 4){
attRank.set(i, 4.0);
}
else if(attRank.get(i) == 5){
attRank.set(i, 3.0);
}
else if(attRank.get(i) == 6){
attRank.set(i, 2.0);
}
else if(attRank.get(i) == 0){
attRank.set(i, 1.0);
}
}
//Loop through the ranked values and assign a weighting to each attribute
for(int j = 0; j < attRank.size(); j++){
weight = (attRank.get(j))/28;
attWeight.add(weight);
}
for(int k = 0; k < attWeight.size();k++){
System.out.println(attWeight.get(k));
}
return attWeight;
}
public static ArrayList<ArrayList> valuePoints(ArrayList<ArrayList> valuePoints){
//DataRetrievalImpl database = new DataRetrievalImpl();
ArrayList<ArrayList> holiday = new ArrayList<>();
//test info
ArrayList<String> test = new ArrayList<>();
test.add("stuff1");
test.add("stuff2");
test.add("stuff3");
test.add("stuff4");
test.add("stuff5");
test.add("stuff6");
holiday.add(test);
ArrayList<String> test1 = new ArrayList<>();
test1.add("stuff11");
test1.add("stuff12");
test1.add("stuff13");
test1.add("stuff14");
test1.add("stuff15");
test1.add("stuff16");
holiday.add(test1);
ArrayList<ArrayList> holidayScore = new ArrayList<>(); // creates new arraylist to hold the 6 attributes and their value points to be used in recommendation score
//database information
/*boolean condition = false;
String[] select = null;
String[] from = null;
String[] where = null;
holiday = database.getData(condition, select, from, where);*/
//Loops through the holiday arraylist which contains all the holidays and adds the attributes that we need to the new one along with default points
for(int i = 0; i < holiday.size(); i++){
holidayScore.add(new ArrayList());
holidayScore.get(i).add(holiday.get(i).get(0));
holidayScore.get(i).add("0");
holidayScore.get(i).add(holiday.get(i).get(1));
holidayScore.get(i).add("0");
holidayScore.get(i).add(holiday.get(i).get(2));
holidayScore.get(i).add("0");
holidayScore.get(i).add(holiday.get(i).get(3));
holidayScore.get(i).add("0");
holidayScore.get(i).add(holiday.get(i).get(4));
holidayScore.get(i).add("0");
holidayScore.get(i).add(holiday.get(i).get(5));
holidayScore.get(i).add("0");
}
//Loops through the holidayScore arraylist checking the attributes against the valuePoints array list and
//modifying the value points where the two attribute values are equivalent in both arraylists
//each if statement checks that each attrbute value is equivalent, successful matches record the points from valuePoints into holidayScore
for(int j = 0; j < holidayScore.size(); j++){
if(holidayScore.get(j).get(0) == valuePoints.get(j).get(0)){
holidayScore.get(j).set(1, valuePoints.get(j).get(1));
}
if(holidayScore.get(j).get(2) == valuePoints.get(j).get(2)){
holidayScore.get(j).set(3, valuePoints.get(j).get(3));
}
if(holidayScore.get(j).get(4) == valuePoints.get(j).get(4)){
holidayScore.get(j).set(5, valuePoints.get(j).get(5));
}
if(holidayScore.get(j).get(6) == valuePoints.get(j).get(6)){
holidayScore.get(j).set(7, valuePoints.get(j).get(7));
}
if(holidayScore.get(j).get(8) == valuePoints.get(j).get(8)){
holidayScore.get(j).set(9, valuePoints.get(j).get(9));
}
if(holidayScore.get(j).get(10) == valuePoints.get(j).get(10)){
holidayScore.get(j).set(11, valuePoints.get(j).get(11));
}
}
System.out.println(holiday);
System.out.println("----------------------------------------------------");
System.out.println(holidayScore);
return holidayScore;
}
public static void recommendation(ArrayList<Double> weightedAttr, ArrayList<ArrayList> holidayScores){
//each variable holds the current value points for that attribute value
double countryValue;
double durationValue;
double accTypeValue;
double holSubTypeValue;
double weatherValue;
double pricePPValue;
double recScore;
//Loops through the holidayScores arraylist convert the value points into double which is multiplied by the appropriate attribute weighting
//this gives a decimal score for each attribute which is summed up for the final recommendation score and added to the end of the arraylist
for(int k = 0; k < holidayScores.size(); k++){
countryValue = Double.parseDouble(holidayScores.get(k).get(1).toString());
durationValue = Double.parseDouble(holidayScores.get(k).get(3).toString());
accTypeValue = Double.parseDouble(holidayScores.get(k).get(5).toString());
holSubTypeValue = Double.parseDouble(holidayScores.get(k).get(7).toString());
weatherValue = Double.parseDouble(holidayScores.get(k).get(9).toString());
pricePPValue = Double.parseDouble(holidayScores.get(k).get(11).toString());
recScore = (countryValue * weightedAttr.get(0));
recScore = recScore + (durationValue * weightedAttr.get(1));
recScore = recScore + (accTypeValue * weightedAttr.get(2));
recScore = recScore + (holSubTypeValue * weightedAttr.get(3));
recScore = recScore + (weatherValue * weightedAttr.get(4));
recScore = recScore + (pricePPValue * weightedAttr.get(5));
holidayScores.get(k).add(recScore);
}
System.out.println(holidayScores);
}
}
You should implement an object, that holds all the values in of your arraylist (inner). Then you can easily implement Comparable that checks for the recommendationScore.