I'm working on an exercise and I'm running into something. The following code gives me a stackoverflow error, but I have no idea why because my code should stop.
class Options {
private int amount;
private ArrayList<Integer> pieces;
public void execute() {
pieces = new ArrayList<Integer>();
pieces.add(5);
pieces.add(2);
pieces.add(3);
amount = pieces.size();
combinations(new StringBuilder());
}
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
return;
}
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
It only prints the first output (555).
Thanks.
Add a return to end your recursion
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
return; // <-- like so.
}
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
or put the loop in an else like
public void combinations(StringBuilder current) {
if(current.length() == pieces.size()) {
System.out.println(current.toString());
} else {
for(int i = 0; i < amount; i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
Edit
static class Options {
private List<Integer> pieces;
public void execute() {
pieces = new ArrayList<>();
pieces.add(5);
pieces.add(2);
pieces.add(3);
combinations(new StringBuilder());
}
public void combinations(StringBuilder current) {
if (current.length() == pieces.size()) {
System.out.println(current.toString());
} else {
for (int i = current.length(); i < pieces.size(); i++) {
current.append(pieces.get(i));
combinations(current);
}
}
}
}
public static void main(String[] args) {
Options o = new Options();
o.execute();
System.out.println(o.pieces);
}
Output is
523
[5, 2, 3]
Related
I'm trying to print all the word in my prefix tree. I can insert, it's working, but when I try to print all elements of the tree using a preorder way it just gets all messed up. There's some problem on the recursive method PREORDER that I'm using to display all elements.
How can I recursively display all the word on my prefix tree???
public class TrieMain {
public static void main(String[] args) {
TrieTree tree = new TrieTree();
tree.treeInsert("cat");
tree.treeInsert("cattle");
tree.treeInsert("hell");
tree.treeInsert("hello");
tree.treeInsert("rip");
tree.treeInsert("rap");
tree.preorder(tree.getRoot(), "");
}
}
public class TrieTree {
private TrieNode root;
private int wordCount;
public TrieTree() {
this.root = null;
this.wordCount = 0;
}
public TrieNode getRoot() {
return this.root;
}
public void setRoot(TrieNode newRoot) {
this.root = newRoot;
}
public int getWordCount() {
return this.wordCount;
}
public void preorder(TrieNode root, String prefix) {
if (root.getTerminal()) {
System.out.println(prefix);
}
for (int i = 0; i < 26; i++) {
if (root.getCharacters()[i] != '\u0000') {
prefix += root.getCharacters()[i];
preorder(root.getPointers()[i], prefix);
}
}
}
public boolean treeInsert(String word) {
if (this.root == null) {
this.root = new TrieNode();
}
TrieNode temp;
temp = this.root;
int lengthWord = word.length();
for (int i = 0; i < lengthWord; i++) {
int index = getIndex(word.charAt(i));
if (temp.getCharacters()[index] == '\u0000') {
temp.getCharacters()[index] = word.charAt(i);
temp.getPointers()[index] = new TrieNode();
}
temp = temp.getPointers()[index];
}
if (temp.getTerminal()) {
return false;
}
else {
temp.setTerminal(true);
return true;
}
}
public int getIndex(char character) {
int index = ((int) character) - 97;
return index;
}
}
public class TrieNode {
private final int NUM_CHARS = 26;
private char[] characters;
private TrieNode[] pointers;
private boolean terminal;
public TrieNode() {
this.characters = new char[this.NUM_CHARS];
this.pointers = new TrieNode[this.NUM_CHARS];
for (int i = 0; i < this.NUM_CHARS; i++) {
this.characters[i] = '\u0000';
this.pointers[i] = null;
}
this.terminal = false;
}
public char[] getCharacters() {
return this.characters;
}
public TrieNode[] getPointers() {
return this.pointers;
}
public boolean getTerminal() {
return this.terminal;
}
public void setTerminal(boolean newTerminal) {
this.terminal = newTerminal;
}
}
I'm working on a simple(?) exercise for my Data Structures class. It works fine right up until I have an element leave the queue then try to add another one on at which point I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
at queueExercise.IntegerQueue.join(IntegerQueue.java:20)
at queueExercise.IntegerQueueTest.main(IntegerQueueTest.java:27)
My code is as follows:
Queue Constructor Class:
public class IntegerQueue {
private int[] queue;
private int front;
private int end;
private int noInQueue;
private int count;
private boolean full;
public IntegerQueue(int max) {
queue = new int[max];
front = end = 0;
full = false;
}
public void join(int newValue) {
if (isFull()==false) {
queue[end] = newValue;
count++;
if (end == queue.length) {
end = 0;
}
else {
end++;
}
}else
System.out.println("Error: Queue Full");
}
public int leave() {
if (isEmpty()==false) {
noInQueue = queue[front];
queue[front]=0;
front++;
if (front==queue.length) {
front = 0;
}
count--;
}
else {
System.out.println("Error: Queue Empty");
}
System.out.println("Leaving: "+noInQueue);
return noInQueue;
}
public boolean isEmpty() {
if (count == 0){
return true;
}
else
return false;
}
public boolean isFull() {
if (count >= queue.length) {
return true;
}
else
return false;
}
public void printQueue() {
if (!isEmpty()) {
System.out.println("Printing Queue");
int pos = front;
int i =0;
while(i<queue.length) {
System.out.println(queue[pos]);
pos++;
i++;
if (pos >=queue.length) {
pos = 0;
}
}
}
}
}
Test Class
public class IntegerQueueTest {
static IntegerQueue q = new IntegerQueue(10);
public static void main(String[] args) {
int j;
System.out.println("Creating Queue");
for (int i = 0; i <10; i++) {
j = (int)(Math.random()*100);
if (!q.isFull()) {
q.join(j);
System.out.println("Adding: "+j);
}
}
q.printQueue();
q.join(112);
q.leave();
q.leave();
q.leave();
q.printQueue();
q.join(112);
q.join(254);
q.printQueue();
}
}
The problem is in the join method and more precisely in the condition if (end == queue.length). All you have to do is change it to if (end == queue.length - 1).
I've created a Dataset class used to store and manipulate a dataset. A different class, called Dataset Iris, extends Dataset because Dataset is Principal class where every different datasets (iris and so on) extends it because they have a their feature and a different methods to load it(I can load from a file .txt, .data or database and so on...).
My actually code is this and run, but my teacher tells to me that I should apply "Decorator" design pattern to solve it, but looking the Decorator UML I don't think it because I haven't the "Concrete component" (I can create . What do you think about it? Is a Decorator design pattern or other (like template methods)?
Dataset
public class Dataset
{
private int nFeature;
private int nRecord;
private ArrayList<Integer> featureUsed;
private String nomeDataset;
//public double Mat [][];
private ArrayList<ArrayList<Double>> Mat;
public double Distanza(int i, ArrayList<Double> centroide)
{
double Sum=0;
for(int j=0; j<nFeature; j++)
Sum+=Math.pow((centroide.get(j) - Mat.get(j).get(i)), 2);
return Math.sqrt(Sum);
}
public double getCell(int i, int j)
{
return Mat.get(j).get(i);
}
public void initMat()
{
Mat = new ArrayList<ArrayList<Double>>();
featureUsed = new ArrayList<Integer>();
for(int i=0; i< nFeature; i++)
{
Mat.add(new ArrayList<Double>());
featureUsed.add(i);
}
}
public void writeDataset()
{
for(int i=0; i< nRecord; i++)
{
for(int j=0; j < nFeature; j++)
{
System.out.print( Mat.get(j).get(i)+ " ");
}
System.out.println("\n");
}
}
public ArrayList<Double> getRecord(int i_r)
{
ArrayList<Double> record = new ArrayList<Double>();
for(int i=0; i<nFeature; i++)
record.add( Mat.get(i).get(i_r));
return record;
}
public Dataset(int nFeature, String Nome)
{
setnFeature(4);
setNomeDataset(Nome);
initMat();
}
public Dataset(ArrayList<ArrayList<Double>> MatInput, ArrayList<Integer> featureSelected, int nRecord)
{
Mat = new ArrayList<ArrayList<Double>>();
this.featureUsate = new ArrayList<Integer>(featureSelected);
this.nRecord = nRecord;
this.setnFeature(featureSelected.size());
for(int i=0; i<featureSelected.size(); i++)
setCol( MatInput.get( featureSelected.get(i)));
}
public Dataset() {
// TODO Auto-generated constructor stub
}
public void setCol( ArrayList<Double> colVal)
{
this.Mat.add(colVal);
}
public ArrayList<ArrayList<Double>> getMat()
{
return this.Mat;
}
public int getnFeature() {
return this.nFeature;
}
public int getnRecord() {
return this.nRecord;
}
public void setnFeature(int nFeature)
{
this.nFeature = nFeature;
return;
}
public void setnRecord(int nRecord) {
this.nRecord=nRecord;
return;
}
public void setTable(int Colonna, Double Valore)
{
Mat.get(Colonna).add(Valore);
}
public String getNomeDataset() {
return this.nomeDataset;
}
public void setNomeDataset(String nomeDataset) {
this.nomeDataset = new String(nomeDataset);
}
public double[][] toMatrix()
{
double[][] matrix = new double[this.getnRecord()][this.getnFeature()];
for(int i=0; i< nRecord; i++)
{
for(int j=0; j < nFeature; j++)
{
matrix[i][j] = Mat.get(j).get(i);
}
}
return matrix;
}
public ArrayList<Integer> getFeatureUsed()
{return this.featureUsed;}
}
DatasetIris
public class DatasetIris extends Dataset
{
private String[] nomiFeature = {"Petal Length",
"Petal Width",
"Sepal Length",
"Sepal Width"
};
public DatasetIris(String NomeFile) throws IOException
{
super(4,NomeFile);
super.setnRecord( CaricaDataset(NomeFile) );
}
// Other DatasetIris with their load (database or other type of files)?
protected int loadDataset(String pathFile) throws IOException
{
int iRecord = 0;
BufferedReader bufferLetto = null;
String line = "";
String cvsSplitBy = ",";
try {
bufferLetto = new BufferedReader(new FileReader(pathFile));
while ((line = bufferLetto.readLine()) != null)
{
if (line.length() > 0)
{
String[] cell = line.split(cvsSplitBy);
this.addRow(cell);
iRecord++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferLetto != null) {
try {
bufferLetto.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return iRecord;
}
// New File.data to Mat
public void addRow(Object cell[])
{
for(int i=0; i<getnFeature(); i++)
super.setTable(i, Double.parseDouble(cell[i].toString()));
}
}
I'm currently working on an application with animation in JavaFX. The application is used by human corrector, who is correcting computer-generated subtitles. In the animation there is a floating text. My problem is that the animation sometimes shutters. You can see the following image for demonstration:
This flaw occurs mainly after resizing. When the animation breaks, it never gets to the fully functioning state again.
I use the JFXpanel which is in inserted in Swing UI. I use it this way because I've created quite a lot of code in Swing and I didn't want to toss it all away. I don't use Swing for animation because I wasn't able to create an animation that is smooth enough.
Here is the animation-related code:
public class AnimationPanel extends JFXPanel {
public MyAnimationTimer animationTimer;
public EditObject editObject;
public Color colorHOST1;
public Color colorHOST2;
public Color colorGUEST1;
public Color colorGUEST2;
public Color colorUSER;
public Color colorSIGNING;
public Color basicColor = Color.WHITE;
public Color currentColor = Color.WHITE;
public AnimationPanel(EditObject editObject) {
super();
this.editObject = editObject;
Group group = new Group();
this.animationTimer = new MyAnimationTimer((List<MyText>)(List<?>)group.getChildren(), this);
final Scene scene = new Scene(group, 800, 600, Color.BLACK);
this.setScene(scene);
this.animationTimer.start();
/* // Update animation when component is resized
this.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent e) {
animationTimer.updateAnimations();
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
});*/
}
public void setColors(Gui g) {
this.colorHOST1 = Color.rgb(g.colorHOST1.getRed(), g.colorHOST1.getGreen(), g.colorHOST1.getBlue(), g.colorHOST1.getAlpha()/255.0);
this.colorHOST2 = Color.rgb(g.colorHOST2.getRed(), g.colorHOST2.getGreen(), g.colorHOST2.getBlue(), g.colorHOST2.getAlpha()/255.0);
this.colorGUEST1 = Color.rgb(g.colorGUEST1.getRed(), g.colorGUEST1.getGreen(), g.colorGUEST1.getBlue(), g.colorGUEST1.getAlpha()/255.0);
this.colorGUEST2 = Color.rgb(g.colorGUEST2.getRed(), g.colorGUEST2.getGreen(), g.colorGUEST2.getBlue(), g.colorGUEST2.getAlpha()/255.0);
this.colorUSER = Color.rgb(g.colorUSER.getRed(), g.colorUSER.getGreen(), g.colorUSER.getBlue(), g.colorUSER.getAlpha()/255.0);
this.colorSIGNING = Color.rgb(g.colorSIGNING.getRed(), g.colorSIGNING.getGreen(), g.colorSIGNING.getBlue(), g.colorSIGNING.getAlpha()/255.0);
}
}
public class MyAnimationTimer extends AnimationTimer {
private List<MyText> nodes;
private long subtitle_max_time_in_app;
private AnimationPanel animationPanel;
private boolean stopAtTheEnd = false;
private boolean isAtTheEnd = false;
private int currentPos = 0;
public MyAnimationTimer(List<MyText> nodes, AnimationPanel animationPanel) {
super();
this.nodes = nodes;
this.animationPanel = animationPanel;
}
#Override
public void handle(long now) {
MyText node;
if(this.stopAtTheEnd) {
if(this.isAtTheEnd) {
for (int i = this.currentPos; i < this.nodes.size(); i += 2) {
node = nodes.get(i);
if(this.collides(nodes.get(i-2), node)) {
node.setTranslateXforTextandSubText(nodes.get(i-2).getBoundsInParent().getWidth() + nodes.get(i-2).getTranslateX() + 10);
this.currentPos+=2;
}
node.setTranslateXforTextandSubText(node.getTranslateX() - node.getVelocity());
}
} else {
if(nodes.size()!=0) {
node = nodes.get(0);
if((node.getTranslateX() - node.getVelocity()) < 0) {
node.setTranslateXforTextandSubText(0);
this.isAtTheEnd = true;
this.currentPos = 2;
} else {
for (int i = 0; i < this.nodes.size(); i += 2) {
node = nodes.get(i);
node.setTranslateXforTextandSubText(node.getTranslateX() - node.getVelocity());
}
}
}
}
} else {
for (int i = 0; i < this.nodes.size(); i += 2) {
node = nodes.get(i);
node.setTranslateXforTextandSubText(node.getTranslateX() - node.getVelocity());
}
}
}
private boolean collides(MyText node1, MyText node2) {
return (node1.getBoundsInParent().getWidth() + node1.getTranslateX() - node2.getTranslateX()) + 7 >= 0;
}
public void addNode(final MyText node) {
Platform.runLater(() -> {
node.setTranslateYforTextandSubText(animationPanel.getHeight() / 2);
node.setTranslateXforTextandSubText(animationPanel.getWidth());
node.setVelocity(this.getVelocity());
nodes.add(node);
nodes.add(node.id);
// Check for overlaying
if(nodes.size()>=4) {
int size = nodes.size();
double overlaying = (nodes.get(size-4).getBoundsInParent().getWidth() + nodes.get(size-4).getTranslateX() - nodes.get(size-2).getTranslateX()) + 7;
if(overlaying>0) {
nodes.get(size-2).setTranslateXforTextandSubText(nodes.get(size-2).getTranslateX()+overlaying);
}
}
});
}
public void recalculateGaps() {
Platform.runLater(() -> {
if (nodes.size() >= 4) {
double overlaying;
// System.out.println("Size: " + nodes.size());
for (int i = nodes.size() - 2; i > 0; i -= 2) {
overlaying = (nodes.get(i - 2).getBoundsInParent().getWidth() + nodes.get(i - 2).getTranslateX() - nodes.get(i).getTranslateX()) + 7;
if (overlaying > 0) {
nodes.get(i - 2).setTranslateXforTextandSubText(nodes.get(i - 2).getTranslateX() - overlaying);
}
}
}
});
}
public void removeNodesBehindTheScene() {
Platform.runLater(() -> {
MyText node;
for (int i=0; i<nodes.size(); i+=2) {
node = nodes.get(i);
if(node.getTranslateX() > 0) {
break;
} else {
if(!node.isOverdue()) {
animationPanel.editObject.setMessageToBeSendSoon(node);
}
nodes.remove(i);
nodes.remove(i);
i-=2;
}
}
});
}
/* public void updateAnimations() {
// This method is called when the window is resized.
for (int i=0; i<this.nodes.size(); i+=2) {
nodes.get(i).setTranslateYforTextandSubText(animationPanel.getHeight()/2);
}
this.setVelocity();
}*/
public double getVelocity() {
return (this.animationPanel.getWidth()/4)*3/((double) this.subtitle_max_time_in_app)*1000/60;
}
public void setSubtitle_max_time_in_app(long subtitle_max_time_in_app) {
this.subtitle_max_time_in_app = subtitle_max_time_in_app;
}
public void setStopAtTheEnd(boolean stopAtTheEnd) {
// Remove all overdue
if(stopAtTheEnd) {
Platform.runLater(() -> {
for (int i = 0; i < nodes.size(); i += 2) {
if (nodes.get(i).isOverdue()) {
nodes.remove(i);
// Remove ID number
nodes.remove(i);
i -= 2;
} else {
break;
}
}
});
this.isAtTheEnd = false;
this.currentPos = 0;
}
this.stopAtTheEnd = stopAtTheEnd;
}
public void removeUpToNode(MyText node) {
Platform.runLater(() -> {
if(nodes.contains(node)) {
for (int i = 0; i < nodes.size(); i += 2) {
if (nodes.get(i) == node) {
nodes.remove(i);
nodes.remove(i);
break;
}
else {
nodes.remove(i);
nodes.remove(i);
i-=2;
}
}
}
});
}
public void addNodesAtTheBeginning(List<MyText> nodes_list, double nodeposition) {
Platform.runLater(() -> {
MyText node;
double position;
for (int i = nodes_list.size() - 1; i >= 0; i--) {
node = nodes_list.get(i);
node.setTranslateYforTextandSubText(animationPanel.getHeight() / 2);
if(nodes.size()!=0) {
position = this.nodes.get(0).getTranslateX() - node.getBoundsInParent().getWidth() - 10;
} else {
position = animationPanel.getWidth();
}
if(i==(nodes_list.size() - 1)) {
double exactposition = nodeposition - node.getBoundsInParent().getWidth();
if(exactposition < position) {
node.setTranslateXforTextandSubText(exactposition);
} else {
node.setTranslateXforTextandSubText(position);
}
} else {
node.setTranslateXforTextandSubText(position);
}
node.setVelocity(this.getVelocity());
nodes.add(0, node.id);
nodes.add(0, node);
}
});
}
}
I've tested various versions of JavaFX(including the one packed in JDK9), but with no result. Thanks in advance
Finally I fixed the bug. The problem was that I was setting a property of an existing node from my own thread instead of JavaFX thread. Putting it in Platform.runLater method fixed it. I didn't notice the bug immediately because it didn't throw the illegal thread exception as it does when you try to add node. I should have red the documentation more thoroughly.
Thanks
I'm learning the Growing Array in Java, and I implemented the method delete() in the following Code.
Now I want to test this method for a example array [1,2,3,4,5,6,7]
What do I have to write in the Main method?
import java.util.Arrays;
public abstract class GrowingArray {
protected Object[] array;
protected static final int primaryQty = 10;
protected static final int secondaryQty = 5;
protected int index = 0;
public GrowingArray() {
array = new Object[primaryQty];
}
public GrowingArray(int size) {
array = new Object[size];
}
protected void grow() {
int oldsize = array.length;
int newsize = oldsize + secondaryQty;
Object[] loc = new Object[newsize];
for (int i = 0; i < oldsize; i++)
loc[i] = array[i];
array = loc;
}
public Object get(int at) {
return array[at];
}
public int getLength() {
return array.length;
}
public void add(Object obj) {
if (index < array.length)
array[index++] = obj;
else {
grow();
array[index++] = obj;
}
}
public void delete(int x) {
for (int i = x; i < array.length; i++) {
if (i == array.length - 1) {
array[i] = null;
System.out.println(array.toString());
} else {
array[i] = array[i + 1];
System.out.println(array.toString());
}
}
}
#Override
public boolean equals(Object obj) {
if (obj instanceof GrowingArray) {
return Arrays.equals(array, ((GrowingArray) obj).array);
}
return false;
}
#Override
public String toString() {
return Arrays.toString(array);
}
public static void main(String args[]) {
//test ?????
}
}
Your class is abstract. Remove abstract from the class definition.