I am having problems on my insert method. When I go to add a number that needs to be swapped, I get an index out of bounds exception. here: Collections.swap(table, table.get(parent), table.get(child)); This is how I am adding to the heap. tHeap.insert(14); Thanks for any help.
public class Heap {
private ArrayList<Integer> table;
public Heap() {
table = new ArrayList<Integer>();
}
public void insert(Integer toInsert) {
table.add(toInsert);
int child = table.size() - 1;
int parent = (child - 1) / 2;
//TextIO.putln("1 " + parent + " " + toInsert + " " + child);
while (parent >= 0 && table.get(parent) > table.get(child)) {
TextIO.putln("Swapping: " + parent + " Parent for Child: " + child);
Collections.swap(table, table.get(parent), table.get(child));
}
}
public void printTable() {
for (int i = 0; i < table.size(); i++) {
TextIO.putln("Index: " + i + " Data: " + table.get(i));
}
}
}
I think you mean Collections.swap(table, parent, child);? ArrayList.get will return the element at an index (Java ArrayList API) Collections.swap swaps the elements at an index (Java Collections API). You want to be passing in the indices, not the values at the indices. Also I think in your while loop you may want to be updating child and parent.
Related
I am using ControlsFX for CheckTreeView. I have lots of elements in CheckTreeView and i dont want to traverse through all the elements in this tree ( because it takes lots of time due to number of elements in the tree). Is there a method like checkTreeView.getLastUncheckedItem(); to get the last unchecked one.
Currently I am checking the number of elements that checked and comparing it with counter.
If (CountPrev > Count){
//Something Unchecked Do Stuff
}
But again, i cant find what is unchecked without traverse through all elements.
EDIT:
When user checks an item on CheckTreeView, I get that item by
String lastCheckedItem = checkTreeView.getCheckModel().
getCheckedItems().get(treeView.getCheckModel().getCheckedItems().size()-1).toString();
Now I need something like this for the unchecked item
Take a ArrayList 'allItem' and Store all TreeItems, then
after Store selected item in ObservableList 'Selecteditems' using
getCheckedItems() method, Now remove selected item in ArrayList like
below code:
Here allTreeItems is a CheckBoxTreeItem
List<String> allItem = new ArrayList<>();
for (int j = 0; j < allTreeItems.getValue().length(); j++) {
allItem.add(allTreeItems.getChildren().get(j).getValue());
}
if (CountPrev > Count) {
ObservableList<TreeItem<String>> Selecteditems = checkTreeView.getCheckModel().getCheckedItems();
allItem.remove(Selecteditems);
System.out.println("UnChecked Item :" + allItem);
for (int k = 0; k < allItem.size(); k++) {
System.out.println(allItem.get(k));
}
}
Guys thank you so much for your help!
I've accepted Calips' answer because of time and effort he gave for my question.
This is what I've been looking for:
checkTreeView.getCheckModel().getCheckedItems().addListener(new ListChangeListener<TreeItem<String>>() {
#Override public void onChanged(ListChangeListener.Change<? extends TreeItem<String>> change) {
updateText(checkedItemsLabel, change.getList());
while (change.next()) {
System.out.println("============================================");
System.out.println("Change: " + change);
System.out.println("Added sublist " + change.getAddedSubList());
System.out.println("Removed sublist " + change.getRemoved());
System.out.println("List " + change.getList());
System.out.println("Added " + change.wasAdded() + " Permutated " + change.wasPermutated() + " Removed " + change.wasRemoved() + " Replaced "
+ change.wasReplaced() + " Updated " + change.wasUpdated());
System.out.println("============================================");
}
}
});
Resource:
https://github.com/jinghai/controlsfx/blob/master/controlsfx-samples/src/main/java/org/controlsfx/samples/checked/HelloCheckTreeView.java
Stack<YourClassOfTheCheckModel> recentlyUnchcked = new Stack<YourClassOfTheCheckModel>();
yourTreeView.getSelectionModel().
selectedItemProperty().addListener( new ChangeListener() {
#Override
public void changed(ObservableValue observable, Object oldValue,
Object newValue) {
TreeItem<YourClassOfTheCheckModel> selectedItem =
(TreeItem<YourClassOfTheCheckModel>) newValue;
CheckModel checkModel = checkTreeView.getCheckModel().
bool checked = checkModel.isChecked (selectedItem);
if(checked==false){
recentlyUnchcked.push(yourObjectOfTheCheckModel);
}
}
});
Hope this will help or give you an idea though i don't know if this will work (code not tested, have no IDE right now).
I currently have a Red-Black created in Java using the java.util.TreeSet Class. I need to be able to find the height of the Red-Black Tree but I am not sure how to with the Java TreeSet class. I have seen some uses of Recursion but I am not sure how to work this with the TreeSet Class.
Here is my code so far:
import java.util.TreeSet;
import java.util.Random;
public class BinarySearchTreeTest<E extends Comparable<Integer>>{
static Random randomGenerator = new Random();
public static int randomEven(){
int randomEven = randomGenerator.nextInt(50000000);
randomEven = randomEven * 2;
return randomEven;
}
public static int randomOdd(){
int randomOdd = randomGenerator.nextInt(49999999);
randomOdd = randomOdd * 2 + 1;
return randomOdd;
}
public static void main(String[] args) {
TreeSet<Item> RedBlackTree = new TreeSet<Item>();
int[] randomArray = new int[100000];
int inserts = 0;
while(inserts != randomArray.length-1) {
int randomInt = randomEven();
boolean found = false;
for(int j = 0; j < randomArray.length; j++) {
if (randomInt == randomArray[j]) {
System.out.println("Duplicate Found: " + randomInt + " at " + inserts);
found = true;
break;
}
}
if(!found) {
randomArray[inserts] = randomInt;
++inserts;
}
}
//Adds all 100000 values to the Red Black Tree, and stores the number of comparisons
for (int i = 0; i < randomArray.length; i++){
Item randomItem = new Item(randomArray[i]);
RedBlackTree.add(randomItem);
}
long RedBlackTreeComparison = Item.getCompCount();
Item.resetCompCount();
System.out.println("Red Black Tree:");
//String treeOutput = RedBlackTree.toString();
//System.out.println(treeOutput);
System.out.print("\n");
System.out.println("Height: N/A " + " " + "Number of Comparisons: " + RedBlackTreeComparison);
System.out.println("Contains " + doesContain + " : " + RedBlackTree.contains(doesContain) + " " + "Number of Comparisons: " + Item.getCompCount());
System.out.print("\n");
Item.resetCompCount();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public class Person {
private String name;
private boolean adopted;
private String parent;
private List<String> children;
public Person(String Aname) {
name = Aname;
children = new ArrayList<String>();
adopted = false;
}
public void adopt(Person person) {
if (!person.adopted && !person.name.equals(name)
&& children.size() <= 10) {
person.parent = name;
// System.out.println(parent);
// children=person.name;
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
// System.out.println(children);
adopted = true;
}
}
public void setName(String name) {
this.name = name;
}
public void disown(Person person) {
}
public String toString() {
if (children.size() == 0 && parent == null) {
return name + " Parent: No parent. Children: No children ";
} else if (children.size() == 0) {
return name + " Parent: " + parent + " Children: No children";
} else if (parent == null) {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: No Parent " + "Children: " + list;
} else {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: " + parent + " Children: " + list;
}
}
}
In this I am trying to add person.name to arraylist children but I am not able to add. I am initialyzing the list then adding a name to the list.I am using adopt method to add children to the list. Please tell what am I doing wrong here.
The properties are private, please put setters and getters and then try to access to the getName() property.
The following code is incorrect:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
Each time you call Adopt(person) you add that child instead of all the children in the list.
Try using:
children.add(person.name);
EDIT:
Ok, the above is correct, but cristobal de Leon's answer is the explanation to what you're experiencing.
I'm pretty sure the problem is that after you create the new ArrayList(); you never assign any value to the list, so when you iterate based on children.size(), you will always iterate from 0 to 0 and never add any children in the next snippet:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
As per #summerbulb suggestion: person.name should be adopted by the current this so you should just do
children.add(person.name)
Also, at the end of the adopt method, I think you want to mark person (the parameter) as adopted and not this (the person adopting), so you may change
person.adopted=true;
instead of just adopted=true;
The number of items in you arraylist "children" is 0.
Look at this part code:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
for every object in children you will set the same name.
So you will set the name 0 times. That means there also won't be any output.
I think you need an array with al the persons you create in you main.
Change the adopt code to this:
public void adopt(Person person) {
if (!person.adopted && !person.name.equals(this.name)) {
person.parent = name;
children.add(person.name);
person.adopted = true;
}
}
Make getters for your atributes or make them public like this:
public String name;
In your main:
Person[] persons = new Person[5];
persons[0] = new Person("Dude");
persons[1] = new Person("Dude's child");
persons[0].adopt(persons[1]);
Check your toString method. I am not sure if all children are printed. E.g. look at the case in which parent is not NULL and children.size() > 0
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: " + parent + " Children: " + list;
Here you are iterating over all children, take the name of the last children in the list and return it together with the parents name.
Besides: please check if children can also be of class Person
I write an OpenGL app in Java using JOGL. I am trying to completely avoid the creation of objects during the main app's phase as it could lead to the small periodic lag caused by GC.
I want to wrap some JOGL's methods with my own. Imagine a method void method(int[] result, int offset) which receives the pointer to an array and an offset and puts one integer value into it at the specified index. I want to wrap it with simple int getResult()
So I need to create a temporary array somewhere and I must do that in advance (according to 1).
But if it will be stored in a field of the class containing this wrapper method, this will force me to make the wrapper method synchronized. I know that sychronization in time of mostly single-thread access shouldn't produce a big overhead but I still want to know is it there a better solution for this.
Notes:
Synchronized is not the answer, 3.000.000 of empty synchronized blocks, just monitorenter-monitorexit take 17 ms. You have only 16.(6) if you want to keep 60 fps.
As I haven't enough power for voting up the only way I found to appreciate Dave's answer is writting a demo:
class Test {
private static final int CYCLES = 1000000000;
int[] global = new int[1];
ThreadLocal<int[]> local = new ThreadLocal<int[]>();
void _fastButIncorrect() { global[0] = 1; }
synchronized void _slowButCorrect() { global[0] = 1; }
void _amazing() {
int[] tmp = local.get();
if( tmp == null ){
tmp = new int[1];
local.set(tmp);
}
tmp[0] = 1;
}
long fastButIncorrect() {
long l = System.currentTimeMillis();
for (int i = 0; i < CYCLES; i++) _fastButIncorrect();
return System.currentTimeMillis() - l;
}
long slowButCorrect() {
long l = System.currentTimeMillis();
for (int i = 0; i < CYCLES; i++) _slowButCorrect();
return System.currentTimeMillis() - l;
}
long amazing() {
long l = System.currentTimeMillis();
for (int i = 0; i < CYCLES; i++) _amazing();
return System.currentTimeMillis() - l;
}
void test() {
System.out.println(
"fastButIncorrect cold: " + fastButIncorrect() + "\n" +
"slowButCorrect cold: " + slowButCorrect() + "\n" +
"amazing cold: " + amazing() + "\n" +
"fastButIncorrect hot: " + fastButIncorrect() + "\n" +
"slowButCorrect hot: " + slowButCorrect() + "\n" +
"amazing hot: " + amazing() + "\n"
);
}
public static void main(String[] args) {
new Test().test();
}
}
on my machine the results are:
fastButIncorrect cold: 40
slowButCorrect cold: 8871
amazing cold: 46
fastButIncorrect hot: 38
slowButCorrect hot: 9165
amazing hot: 41
Thanks again, Dave!
If you don't have too many threads, you can use a ThreadLocal:
ThreadLocal<int[]> tmpArrayThreadLocal = new ThreadLocal<int[]>();
code to use this:
int[] tmpArray = tmpArrayThreadLocal.get();
if( tmpArray == null ){
tmpArray = new int[100];
tmpArrayThreadLocal.set(tmpArray);
}
method(tmpArray, 5)
You could clean up the code by encapsulating the ThreadLocal in another class.
I have a tree that looks like the following (a simple example, can be a variable size).
1 (root)
|---------------------------------|
1-1 1-2
|------------| |--------------|
1-1-1 1-1-2 1-2-1 1-2-2
I've written a Java class to generate this tree based on NumberOfSiblings (horizontal) and NumberOfChildren (vertical). I'm now looking to write a class that will generate the path of a given entry in the tree, for example:
Entry: 1-1-1
Path: /1/1-1/1-1-1
I believe that I need some sort of recursive method that will count the number of dashes and take off the last part of the entry (not always length() - 2 though as it could be 10-10-10).
This is the method that will generate the tree:
public static void generateCatalog(String parent, int siblings, int children, int level) {
for (int a = 1; a <= siblings; a++) {
String child = parent + "-" + a;
System.out.println(child);
if (level <= children) {
level++;
generateCatalog(child, siblings, children, level);
level--;
}
}
}
I've been trying something like this to generate the path but it does not work very well.
public static void getPath(String category, String path) {
System.out.println("Category: " + category);
System.out.println("Current path: " + path);
int numberOfDashes = category.length() - category.replace("-", "").length();
System.out.println("Number of dashes: " + numberOfDashes);
while (numberOfDashes > 1) {
path = category + "/" + category.substring(0, category.length() - 2);
getPath(category, path);
}
System.out.println("New path: " + path);
}
Could someone please tell me the best way to do this?
Instead of
path = category + "/" + category.substring(0, category.length() - 2);
Try
int endIndex = category.lastIndexOf("-");
if(endIndex != -1) {
path = category + "/" + category.subString(0, endIndex);
}
Not sure what you want to do if there aren't any dashes, but just stick that in an else block.