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 have this project and im writing the add method for my catalog class and this add method needs to add an item to a sorted array into the right place using insertion sort, unless the array has nothing in it in that case i just want to add it in normally. this whole project must use an array I cannot use an arraylist or anything else.
The problem I am having here is that the way my program currently is, its only adding one object to my array and each time i try to add a new one during run tine it jst replaces the item already in there. I know that my problem is something in the body of my while loop and the way i initialize my position variable.
here is the method im having trouble with.
public void addItem(Item theItem)
{
int position = size;
if(size != 0){
while (position > 0 && theItem.compareTo(items[position - 1]) < 0){
items[position] = items[position - 1];
position--;
}
items[position] = theItem;
}
else{
items[size] = theItem;
size++;
}
here is my compareTo method
public int compareTo(Item other){
if(this.getItemType().equals(other.getItemType())){
return this.itemnum - other.itemnum;
}
//item types are not equal
else
return this.getItemType().compareTo(other.getItemType());
//try writing code to compare by price as well
}
The most likely problem in your code is this line:
items[position-1] = items[position];
This will copy an item in you array from the current position to the position to the left of it.
When you insert a new item you want to copy items from the left to the current position to make room for the new item to the left.
Change it to
items[position] = items[position-1];
A size++ is also missing after the while block, inside the first if block.
I realized this when adding a second call to addItem in my test code below.
You could also put a single size++ statement outside of the if statement.
A Complete, Minimal, Reproducible Example that I used trying to fix it. I have used Integer instead of Item to avoid having to add more classes.
public class Main {
private int size = 0;
private Integer[] items = new Integer[20];
public static void main(String... args) {
new Main().execute(); // Moving us into a non-static context
}
public void execute() {
System.arraycopy(new Integer[] {1,2,3,4,6,7,8,9}, 0, items, 0, 8);
size = 8;
// items = [1,2,3,4,6,7,8,9,null,null,...]
addItem(5);
addItem(5); // test adding a second item
// items = [1,2,3,4,5,6,7,8,9,null,null,...]
for (Integer i : items) {
System.out.println(i);
}
}
public void addItem(Integer item) {
int position = size;
if (size != 0) {
while (position > 0 && item.compareTo(items[position - 1]) < 0) {
// items[position-1] = items[position]; // Result [1,2,3,4,5,null,null,...]
items[position] = items[position-1]; // Result [1,2,3,4,5,6,7,8,9,null,null,...]
position--;
}
items[position] = item;
size++; // this line was missing as well
} else {
items[size] = item;
size++;
}
// or a single size++; here, removing the other two
}
}
The ugly solution by making new array
public int[] addItem(int item, int[] items){
int[] tempArr = new int[items.length + 1];
boolean hasAlready = false;
for(int i = 0 ; i < items.length; i++){
if(hasAlready)tempArr[i + 1] = items[i];
else if(item < items[i]){
tempArr[i] = item;
tempArr[i + 1] = items[i];
hasAlready = true;
}else {
tempArr[i] = items[i];
}
}
//items = tempArr; if items is global variable
return tempArr;
}
One can use existing utility functions, Arrays.binarySearch, and System.arraycopy. Your loop was 1 off.
public void addItem(Item theItem) {
Comparator<Item> comparator = Comparator.comparing(Item::getItemType)
.thenComparingInt(it -> it.itemnum);
int position = Arrays.binarySearch(items, 0, size, theItem, comparator);
// If position >= 0 the item was found (maybe no need to insert?)
if (position < 0) {
position = ~position; // Insert position of not found item
}
System.arraycopy(items, position, items, position + 1, size - position);
items[position] = theItem;
size++;
}
Binary search results in the non-negative index when found, or the negative ~index when not found. Here binary search is done on a subarray from 0 upto size (excluded).
Same as Roger Gustavsson
public class Main {
private int size = 0;
private Integer[] items = new Integer[20];
public static void main(String... args) {
new Main().execute(); // Moving us into a non-static context
}
public void execute() {
System.arraycopy(new Integer[] {1,2,3,4,6,7,8,9}, 0, items, 0, 8);
size = 8;
// items = [1,2,3,4,6,7,8,9,null,null,...]
addItem(5);
// items = [1,2,3,4,5,6,7,8,9,null,null,...]
for (Integer i : items) {
System.out.println(i);
}
}
public void addItem(Integer item) {
if (size == 0) {
items[size] = item;
size++;
return;
}
int position = size;
while (position > 0 && item.compareTo(items[position - 1]) < 0) {
items[position] = items[position - 1];
position--;
}
items[position] = item;
size++;
}
}
on what you are trying to achieve, i think next solution will be starting point from where you can build your own solution depending your specific needs. i have Changed your main method a little bit, and i do not know if your classes implements comparable /Comparator or not.
public void addItem(Item theItem) {
int position = position(items, theItem); // position is a method that finds best position for inseriton
if (items[position] == null){ // if items at best position is null then add new element there
items[position] = theItem;
} else{
items[size] = theItem; // if not add element at last position
swapUp(size); // and swap them up to perfect position.
}
size++;
}
method that find best position looks like this.
private static int position(Item[] items, Item newItem) {
if (isEmpty(items))
return 0;
int pos=0;
int target=items.length-1;
while(pos < target){
int m = pos+(target-pos)/2;
if (items[m] !=null){
if(newItem.getNumber()>items[m].getNumber()){ // comparing depending on item number
pos=m+1;
}else{
target=m;
}
}else{
target = m;
}
}
return pos;
}
as you can see method is looking for position depending on item number, you can change this with your type, or do both type and number comparison. Swaping up is handled by thus 2 method.
private void swapUp(int lastPosition){
if (lastPosition == -1){
return;
}
Item lastItem = items[lastPosition];
Item p = items[lastPosition-1];
if (lastItem.getNumber() < p.getNumber())
replace(lastPosition, lastPosition-1);
else
lastPosition = 0;
swapUp(lastPosition-1);
}
private void replace(int from, int to){
Item temporary = items[from];
items[from] = items[to];
items[to] = temporary;
}
and again i'm doing comparison of numbers you can implement any kind of comparison you want. i saw your previous question and modeled your classes
Music{number=1111, name='White and Nerdy', price=2.5, pro='"Weird Al" Yankovic'}
Music{number=2222, name='Amish Paradise', price=2.22, pro='"Weird Al" Yankovic'}
Music{number=3333, name='The Saga Begins', price=2.0, pro='"Weird Al" Yankovic'}
Movie{number=4444, name='UHF', price=9.99, pro='"Weird Al" Yankovic'}
Movie{number=5555, name='The Dark Crystal', price=8.99, pro='"Jim Henson'}
Movie{number=6666, name='Die Hard', price=13.99, pro='Bruce Willis'}
Movie{number=6969, name='The Adventures of Mr. Winky', price=9.99, pro='Richard Dickinson'}
Book{number=7777, name='When I Grow Up', price=7.98, pro='"Weird Al" Yankovic'}
Book{number=8888, name='The Chronicles of Pern: First Fall', price=5.99, pro='"Anne McCaffrey'}
Book{number=9999, name='Get gud you scrub', price=2.5, pro='Steve "Troll" Rathier'}
as you can see they are in sorted order.
For a school project i have a list of 50k containers that arrive on a boat.
These containers need to be sorted in a list in such a way that the earliest departure DateTimes are at the top and the containers above those above them.
This list then gets used for a crane that picks them up in order.
I started out with 2 Collection.sort() methods:
1st one to get them in the right X>Y>Z order
Collections.sort(containers, new Comparator<ContainerData>()
{
#Override
public int compare(ContainerData contData1, ContainerData contData2)
{
return positionSort(contData1.getLocation(),contData2.getLocation());
}
});
Then another one to reorder the dates while keeping the position in mind:
Collections.sort(containers, new Comparator<ContainerData>()
{
#Override
public int compare(ContainerData contData1, ContainerData contData2)
{
int c = contData1.getLeaveDateTimeFrom().compareTo(contData2.getLeaveDateTimeFrom());
int p = positionSort2(contData1.getLocation(), contData2.getLocation());
if(p != 0)
c = p;
return c;
}
});
But i never got this method to work..
What i got working now is rather quick and dirty and takes a long time to process (50seconds for all 50k):
First a sort on DateTime:
Collections.sort(containers, new Comparator<ContainerData>()
{
#Override
public int compare(ContainerData contData1, ContainerData contData2)
{
return contData1.getLeaveDateTimeFrom().compareTo(contData2.getLeaveDateTimeFrom());
}
});
Then a correction function that bumps top containers up:
containers = stackCorrection(containers);
private static List<ContainerData> stackCorrection(List<ContainerData> sortedContainerList)
{
for(int i = 0; i < sortedContainerList.size(); i++)
{
ContainerData current = sortedContainerList.get(i);
// 5 = Max Stack (0 index)
if(current.getLocation().getZ() < 5)
{ //Loop through possible containers above current
for(int j = 5; j > current.getLocation().getZ(); --j)
{ //Search for container above
for(int k = i + 1; k < sortedContainerList.size(); ++k)
if(sortedContainerList.get(k).getLocation().getX() == current.getLocation().getX())
{
if(sortedContainerList.get(k).getLocation().getY() == current.getLocation().getY())
{
if(sortedContainerList.get(k).getLocation().getZ() == j)
{ //Found -> move container above current
sortedContainerList.add(i, sortedContainerList.remove(k));
k = sortedContainerList.size();
i++;
}
}
}
}
}
}
return sortedContainerList;
}
I would like to implement this in a better/faster way. So any hints are appreciated. :)
I think you probably want to sort with a single Comparator that compares on all of the criteria. E.g.:
compareTo(other)
positionComparison = this.position.compareTo(other.position)
if positionComparison != 0
return positionComparison
return this.departureTime.compareTo(other.departureTime)