I need to find the first true value in arraylist and then the next true I need to turn into false and I don't know how to do so. I tried to use isCorrect but it doesn't do what I want it to.
Here's what I wrote so far:
private boolean singleOption;
private ArrayList<Option> allOptions;
public ClosedQuestion(int id, String title, boolean mandatory,boolean singleOption)
{
super(id,title,mandatory);
this.singleOption=singleOption;
allOptions = new ArrayList<Option>();
}
public boolean isSingleOption() {
return singleOption;
}
public void setSingleOption(boolean singleOption)
{
boolean flag = true;
for (int i = 0; i < allOptions.size();i++)
{
if(allOptions.get(i).isCorrect()&&flag)
{
flag = false;
}
if (!flag)
{
for(int j=1; j< allOptions.size();j++)
{
allOptions.get(j).setCorrect(false);
}
}
}
}
public ClosedQuestion(ClosedQuestion other)
{
super(other);
this.singleOption=other.singleOption;
allOptions = new ArrayList<Option>();
for (Option o: other.allOptions)
{
allOptions.add(new Option(o));
}
}
}
Related
Code: Search word in Trie
Implement the function SearchWord for the Trie class.
For a Trie, write the function for searching a word. Return true if the word is found successfully, otherwise return false.
Note: main function is given for your reference which we are using internally to test the code.
class TrieNode{
char data;
boolean isTerminating;
TrieNode children[];
int childCount;
public TrieNode(char data) {
this.data = data;
isTerminating = false;
children = new TrieNode[26];
childCount = 0;
}
}
public class Trie {
private TrieNode root;
public int count;
public Trie() {
root = new TrieNode('\0');
count = 0;
}
private boolean add(TrieNode root, String word){
if(word.length() == 0){
if (!root.isTerminating) {
root.isTerminating = true;
return true;
} else {
return false;
}
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if(child == null){
child = new TrieNode(word.charAt(0));
root.children[childIndex] = child;
root.childCount++;
}
return add(child, word.substring(1));
}
public void add(String word){
if (add(root, word)) {
this.count++;
}
}
public boolean search(String word){
// add your code here
return search(root,word);
}
private boolean search(TrieNode root, String word){
if(word.length()==0){
return true;
}
int childIndex = word.charAt(0) -'a';
TrieNode child = root.children[childIndex];
if(child==null){
return false;
}
return search(child, word.substring(1));
}
}
//Main Function
code
import java.io.*;
public class Runner {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException{
Trie t = new Trie();
String[] string = br.readLine().split("\\s");
int choice = Integer.parseInt(string[0]);
String word = "Null";
if (string.length!=1)
{
word = string[1];
}
while(choice != -1) {
switch(choice) {
case 1 : // insert
t.add(word);
break;
case 2 : // search
System.out.println(t.search(word));
break;
default :
return;
}
string = br.readLine().split("\\s");
choice = Integer.parseInt(string[0]);
if (string.length!=1)
{
word = string[1];
}
}
}
}
You need to make use of the isTerminating information. In search, change:
if(word.length()==0){
return true;
}
To:
if(word.length()==0){
return root.isTerminating;
}
Am really new to Java, started to study it on my own.... I downloaded netbeans and Eclipse and the two gave me the same result.. they don't run the code (stuck on running) neither let me debug it - Eclipse debugger and Netbeans - was not responding :? I don't whats wrong.. and I got no clue as I can't debug..
Here's my code: am tryin to check for palindrome:
package ClassQueue;
class Stack {
private Object[] Stack_Array = null;
public int top = 0;
public Stack(int size) {
top = 0;
Stack_Array = new Object[size];
}
public Stack() {
this(100);
}
protected void finalizer() {
Stack_Array = null;
}
final public boolean empty() {
return top == 0;
}
final public boolean full() {
return top == Stack_Array.length;
}
public void push(Object token) {
if (!full()) {
Stack_Array[top] = token;
top++;
}
}
public Object pop() {
Object Value_return = -999;
if (!empty()) {
Value_return = Stack_Array[top];
top--;
}
return Value_return;
}
}//end of Class_Stack
class Queue {
private Object[] Queue_Array = null;
private int Front = 0;
private int Rear = 0;
public Queue(int size) {
Front = Rear = 0;
Queue_Array = new Object[size];
}
public Queue() {
this(100);
}
protected void finalizer() {
Front = Rear = 0;
Queue_Array = null;
}
final public boolean empty() {
return Front == Rear;
}
final public boolean full() {
return Rear == Queue_Array.length;
}
public void queueAdd(Object token) {
if (!full()) {
Queue_Array[Rear] = token;
Rear++;
}
}
public Object queueDelete() {
Object Value_return = -999;
if (!empty()) {
Value_return = Queue_Array[Front];
Front++;
return Value_return;
}
return Value_return;
}
}//end of Class_Queue
public class ClassQueue {
public static void main(String[] args) {
int i = 0;
String Value_1 = "ABBA";
Stack Value_1_Stack = new Stack(Value_1.length());
Queue Value_1_Queue = new Queue(Value_1.length());
while (i < Value_1.length()) {
Value_1_Stack.push(Value_1.charAt(i));
Value_1_Queue.queueAdd(Value_1.charAt(i));
}
i = 0;
while (Value_1_Stack.pop() == Value_1_Queue.queueDelete()) {
i++;
}
if (i == Value_1.length()) {
System.out.println("Palindrome");
} else {
System.out.println("NOT");
}
}//end of main
}//end of ClassQueue
You've got an infinite loop here as i is never incremented:
while (i < Value_1.length()) {
Value_1_Stack.push(Value_1.charAt(i));
Value_1_Queue.queueAdd(Value_1.charAt(i));
}
Also don't exceed the length of the String Value_1:
while (i < Value_1.length() - 1) {
Value_1_Stack.push(Value_1.charAt(i));
Value_1_Queue.queueAdd(Value_1.charAt(i));
i++;
}
Aside: Use Java naming conventions for variable names.
You cannot create class with the name of package name.
To run your program
change the package name.
For ClassQueue create another ClassQueue.java file in same package.
To Debug program: Run>Debug
This will give you environment for debugging
Change view: Window>Show View>Debug
I'm writing program with several different algorithms for solving n-puzzle problem. I have problem with DFS algorithm, as it only finds solution for simplest combinations of depth 1 to 4, then it shows stack overflow error. Also, for depth 4 it shows solution of length 2147, which is obviously wrong. I ran out of ideas what is the problem.
I use HashMap to keep explored nodes and to retrace path. Here is my code for DFS:
public class DFS extends Path{
Node initial;
Node goal;
String order;
boolean isRandom = false;
ArrayList<Node> Visited = new ArrayList<Node>();
boolean goalFound=false;
public DFS(Node initial, String order, byte [][] goal_state){
this.initial=initial;
goal=new Node(goal_state);
this.order=order;
if(order.equals("Random"))isRandom=true;
Visited.add(initial);
path.put(this.initial, "");
runDFS(initial);
}
public void runDFS(Node current){
if(current.equals(goal))
{
goalFound=true;
System.out.println("Goal");
retracePath(current,true);
return;
}
if(!current.equals(goal) && goalFound==false)
{
Node child;
Moves m = new Moves(current);
if(isRandom)order=randomOrder("LRUD");
for (int i=0; i<4; i++)
{
String s = order.substring(i,i+1);
if(m.CanMove(s)==true)
{
child=m.move();
if(Visited.contains(child))
{
continue;
}
else
{
path.put(child,s);
Visited.add(child);
runDFS(child);
}
}
}
}
}
}
Node:
public class Node {
public byte[][] status;
private int pathcost;
public int getPathcost() {
return pathcost;
}
public void setPathcost(int pathcost) {
this.pathcost = pathcost;
}
public Node(byte[][] status)
{
this.status=new byte[status.length][status[0].length];
for(int i=0;i<status.length;i++){
for(int j=0;j<status[0].length;j++){
this.status[i][j]=status[i][j];
} }
}
#Override
public boolean equals(Object other)
{
if (!(other instanceof Node))
{
return false;
}
return Arrays.deepEquals(status, ((Node)other).status);
}
#Override
public int hashCode()
{
return Arrays.deepHashCode(status);
}
}
and Path:
public class Path {
public HashMap<Node,String> path;
public Path(){
path=new HashMap<Node, String>(100);
}
public void retracePath(Node nstate, boolean print){
String dir=path.get(nstate);
String textPath="";
int i=0;
while(!dir.equals("")){
textPath+=dir + ", ";
boolean changed=false;
if(dir.equals("L")) {dir="R"; changed=true;}
if(dir.equals("R") && changed==false) {dir="L";}
if(dir.equals("U")) {dir="D"; changed=true;}
if(dir.equals("D") && changed==false) {dir="U";}
Moves m=new Moves(nstate);
m.CanMove(dir);
nstate=new Node(m.move().status);
dir=path.get(nstate);
i++;
}
if(print==true) {textPath=textPath.substring(0,(textPath.length()-2));
System.out.println(i);
System.out.print(new StringBuffer(textPath).reverse().toString());}
}
public Node getParent(Node n){
String dir=path.get(n);
boolean changed=false;
if(dir.equals("L")) {dir="R"; changed=true;}
if(dir.equals("R") && changed==false) {dir="L";}
if(dir.equals("U")) {dir="D"; changed=true;}
if(dir.equals("D") && changed==false) {dir="U";}
Moves m=new Moves(n);
m.CanMove(dir);
n=new Node(m.move().status);
return n;
}
public String randomOrder(String order) {
ArrayList<Character> neworder = new ArrayList<Character>();
for(char c : order.toCharArray()) {
neworder.add(c);
}
Collections.shuffle(neworder);
StringBuilder newstring = new StringBuilder();
for(char c : neworder) {
newstring.append(c);
}
return newstring.toString();
}
}
If you have any ideas what is the problem and where is mistake I would be very thankful!
I'm trying to implement a linked list merge sort.
Here's the class I'm trying to do the merge sort in.
/**
* CS 200 Colorado State University, Fall 2011
*/
public class Member {
private String userID;
private String first;
private String last;
private EdgeStack edgeStack;
public void sortScore(Member member){
// calling a helper method
// this greedy method takes all the creds
edgeStack = sortEdgeStack(member);
}
private EdgeStack sortEdgeStack(Member member)
{
// our temp stacks
EdgeStack tempEdgeStack_A = new EdgeStack();
EdgeStack tempEdgeStack_B = new EdgeStack();
// our return value
EdgeStack result = null;
// storing the size of the stack
int sizeOfStack = member.getEdgeStack().getSize();
// base case
if(sizeOfStack<0){
return null;
}
// our true base case
else if(sizeOfStack==1)
{
// init stack
EdgeStack base = new EdgeStack();
base.push(member.getEdgeStack().pop());
return base;
}
else
{
// pop and store
for(int i = 0; i < (sizeOfStack / 2); i++)
{
tempEdgeStack_A.push(member.getEdgeStack().pop());
}
// pop and store into b
for(int j = (sizeOfStack/2)+1; j < sizeOfStack; j++)
{
tempEdgeStack_B.push(member.getEdgeStack().pop());
}
tempEdgeStack_A = sortEdgeStack(member);
tempEdgeStack_B = sortEdgeStack(member);
result = merge(tempEdgeStack_A,tempEdgeStack_B);
return result;
}
}
private EdgeStack merge(EdgeStack tempEdgeStack_A, EdgeStack tempEdgeStack_B) {
EdgeStack result = new EdgeStack();
// while either or
while(tempEdgeStack_A.getSize()> 0 || tempEdgeStack_B.getSize() > 0)
{
// if both are bigger then 0
if(tempEdgeStack_A.getSize()> 0 && tempEdgeStack_B.getSize() > 0)
{
if(tempEdgeStack_A.peek().getEdgeRank()<=tempEdgeStack_B.peek().getEdgeRank())
{
// adds b to result
result.push(tempEdgeStack_A.pop());
}
else
{
result.push(tempEdgeStack_B.pop());
}
}
// these elses cover if A or B are > 0 but A or B is also less then or equal too 0;
else if(tempEdgeStack_A.getSize()> 0)
{
while(tempEdgeStack_A.iterator().hasNext())
{
result.push(tempEdgeStack_A.iterator().next());
}
}
else if(tempEdgeStack_B.getSize()> 0)
{
while(tempEdgeStack_B.iterator().hasNext())
{
result.push(tempEdgeStack_B.iterator().next());
}
}
}
return result;
}
}
Here's the stack class (that implements a linked list). Why am I getting a stack overflow error?
import java.util.LinkedList;
import java.util.ListIterator;
/**
* CS 200 Colorado State University, Fall 2011
*/
public class EdgeStack {
private LinkedList<Edge> llist=new LinkedList<Edge>();
public EdgeStack(){
//add your code
}
public boolean isEmpty(){
return llist.isEmpty();
}
public void push(Edge e){
llist.add(e);
}
public Edge getIndexAt(int n){
return llist.get(n);
}
public Edge pop(){
return llist.remove();
}
public Edge peek(){
return llist.getLast();
}
public int getSize(){
return llist.size();
}
// public Edge peek(int n){
// LinkedList<Edge> temp=llist;
// return temp.peek();
// }
public LinkedList<Edge> popAll(){
LinkedList<Edge> temp=llist;
llist=null;
return temp; }
public ListIterator<Edge> iterator()
{
return llist.listIterator();
}
}
Check this:
else if(tempEdgeStack_A.getSize()> 0)
{
while(tempEdgeStack_A.iterator().hasNext())
{
result.push(tempEdgeStack_A.iterator().next());
}
}
else if(tempEdgeStack_B.getSize()> 0)
{
while(tempEdgeStack_B.iterator().hasNext())
{
result.push(tempEdgeStack_B.iterator().next());
}
}
You don't remove entries from the stacks, so the loop doesn't stop.
I would need some help with the following code if you are kind.
Basically i have a tree node that remembers it's parent node, depth-level and his current state(a 2D array).
Most variable names are written in my native language, i hope this is not a problem :
public class Nod implements Cloneable {
private Nod parinte;//parent node
private int[][] stare;//state
private int cost;//depth-level
private String actiune;//the action used to obtain this node
private volatile int hashCode = 0;
public boolean equals(Object obj)
{
if(this == obj)
{
return true;
}
if (!(obj instanceof Nod))
{
return false;
}
Nod nod = (Nod)obj;
return cost == nod.getCost() && actiune.equals(nod.getActiune())
&& stare.equals(nod.getStareNod());
}
public int hashCode()
{
StringBuffer strBuff = new StringBuffer();
try
{
int n = Problema.Dimensiune();//returns the dimension of state matrix
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
strBuff.append(stare[i][j]);
strBuff.append(cost);
strBuff.append(actiune);
String str = strBuff.toString();
hashCode = str.hashCode();
}
catch (IOException e) {
e.printStackTrace();
}
return hashCode;
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
public static boolean goUp(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (i != 0)
ok = true;
}
return ok;
}
public static boolean goDown(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (i != (n-1))
ok = true;
}
return ok;
}
public static boolean goLeft(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (j != 0)
ok = true;
}
return ok;
}
public static boolean goRight(int[][] st) throws IOException
{
int n = Problema.Dimensiune();
boolean ok = false;
int[][] a = st;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
if (a[i][j] == 0)
if (j != (n-1))
ok = true;
}
return ok;
}
public static int[] Zero(int[][] st) throws IOException
{
int[][] a = st;
int n = Problema.Dimensiune();
int[] b = new int[2];
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
if (a[i][j] == 0)
{
b[0] = i;
b[1] = j;
}
return b;
}
public static int[][] Actiune(int[][] st, String s) throws IOException
{
int[][] a = st;
int[] b = Zero(st);
if ((goRight(st) == true) && (s == "right"))
{
a[b[0]][b[1]] = a[b[0]][b[1]+1];
a[b[0]][b[1]+1] = 0;
}
if ((goLeft(st) == true) && (s == "left"))
{
a[b[0]][b[1]] = a[b[0]][b[1]-1];
a[b[0]][b[1]-1] = 0;
}
if ((goUp(st) == true) && (s == "up"))
{
a[b[0]][b[1]] = a[b[0]-1][b[1]];
a[b[0]-1][b[1]] = 0;
}
if ((goDown(st) == true) && (s == "down"))
{
a[b[0]][b[1]] = a[b[0]+1][b[1]];
a[b[0]+1][b[1]] = 0;
}
return a;
}
public Nod(){}
public Nod (int[][] st)
{
parinte = null;
stare = st;
cost = 0;
actiune = null;
}
public Nod (Nod nod)
{
parinte = nod.parinte;
stare = nod.stare;
cost = nod.cost;
actiune = nod.actiune;
}
public Nod(Nod nodp, String ac) throws IOException
{
this.parinte = nodp;
this.cost = parinte.getCost()+1;
this.actiune = ac;
this.stare = Actiune(parinte.getStareNod(),actiune);
}
public void setCost(int cost)
{
this.cost = cost;
}
public int getCost(){
return this.cost;
}
public void setStareNod(int[][] stare)
{
this.stare = stare;
}
public int[][] getStareNod(){
return this.stare;
}
public void setNodParinte(Nod parinte)
{
this.parinte = parinte;
}
public Nod getNodParinte() throws IOException{
return this.parinte;
}
public void setActiune(String actiune)
{
this.actiune = actiune;
}
public String getActiune()
{
return this.actiune;
}
}
Now, i create an initial node and after, a child-node from it. The problem is that when i create the child-node, the parent's 2D array becomes identical with the child's array. I tried to clone the node object but it didn't fix it. I would appreciate if someone has an ideea how to fix it and shares it.
public class test {
public static void main(String[] args) throws IOException, CloneNotSupportedException
{
int[][] p = Problema.stareInitiala();
Nod nod = new Nod(p);
Nod nodc = (Nod) nod.clone();
Nod nod1 = new Nod(nodc,"right");
Nod nod1c = (Nod) nod1.clone();
Nod nod2 = new Nod(nod1c,"up");
if (nod.getStareNod().equals(nod.getStareNod()))
System.out.print("ok");
else
System.out.print("not ok");
}
}
So if p = {{7,2,4},{5,0,6},{8,3,1}} the if statement should return "not ok", but instead i get the "ok" message.
There is nothing broken or wrong about the clone mechanism. Just a bunch or programmers who don't understand it, here's a valid one for you class.
public Object clone() {
try {
Nod clone = (Nod)super.clone();
clone.stare = (int[][])stare.clone();
return clone;
} catch (CloneNotSupportedException cnse) {
//won't happen;
throw new RuntimeError("Won't happen");
}
}
This implementation assumes that the clone wants to use the same parent as the original. If this is not the case, you will need to clone that as well, or perhaps set the parent to null.
You may want to look at the documentation of the clone() method of Object. Default clone implementation (that is if you implemented Cloneable, which you did) performs shallow copy. This is probably not what you want, you may be better off by writing your own copying method.