I'm trying obtain all the names from one file and all the attendances from another then calculate the average attendance. I know the att bit in the calculation is completely wrong but I could not work it out.
{
ArrayList<Match> ourList = new ArrayList(teams);
ArrayList<Match> teamsAttendance = new ArrayList<Match>();
for (Match att : ourList)
{
if (att != null && att.getTeamName().equals(team.getName()))
{
teamsAttendance.add(att);
}
}
double attendance = 0; //start attendance as 0
for (int i = 0; i < att.length; i++)
{
attendance += att[i];
}
return attendance / att.length;
}
I am guessing that the Match class will have a team name and attendance(an array list). Just like getting the team name, there should be a get to get the attendance array list .Assuming this you can try the below approach:
{
ArrayList<Match> ourList = new ArrayList(teams);
ArrayList<Match> teamsAttendance = new ArrayList<Match>();
//to store the attendance mean for each team
ArrayList<double> teamAttendanceMean = new ArrayList<double>();
//to store the attendance values of team
ArrayList<double> tempAttendance= new ArrayList<double>();
//declare outside
double attendance = 0;
for (Match att : ourList)
{
if (att != null && att.getTeamName().equals(team.getName()))
{
teamsAttendance.add(att);
}
attendance = 0;// assign 0
tempAttendance = att.getTeamAttendance();
for (int i = 0; i < tempAttendance.size(); i++)
{
attendance += tempAttendance [i];
}
//storing the mean value
teamAttendanceMean.add(attendance/tempAttendance.size());
}
}
Let me know if any of my assumptions are wrong and also post information on the Match class if so.
Related
I am looking to separate a single array into separate arrays based on gaps in the key. For example take this scenario:
I'm attempting to create separate datasets (arrays) for consecutive days of the month. If a day is missed a new dataset needs to be created starting with the next day that has a value.
The data is retrieved in one array like so:
[1:10, 2:8, 4:5, 5:12, 8:6, 9:10, 10:5, 11:4, 13:6, 14:5]
I would like to output:
[1:10, 2:8], [4:5, 5:12], [8:6, 9:10, 10:5, 11:4], [13:6, 14:5]
How would I achieve this?
I currently have this:
ArrayList<Entry> allValues = new ArrayList<>();
// Data Retrieval from the Server is Here (hidden for privacy)
// Each data entry contains key and value
// This is converted into a data model "Entry" which is essentially an x & y coordinate ( Entry(x,y) )
// and then added to the allValues List
List<ArrayList<Entry>> rawDataSets = new ArrayList<>();
ArrayList<Entry> tempDataSet = new ArrayList<>();
for(int i = 0; i < allValues.size(); i++){
Entry tempEntry = allValues.get(i);
if(i == tempEntry.getX()){
tempDataSet.add(tempEntry);
}else{
if(tempDataSet.size() > 0) {
rawDataSets.add(tempDataSet);
tempDataSet.clear();
}
}
}
Something like this should do trick:
ArrayList<Entry> allValues = new ArrayList<>();
// Assuming at this point that `allValues` is sorted in ascending order by X values.
// If necessary, it can be sorted with
//
// Collections.sort(allValues, Comparator.comparing(Entry::getX));
//
List<ArrayList<Entry>> rawDataSets = new ArrayList<>();
ArrayList<Entry> tempDataSet = new ArrayList<>();
for (Entry tempEntry : allValues){
if (!tempDataSet.isEmpty() &&
tempEntry.getX() != tempDataSet.get(tempDataSet.size()-1).getX() + 1)
{
// tempDataSet is not empty, and tempEntry's X is not
// consecutive with the X of tempDataSet's last entry, so it's
// it's time finish with the current tempDataSet and start fresh
// with a new one.
rawDataSets.add(tempDataSet);
tempDataSet = new ArrayList<>();
}
// Regardless of what happened, or didn't happen, with tempDataSet above,
// the current allValues entry now belongs with the current tempDataSet
tempDataSet.add(tempEntry);
}
// Now add any final non-empty tempDataSet (there will always be one if
// allValues wasn't empty) onto rawDataSets
if (!tempDataSet.isEmpty()) {
rawDataSets.add(tempDataSet);
}
After a number of attempts I think I found the solution, although I'm not sure if this is the most effective:
List<ArrayList<Entry>> rawDataSets = new ArrayList<>();
ArrayList<Entry> tempDataSet = new ArrayList<>();
for(int i = 0; i <= allValues.get(allValues.size() - 1).getX(); i++){
int matchedIndex = -1;
for(int j = 0; j < allValues.size(); j++){
if(allValues.get(j).getX() == i){
matchedIndex = j;
}
}
if(matchedIndex != -1) {
Entry tempEntry = allValues.get(matchedIndex);
tempDataSet.add(tempEntry);
} else {
if (tempDataSet.size() > 0) {
rawDataSets.add(tempDataSet);
tempDataSet = new ArrayList<>();
}
}
}
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.
So, I made this code almost work, but I want to use insertion sort on the array and for the output to display results sorted by product ID only by insertion sort. Each product ID should have the same corresponding number of units. The units should not be sorted independently. The only order would be by product ID is what I'm basically implying.
import java.util.*;
import java.io.*;
class newversion {
public static int [][] table; // the output table
public static int numOfRows; //number of rows used up in the table
public static int lookfor(int productID){
int location = -1; //-1 an error
for(int i = 0; i < numOfRows; i++){
if (table[i][0] == productID){
location = i;
}
}
return location;
}
/*
here is my modified bubble sort code. I based it on this, but done differently:
http://stackoverflow.com/questions/23283655/bubble-sort-on-2d-array-java
public static void swap(int int1, int int2, int[] array) {
if(int1 == int2){
return;
}
else{
int temp = int2;
array[int2] = array[int1];
array[int2] = temp;
}
}
but it didn't work and I had to try something else
*/
public static boolean contains(int productID){
if (lookfor(productID) == -1){
return false;
}
return true;
}
public static void main(String[] args) {
File file = null;
Scanner scanner = null;
try{
file = new File("data.csv");
scanner = new Scanner( file );
}
catch(Exception e){
System.out.println("Error opening file!");
System.exit(1);
}
//citation of idea for sorting method in 2D array: http://stackoverflow.com/questions/23283655/bubble-sort-on-2d-array-java
//I'm using bubble sort on a 2D array
//this is his code
/*
private static void bubblesort(Integer[] array) {
for (int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length - 1; j++) {
if(array[j].compareTo(array[j+1]) > 0) {
swap(j, j+1, array);
}
}
}
}
private static void swap(Integer int1, Integer int2, Integer[] array) {
if(int1 == int2)return;
Integer temp = new Integer(array[int2]);
array[index2] = array[int1];
array[int1] = temp;
}
*/
//here's my idea for bubble sort on a 2D array
/*
for (int i = 0; i < numOfRows; i++){
for(int j = 0; j < numOfRows - 1; j++) {
if(table[j][0].compareTo(array[j+1][0]) > 0) {
swap(j, j+1, table);
}
}
//this didn't work well either
//Now, I have to try another for-loop
*/
//Count the number of lines in the file
int size_of_file = 0;
while (scanner.hasNextLine()){
scanner.nextLine();
size_of_file++;
}
table = new int[size_of_file][2];
//reset scanner
try{
file = new File("data.csv");
scanner = new Scanner( file );
}
catch(Exception e){
System.out.println("Error opening file!");
System.exit(1);
}
//save the title
String titleLine = scanner.nextLine();
System.out.println(titleLine);
//for each line in the file, store and total it.
numOfRows=0;
while (scanner.hasNextLine()){
String ln = scanner.nextLine();
String[] row = ln.split(",");
System.out.println(row[0] + ", " + row[1]);
if (contains(Integer.parseInt(row[0]))){
//This is the location in the table where the product id exists already.
int location = lookfor(Integer.parseInt(row[0]));
//add the units to what we have in the table
table[location][1] += Integer.parseInt(row[1]);
}
else{
table[numOfRows][0]= Integer.parseInt(row[0]);
table[numOfRows][1]= Integer.parseInt(row[1]);
numOfRows++;
}
}
//output
try{
PrintWriter output = new PrintWriter("output.csv");
output.println(titleLine);
for(int i=0;i<numOfRows;i++){
output.println(table[i][0] + "," + table[i][1]);
}
output.close();
}
catch(Exception e){
System.out.println("Error writing file");
}
}
}
I want to understand how to use FileReader better. I read a little bit about it here:
https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html
https://bytes.com/topic/java/answers/585814-reading-data-into-array-file
Although I don't think I understand from that how to store it into an array. Could someone explain how I can store values from FileReader class into an array? I want it in a 2D array where the number of rows is just however many product IDs I have and there is always 2 columns.
Excel File to read from:
Product ID Units
10002 4
10004 6
10008 2
10010 3
10010 3
output I get right now:
Product ID Units
10002 20
10004 72
10008 12
10010 37
10007 28
20003 42
30019 56
30020 29
10006 36
20005 32
etc.
I apologize if this update should be posted as a different question. Let me know so I can go by community standards. The piece of output I posted, you'll notice isn't sorted by productID. That's the last thing I want to do. Other than that, it basically works. I am apologizing in case someone wants to vote me down for not posting the answer, since technically it would be the same answer to the initial question. If this update should be a different thread, again, let me know and I'll make the edit.
Why this is not working? I am looping on a trxFifoArray List and passing its object items to result List. I need to split some amounts in 2 so I need to addFirst this 2 amount to result list. The amounts are in an arrayList [-9.0000, -6.0000]. So I loop the amount list to do the addFirst on result and the items are added but with same amount even the list has 2 different amount.
LinkedList<InvtQaTracer> trxFifoArray = new LinkedList<InvtQaTracer>();
LinkedList<InvtQaTracer> result = new LinkedList<InvtQaTracer>();
InvtQaTracer trx = new InvtQaTracer();
int trxDocoRef = 0;
for (int j = list.size() - 1; j >= 0; j--) {
trx = list.get(j);
System.out.printf("%12.4f %4s%10d %12s%n", trx.getTrxQty(), trx.getDocType(), trx.getOrdNo(), trx.getLocNo());
List<BigDecimal> auxAmounts = new ArrayList<BigDecimal>();
if (trx.getDocType().compareTo("OV") == 0
|| trx.getDocType().compareTo("XV") == 0) {
//Do something ...
} else {
BigDecimal auxAmount = BigDecimal.ZERO;
Boolean needRemove = false;
for (InvtQaTracer tFifo : trxFifoArray) {
if (trx.getDocType().compareTo("IT") == 0) {
auxAmounts.add(tFifo.getTrxQty().negate());
}
}
if (needRemove) {
Iterator<InvtQaTracer> iterator = trxFifoArray.iterator();
int count = 0;
while (iterator.hasNext()) {
InvtQaTracer iqt = iterator.next();
if (iqt.getTrxQty().compareTo(BigDecimal.ZERO) == 0) {
count++;
iterator.remove();
}
}
}
}
if (!auxAmounts.isEmpty()) {
for (BigDecimal asss : auxAmounts) {
System.out.println(asss);
trx.setTrxQty(asss);
result.addFirst(trx);
}
} else {
result.addFirst(trx);
}
for (InvtQaTracer invtQT : trxFifoArray) {
System.out.printf("%20s%2s%12.4f %10d %12s%10d%n", " ----------------> ", invtQT.getDocType(), invtQT.getTrxQty(), invtQT.getOrdNo(), invtQT.getLocNo(), invtQT.getDocNo());
}
}
This code add two records with -6.000000 value even it is printing out both of them. I hope you understand the code. Please Help!!!
Thanks.
Thanks for any help!
Am finding a problem in the code.
Code needs to be updated like this
if (!auxAmounts.isEmpty()) {
LinkedList<InvtQaTracer> result = new LinkedList<InvtQaTracer>();
//Updated Here
InvtQaTracer trx = null;
List<BigDecimal> auxAmounts = new ArrayList<BigDecimal>(); //[-9.000000, -6.000000]
for (BigDecimal asss : auxAmounts) {
System.out.println(asss);
//Updated Here
trx = new InvtQaTracer();
trx.setTrxQty(asss);
result.addFirst(trx);
}
} else {
result.addFirst(trx);
}
One more change identified is
inside the else loop needRemove value is set to false by default and below checking whether it is true in if loop. think this one can be removed.
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.