Below I have provided my example of selection sort code, which if possible I want to convert to merge sort (I am using a linked-list as my data type):
public void sortRawDataRepository() {
for (int i = 0; i < rawDataRepository.size(); i++) {
for (int j = i + 1; j < rawDataRepository.size(); j++) {
Date iDate = rawDataRepository.get(i).getProductionDate();
Date jDate = rawDataRepository.get(j).getProductionDate();
if (iDate.getTime() > jDate.getTime()) {
Item tmp = rawDataRepository.get(i);
rawDataRepository.set(i, rawDataRepository.get(j));
rawDataRepository.set(j, tmp);
}
}
}
}
Related
I have two 2d boolean arrays, the smaller array (shape) is going over the larger array (world).
I am having trouble to find a method to find out when the smaller array can "fit" into the larger one.
When I run the code it either just goes through the larger array, never stopping, or stops after one step (incorrectly).
public void solve() {
ArrayList<Boolean> worldList=new ArrayList<>();
ArrayList<Boolean> shapeList=new ArrayList<>();
for (int i = 0; i < world.length; i++) {
for (int k = 0; k < world[i].length; k++) {
worldList.add(world[i][k]);
display(i, k, Orientation.ROTATE_NONE);
for (int j = 0; j < shape.length; j++) {
for (int l = 0; l < shape[j].length; l++) {
shapeList.add(shape[j][l]);
if(shapeList.equals(worldList)) {
return;
}
}
}
}
}
}
A good place to start with a problem like this is brute force for the simplest case. So, for each index in the world list, just check to see if every following index of world and shapes match.
Notice we only iterate to world.size()-shapes.size(), because naturally if shapes is longer than the portion of world we haven't checked, it won't fit.
import java.util.ArrayList;
public class Test {
ArrayList<Boolean> world = new ArrayList<>();
ArrayList<Boolean> shapes = new ArrayList<>();
public static void main(String[] args) {
new Work();
}
public Test() {
world.add(true);
world.add(false);
world.add(false);
world.add(true);
shapes.add(false);
shapes.add(true);
// Arraylists initialized to these values:
// world: T F F T
// shapes: F T
System.out.println(getFitIndex());
}
/**
* Get the index of the fit, -1 if it won't fit.
* #return
*/
public int getFitIndex() {
for (int w = 0; w <= world.size()-shapes.size(); w++) {
boolean fits = true;
for (int s = 0; s < shapes.size(); s++) {
System.out.println("Compare shapes[" + s + "] and world["+ (w+s) + "]: " +
shapes.get(s).equals(world.get(w+s)));
if (!shapes.get(s).equals(world.get(w+s))) fits = false;
}
System.out.println();
if (fits) return w;
}
return -1;
}
}
When we run this code, we get a value of 2 printed to the console, since shapes does indeed fit inside world, starting at world[2].
You can find the row and column of fitting like this
public void fit() {
int h = world.length - shape.length;
int w = world[0].length - shape[0].length;
for (int i = 0; i <= h; i++) {
for (int k = 0; k <= w; k++) {
boolean found = true;
for (int j = 0; j < shape.length && found; j++) {
for (int l = 0; l < shape[j].length && found; l++) {
if (shape[j][l] != world[i + j][k + l])
found = false;
}
}
if (found) {
//Your shape list fit the world list at starting index (i, k)
//You can for example save the i, k variable in instance variable
//Or return then as an object for further use
return;
}
}
}
I have a List called listTeams which comprises of Strings. I need to generate all unique combinations of these strings and store them in another ArrayList called lines. I've tried the following but the results are not desirable:
for(int i=0; i<listTeams.size();i++){
for(int j=1;j<listTeams.size();j++){
if (listTeams.get(j).equals(listTeams.get(i)))
continue;
for(int k=2;k<listTeams.size();k++){
if (listTeams.get(k).equals(listTeams.get(i)) || listTeams.get(k).equals(listTeams.get(j)))
continue;
String str = listTeams.get(i)+listTeams.get(j)+listTeams.get(k);
lines.put(str,new ArrayList<String>());
}
}
}
Here's the original list : {"A","B","C","D"}
What I am getting is
a_b_c
a_b_d
a_c_d
a_d_c
b_c_d
b_d_c
c_b_d
d_b_c
What I desire is:
a_b_c
a_b_d
a_c_d
b_c_d
for(int i=0; i<listTeams.size();i++){
for(int j=i+1;j<listTeams.size();j++){
for(int k=j+1;k<listTeams.size();k++){
String str = listTeams.get(i)+listTeams.get(j)+listTeams.get(k);
lines.put(str,new ArrayList<String>());
}
}
}
You need to modify your for loops like this:
for (int j = i;
and
for (int k = j;
So that only unique combinations appear
As #Berger said, the following code is working as you expect.
for (int i = 0; i < listTeams.size(); i++) {
for (int j = i+1; j < listTeams.size(); j++) {
if (listTeams.get(j).equals(listTeams.get(i)))
continue;
for (int k = j+1; k < listTeams.size(); k++) {
if (listTeams.get(k).equals(listTeams.get(i)) || listTeams.get(k).equals(listTeams.get(j)))
continue;
String str = listTeams.get(i) + listTeams.get(j) + listTeams.get(k);
lines.add(str);
}
}
}
for (int i = 0; i < newBookCatalog.length; i++) {
double currentMin = newBookCatalog[i].getPrice();
int currentMinIndex = i;
for (int j = i + 1; j < newBookCatalog.length; j++) {
if (currentMin > newBookCatalog[j].getPrice()) {
currentMin = newBookCatalog[j].getPrice();
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
BookCatalog2 temp = newBookCatalog[currentMinIndex];
newBookCatalog[currentMinIndex] = newBookCatalog[i];
newBookCatalog[i] = temp;
}
}
//Display the newly sorted array of objects
for (int i = 0; i < newBookCatalog.length - 1; i++) {
System.out.printf("%-8d%-20s%-19s%-18.2f\n", newBookCatalog[i].getItemNumber(), newBookCatalog[i].getProduct(), newBookCatalog[i].getCategory(), newBookCatalog[i].getPrice());
}
break;
This is what i have so far. I'm trying to sort the array by increasing price but when the program runs, it shows all but the last item. I reworked it a few times but i cannot get the sort to show the last item. i'm beginner level and copied the basic structure of the sort from my text book and help from my instructor. The example in my textbook was just for an array of int though. so this was a little bit more complicated.
Any tips or tricks?
I reworked it a few times but i cannot get the sort to show the last
item.
you're excluding the last item by doing newBookCatalog.length-1 rather it should be i < newBookCatalog.length.
change this:
for (int i = 0; i < newBookCatalog.length-1; i++)
to this:
for (int i = 0; i < newBookCatalog.length; i++)
My title isn't the best but i haven't any other ideas. I have one List of objects with a List categories parameter and one String. The String is something like: "action,azione adventure,avventura horror sport ". I have to split it with spaces to obtain an array of strings like: ["action,azione", "adventure,avventura", "horror", "sport"].
I have to remove an item from the List of objects if his List categories item isn't contained in the array of String.
I know that it could sound tricky so i'll make some example:
Array: ["action,azione", "adventure,avventura", "horror", "sport"]
List categories (of the actual List object): ["action", "adventure", "horror", "comic", "sport"] remain
Array: ["action,azione", "adventure,avventura", "horror", "sport"]
List categories (of the actual List object): ["azione", "horror", "comico", "sport"] delete because adventure categories isn't there
Here is my try:
listaManga.getManga() is the List of objects
listaManga.getManga().get(index).getC() is the List of categories of that object
String[] categories is the String splitted in spaces
String[] categories = MainActivity.categories.split(" ");
for (int i = 0; i < listaManga.getManga().size(); i++) {
for (int j = 0; j < categories.length; j++) {
for (int z = 0; z < listaManga.getManga().get(i).getC().size(); z++) {
if (!categories[j].contains(String.valueOf(listaManga.getManga().get(i).getC().get(z)))) {
listaManga.getManga().remove(i);
break;
}
}
}
}
It throws IndexOutOfBoundsException on j value.
See if the following works.
String[] categories = MainActivity.categories.split(" ");
boolean found = false;
for (int i = (listaManga.getManga().size() - 1); i >= 0; i--) {
found = false;
for (int j = (categories.length - 1); j >= 0; j--) {
for (int z = (listaManga.getManga().get(i).getC().size() - 1); z >= 0; z--) {
if (!categories[j].contains(String.valueOf(listaManga.getManga().get(i).getC().get(z)))) {
listaManga.getManga().remove(i);
// Either do this
// i = i - 1;
// or put a flag here that is
// found == true;
break;
}
//if(found == true){
// break;
//}
}
}
}
I finally solved it following the inverse loop cycle idea but i had to change the code of muasif80 cause his code take to an issue:
It can get right categories only if in listaManga.getManga().get(i).getC() there aren't more categories. I'll make an example: if i have ["comic", "adventure"] as String[] categories, it will find all list item with ["comic", "adventure"] categories but not also item with more other categories like: ["comic", "adventure", "horror"].
I did it setting a new String to check every possibility:
String is_contained = "";
String[] categories = MainActivity.categories.split(" ");
for (int i = (listaManga.getManga().size() - 1); i >= 0; i--) {
if(listaManga.getManga().get(i).getC().size()==0){
listaManga.getManga().remove(i);
} else {
for (int j = (categories.length - 1); j >= 0; j--) {
is_contained = "";
for (int z = (listaManga.getManga().get(i).getC().size() - 1); z >= 0; z--) {
if (!categories[j].toLowerCase().contains((String.valueOf(listaManga.getManga().get(i).getC().get(z))).toLowerCase())) {
is_contained += "a";
} else {
is_contained += "b";
}
}
if (!is_contained.toLowerCase().contains(("b").toLowerCase())) {
listaManga.getManga().remove(i);
break;
}
}
}
}
P.s. Also if this is the most correct answer, i'll accept the one of muasif80 for all the time that he dedicated to me in chat!
how would I increment the key [i] by 1 in this situation every time I run through this for loop with the way I currently have it set up all the elements only get mapped to 1. I am trying to find out how many times each number occurs. I have tried +1 in the empty spot after list.get(i) but again only maps each element to 1. thank you.
List<Integer> list = new ArrayList<Integer>();
HashMap<Integer,Integer> Mode = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
list.add(arr[i][j]);
}
}
System.out.println(list);
int count = 1;
for(int i = 0; i < list.size(); i ++) {
Mode.put(list.get(i), );
You need to specify a Key here.
for(int i = 0; i < list.size(); i++) {
int value=list.get(i);
if(!Mode.containsKey(value))
Mode.put(value,1);
else
Mode.put(value,Mode.get(value)+1);
}
According to your comment,
for(int i = 0; i < list.size(); i ++) {
if(Mode.containsKey(list.get(i)) ){
Integer count = Mode.get(list.get(i));
Mode.put(list.get(i), ++count);}
else
Mode.put(list.get(i), 1);
If you have the option, you may find it easier to use something like Multiset from Guava.
Multiset<Integer> seen = HashMultiset.create();
for (int[] row : arr) {
for (int elem : row) {
seen.add(elem); // none of that nasty dealing with the Map
}
}
// you can look up the count of an element with seen.count(elem)
E mostCommon = null;
int highestCount = 0;
for (Multiset.Entry<Integer> entry : seen.entrySet()) {
if (entry.getCount() > highestCount) {
mostCommon = entry.getElement();
highestCount = entry.getCount();
}
}
return mostCommon; // this is the most common element