I gotta create a program that, given a number N of threads, these threads can Insert or Remove an element from a queue, but there are conditions for the threads to access the queue:
if only one thread try to insert or remove an element, it will be able to;
if two or more threads are trying at the same time, one will be able to, and the next one will execute its operations when the first one finishes.
I made it using synchronized blocks, just like that:
import java.util.ArrayList;
import java.util.Random;
public class EditorThread extends Thread {
static int N = 10; // number of threads
static queue Q = new queue(); // shared queue
private int number; //number of the thread
public EditorThread(int n) {
number = n;
}
#Override
public void run() {
Random r = new Random();
while (true) {
int t = r.nextInt(2);
if (t == 1) {
int value = Q.get();
if (value == -1) {
System.out.println("The Thread " + number + " couldnt get any element (empty queue)");
}
else {
System.out.println("The Thread " + number + " got the element " + value );
}
}
else {
int n = r.nextInt(100);
Q.put(n);
System.out.println("The Thread " + number + " inserted the element " + n);
}
}
}
public static void main(String[] args) {
for (int i = 0; i < N; i++) {
Thread t = new EditorThread(i);
t.start();
}
}
}
class queue {
node head;
node tail;
queue() {
head = tail = null;
}
public synchronized int get() {
if (head == null)
return -1;
int r = head.value;
if (head != tail)
head = head.next;
else
head = tail = null;
return r;
}
public synchronized void put(int i) {
node n = new node(i);
if (head == null)
head = tail = n;
else {
tail.next = n;
tail = n;
}
}
}
class node {
int value;
node next;
public node(int value) {
this.value = value;
}
}
the run void is simple, it just loops forever while inserts or removes elements.
My question is, how can I follow that conditions without using synchronized?
How is it possible to guarantee mutual exclusion without the synchronized blocks?
EDIT: I cannot use things similar to synchronized (just like locks)
No, and yes.
Fundamentally you need to use some form of synchronization to do this. There is no way to do it yourself without.
However there are classes in the java.util.concurrent package that provide exactly the sort of behaviour you need and do it while minimizing locking and the cost of synchronization as much as possible.
For example LinkedBlockingQueue. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html
If you really want to understand how this stuff works though you should also read up on Non Blocking Algorithms. The wiki page is a good start. In general a lot of very smart people who know exactly what they are doing have worked on the concurrent package though. Threading is hard to get right.
https://en.wikipedia.org/wiki/Non-blocking_algorithm
Related
I wrote a recursive backtracking algorithm for the so-called "Coin Change Problem". I store the coin values (int) in a self-written LinkedList ("ll") and each of those LinkedLists is stored inside one master LinkedList ("ll_total"). Now, when I try to print out the LinkedLists inside the master LinkedList, all I get is "LinkedList#1e88b3c". Can somebody tell me how to modify the code, in order to print out the coin values properly?
I would also like the algorithm to chose the LinkedList with the least values stored inside, as it would represent the optimal coin combination for the "coin change problem".
import java.util.Scanner;
public class CoinChange_Backtracking {
static int[] coins = {3, 2, 1};
static int index_coins = 0;
static int counter = 0;
static LinkedList ll = new LinkedList();
static LinkedList ll_total = new LinkedList();
public static void main(String[] args) {
Scanner myInput = new Scanner(System.in);
int amount;
System.out.println("Put in the amount of money: ");
amount = myInput.nextInt();
if (amount < 101) {
//Start recursion and display result.
recursiveFunction(coins, amount, index_coins, ll);
ll_total.show_ll();
} else {
System.out.println("The value must be less than 100!");
}
}
public static LinkedList recursiveFunction(int[] coins, int amount, int index_coins, LinkedList ll) {
//The current coin is being omitted. (If index_coins + 1 is still within range.)
if ((index_coins + 1) < coins.length) {
ll = recursiveFunction(coins, amount, index_coins + 1, ll);
ll_total.insert_ll(ll);
for (int i = 0; i < counter; i++) {
ll.deleteAt(0);
}
counter = 0;
}
//The current coin is not being omitted. (If there is still some change left and value of change isn't lower than value of current coin.)
if (amount != 0) {
if (amount >= coins[index_coins]) {
ll.insert(coins[index_coins]);
counter++;
ll = recursiveFunction(coins, amount - coins[index_coins], index_coins, ll);
}
}
return ll;
}
}
public class LinkedList {
Node head;
public void insert(int data) {
Node node = new Node();
node.data = data;
node.next = null;
if (head == null) {
head = node;
} else {
Node n = head;
while(n.next != null) {
n = n.next;
}
n.next = node;
}
}
public void insert_ll(LinkedList ll) {
Node node = new Node();
node.ll = ll;
node.next = null;
if (head == null) {
head = node;
} else {
Node n = head;
while(n.next != null) {
n = n.next;
}
n.next = node;
}
}
public void deleteAt(int index) {
if(index == 0) {
head = head.next;
} else {
Node n = head;
Node n1 = null;
for (int i = 0; i < index - 1; i++) {
n = n.next;
}
n1 = n.next;
n.next = n1.next;
n1 = null;
}
}
public void show() {
Node node = head;
while(node.next != null) {
System.out.println(node.data);
node = node.next;
}
System.out.println(node.data);
}
public void show_ll() {
Node node = head;
while(node.next != null) {
System.out.println(node.ll);
node = node.next;
}
System.out.println(node.ll);
}
//A toString method I tried to implement. Causes an array error.
/*
public String toString() {
Node n = head.next;
String temp = "";
while (n != null) {
temp = temp + n.data + " ";
n = n.next;
}
return temp;
}
*/
}
public class Node {
int data;
LinkedList ll;
Node next;
}
To answer your question. You are printing the linked list object, see here System.out.println(node.ll);
There are several ways to do it right. One approach is to question why you use Node and LinkedList the way you do ? A node can have a linked list and a linked list can have a node, I believe this is not really what you wanted. Maybe you can make it work, but from a design point of view in my experience it is not good. I find it confusing and it's a great source of bugs.
I try to list some points that caught my eye (or that my IDE had caught for my eyes).
You are not closing the Scanner object. Just close it at the end of the program or use the try-with-resources.
As mentioned before you have linked list that has a node and a node that has a linked list. You are not using that correctly in your program. I recommend to review that approach. It is error prone.
Also simply use the LinkedList of the Java library unless you have a good reason not to. It works fine and offers all you need.
You use many static, global (within the scope of the package) variables. In this case I think you can avoid that. coins does not need to be given as a parameter every time. It should be an immutable object. It is not supposed to change.
...
And I am not sure if it is a backtracking algorithm. It is certainly tree recursive. This just as a side note.
I'd like to propose a solution that looks similar to yours. I'd probably do it differently my way, but then it probably takes time to understand it. I try to adopt your style, which I hope helps. I simplified the program.
In order to print the result, simply write a helper function.
The linked list is an object. You have to make a copy of the list every time you call the recursion in order to work on a dedicated object. Otherwise you modify the same object while recursing different paths.
You can simply use a list of lists. A global list of lists (within package scope), and a list of which you make a copy every time you recurse. When you reach a good base case you add it to the global list. Otherwise just ignore.
import java.util.LinkedList;
import java.util.Scanner;
public class CoinChangeBacktracking {
static final int[] COINS = {3, 2, 1};
static final LinkedList<LinkedList<Integer>> changes = new LinkedList<>();
public static void main(String[] args) {
Scanner myInput = new Scanner(System.in);
int amount;
System.out.println("Put in the amount of money: ");
amount = myInput.nextInt();
if (amount < 101) {
// Start recursion and display result.
recursiveFunction(amount, 0, new LinkedList<>());
print(changes);
} else {
System.out.println("The value must be less than 100!");
}
myInput.close();
}
static void recursiveFunction(int amount, int index,
LinkedList<Integer> list) {
// exact change, so add it to the solution
if (amount == 0) {
changes.add(list);
return;
}
// no exact change possible
if (amount < 0 || index >= COINS.length) {
return;
}
// explore change of amount without current coin
recursiveFunction(amount, index + 1, new LinkedList<>(list));
// consider current coin for change and keep exploring
list.add(COINS[index]);
recursiveFunction(amount - COINS[index], index, new LinkedList<>(list));
}
static void print(LinkedList<LinkedList<Integer>> ll) {
for (LinkedList<Integer> list : ll) {
for (Integer n : list) {
System.out.print(n + ", ");
}
System.out.println();
}
}
}
I have a binary tree where each node has the value of 0 or 1, and each path from the root to leaf node represents a binary string of a certain length. The aim of the program is to find all possible binary String (i.e. all possible paths from root to leaf). Now I want to parallelise it, so that it can use multiple cores. I assume I need to somehow split up the workload on the branch nodes, but I have no idea where to begin. I am looking at the ForkJoin functionality, but I have no idea how to split up the work and then combine it.
public class Tree{
Node root;
int levels;
Tree(int v){
root = new Node(v);
levels = 1;
}
Tree(){
root = null;
levels = 0;
}
public static void main(String[] args){
Tree tree = new Tree(0);
populate(tree, tree.root, tree.levels);
tree.printPaths(tree.root);
}
public static void populate(Tree t, Node n, int levels){
levels++;
if(levels >6){
n.left = null;
n.right = null;
}
else{
t.levels = levels;
n.left = new Node(0);
n.right = new Node(1);
populate(t, n.left, levels);
populate(t, n.right, levels);
}
}
void printPaths(Node node)
{
int path[] = new int[1000];
printPathsRecur(node, path, 0);
}
void printPathsRecur(Node node, int path[], int pathLen)
{
if (node == null)
return;
/* append this node to the path array */
path[pathLen] = node.value;
pathLen++;
/* it's a leaf, so print the path that led to here */
if (node.left == null && node.right == null)
printArray(path, pathLen);
else
{
/* otherwise try both subtrees */
printPathsRecur(node.left, path, pathLen);
printPathsRecur(node.right, path, pathLen);
}
}
/* Utility function that prints out an array on a line. */
void printArray(int ints[], int len)
{
int i;
for (i = 0; i < len; i++)
{
System.out.print(ints[i] + " ");
}
System.out.println("");
}
}
You can use Thread Pools to efficiently split the load between separate threads.
One possible approach:
ExecutorService service = Executors.newFixedThreadPool(8);
Runnable recursiveRunnable = new Runnable() {
#Override
public void run() {
//your recursive code goes here (for every new branch you have a runnable (recommended to have a custom class implementing Runnable))
}
};
service.execute(recursiveRunnable);
However, this approach is no longer a deep first search, since you list the sub-branches for your position before searching through the first one. In my understanding, DFS is a strictly linear approach and is therefore not entirely parallelizable (feel free to correct me in the comments though).
I'm supposed to copy elements from a stack to a queue.
I haven't been able to think of a way to keep the stack the way it is and still copy its elements to a queue.
I ended up with this method which removes the elements completely from the stack and adds them to the queue:
public void CopyFromStack(){
E t;
int c = w.size();
while(c != 0){
t = w.pop();
enqueue(t);
c--; }}
Trying to push elements back is not an option because it'll do it backwards.
Edit: This is the class that contains my method which is my queue class:
public class Queue<E> {
protected int size;
protected Node<E> head;
protected Node<E> tail;
NodeStack<E> w = new NodeStack<E>();
NodeStack<E> w2 = new NodeStack<E>();
public Queue(){
size = 0;
head = tail = null;}
public boolean isEmpty(){
return size==0;}
public void enqueue(E elem) {
Node<E> node = new Node<E>();
node.setElement(elem);
node.setNext(null);
if (size == 0) head = node;
else tail.setNext(node);
tail = node;
size++; }
public E dequeue() {
if (size == 0) System.out.print("Queue is empty.");
E tmp = head.getElement();
head = head.getNext();
size--;
if (size == 0) tail = null;
return tmp; }
public String toString(){
String s = "";
E t;
int c = size;
while(c != 0){
t = dequeue();
s += t + " ";
enqueue(t);
c--; }
return s;}
public int FindItem(E elem){
int index=0;
int c = size;
E t;
while(c != 0){
t = dequeue();
if (t == elem)
return index;
else index++;
c--;}
System.out.print("Not found!");
return -1;}
public void CopyToStack(){
System.out.print("Elements copied to the stack are: ");
E t;
int c = size;
while(c != 0){
t = dequeue();
w.push(t);
enqueue(t);
c--;
System.out.print(w.pop()+" "); }}
public void CopyFromStack(){
E t;
int c = w.size();
while(c != 0){
t = w.pop();
enqueue(t);
c--; }}
Q: I haven't been able to think of a way to keep the stack the way it is A:
A: That's because reading from a "classic" stack is destructive. "Reading" an element == removing that element from the stack.
TWO SOLUTIONS:
1) Modify your stack implementation so that you can "peek" each element
... or ...
2) Create a new stack containing all the elements from the first one.
Q: I ended up with this method ... Trying to push elements back is not an option because it'll do it backwards.
"A: This is a variation on "Option 2): above.
SOLUTION: Just create a new stack object, and push each element at the same time as you enqueue the element.
PS:
The standard JRE implementation of Stack includes peek() and search() methods. But I don't think they would help you here. If you wanted "Option 1)", you'd have to implement your own, custom stack.
================== UPDATE ==================
Note, too:
You should always indent your methods, and indent your "if" and "loop" blocks within your methods.
You should use "camel-case" (lower-case first letter) for your method names.
Here are the "official" Java coding conventions. They were useful in 1995; they're useful today:
http://www.oracle.com/technetwork/java/index-135089.html
There's actually a third option: Java's "Stack" happens to implement "iterator". Here's an example:
EXAMPLE CODE:
package com.testcopy;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
import java.util.Stack;
public class TestCopy {
public static void main (String[] args) {
TestCopy app = new TestCopy ();
app.run ();
}
public void run () {
// Create and populate stack
Stack<String> myStack = new Stack<String> ();
mkData(myStack);
// Copy to queue
Queue<String> myQueue = new ArrayDeque<String> ();
copyFromStack (myStack, myQueue);
// Print
int i=0;
for (String s : myQueue) {
System.out.println ("myQueue[" + i++ + "]: " + s);
}
}
#SuppressWarnings("unchecked")
public void mkData (Stack stack) {
stack.push("A");
stack.push("B");
stack.push("C");
// Stack should now contain C, B, A
}
public void copyFromStack (Stack stack, Queue queue) {
#SuppressWarnings("rawtypes")
Iterator it = stack.iterator ();
while (it.hasNext()) {
queue.add(it.next());
}
}
}
EXAMPLE OUTPUT:
myQueue[0]: A
myQueue[1]: B
myQueue[2]: C
I know that you can simply solve this question iteratively by using a counter to increment each time you pass a node in linkedlist; also creating an arraylist and setting the data found with each node inside it. Once you hit the tail of the linkedlist, just minus the Nth term from the total number of elements in the arraylist and you will be able to return the answer. However how would someone perform this using recursion? Is it possible and if so please show the code to show your genius :).
Note: I know you cannot return two values in Java (but in C/C++, you can play with pointers :])
Edit: This was a simple question I found online but I added the recursion piece to make it a challenge for myself which I've come to find out that it may be impossible with Java.
The trick is to do the work after the recursion. The array in the private method is basically used as a reference to a mutable integer.
class Node {
Node next;
int data;
public Node findNthFromLast(int n) {
return findNthFromLast(new int[] {n});
}
private Node findNthFromLast(int[] r) {
Node result = next == null ? null : next.findNthFromLast(r);
return r[0]-- == 0 ? this : result;
}
}
As a general rule, anything that can be done with loops can also be done with recursion in any reasonable language. The elegance of the solution may be wildly different. Here is a fairly java idiomatic version. I've omitted the usual accessor functions for brevity.
The idea here is to recur to the end of the list and increment a counter as the recursion unwinds. When the counter reaches the desire value, return that node. Otherwise return null. The non-null value is just returned all the way tot the top. Once down the list, once up. Minimal arguments. No disrespect to Adam intended, but I think this is rather simpler.
NB: OP's statement about Java being able to return only one value is true, but since that value can be any object, you can return an object with fields or array elements as you choose. That wasn't needed here, however.
public class Test {
public void run() {
Node node = null;
// Build a list of 10 nodes. The last is #1
for (int i = 1; i <= 10; i++) {
node = new Node(i, node);
}
// Print from 1st last to 10th last.
for (int i = 1; i <= 10; i++) {
System.out.println(i + "th last node=" + node.nThFromLast(i).data);
}
}
public static void main(String[] args) {
new Test().run();
}
}
class Node {
int data; // Node data
Node next; // Next node or null if this is last
Node(int data, Node next) {
this.data = data;
this.next = next;
}
// A context for finding nth last list element.
private static class NthLastFinder {
int n, fromLast = 1;
NthLastFinder(int n) {
this.n = n;
}
Node find(Node node) {
if (node.next != null) {
Node rtn = find(node.next);
if (rtn != null) {
return rtn;
}
fromLast++;
}
return fromLast == n ? node : null;
}
}
Node nThFromLast(int n) {
return new NthLastFinder(n).find(this);
}
}
Okay, I think think this should do the trick. This is in C++ but it should be easy to translate to Java. I also haven't tested.
Node *NToLastHelper(Node *behind, Node *current, int n) {
// If n is not yet 0, keep advancing the current node
// to get it n "ahead" of behind.
if (n != 0) {
return NToLastHelper(behind, current->next, n - 1);
}
// Since we now know current is n ahead of behind, if it is null
// the behind must be n from the end.
if (current->next == nullptr) {
return behind;
}
// Otherwise we need to keep going.
return NToLastHelper(behind->next, current->next, n);
}
Node *NToLast(Node *node, int n) {
// Call the helper function from the head node.
return NToLastHelper(node, node, n);
}
edit: If you want to return the value of the last node, you can just change it to:
int NToLast(Node *node, int n) {
// Call the helper function from the head node.
return NToLastHelper(node, node, n)->val;
}
This code will fail badly if node is null.
The recursion function:
int n_to_end(Node *no, int n, Node **res)
{
if(no->next == NULL)
{
if(n==0)
*res = no;
return 0;
}
else
{
int tmp = 1 + n_to_end(no->next, n, res);
if(tmp == n)
*res = no;
return tmp;
}
}
The wrapper function:
Node *n_end(Node *no, int n)
{
Node *res;
res = NULL;
int m = n_to_end(no, n, &res);
if(m < n)
{
printf("max possible n should be smaller than or equal to: %d\n", m);
}
return res;
}
The calling function:
int main()
{
List list;
list.append(3);
list.append(5);
list.append(2);
list.append(2);
list.append(1);
list.append(1);
list.append(2);
list.append(2);
Node * nth = n_end(list.head, 6);
if(nth!=NULL)
printf("value is: %d\n", nth->val);
}
This code has been tested with different inputs. Although it's a C++ version, you should be able to figure out the logic :)
I have this code:
static int countStu = 0;
public static int countStudent(Node<Student> lst) {
// pre : true
// post : res = number of students in list
if (lst != null) {
countStu++;
countStudent(lst.getNext());
}
return countStu;
}
The problem with this method is I must declare countStu outside the countStudent() method, which is not good in the case when I want to call countStudent() twice, it will make the returned value doubles. How do I solve this problem and able to call countStudent() unlimited times with correct results?
instead, return((lst == null)? 0 : (1 + countStudent(lst.getNext()))).
Change:
if(lst!=null){
countStu++;
countStudent(lst.getNext());
}
return countStu;
to
return lst==null ? 0 : (1+countStudent(lst.getNext()));
Assuming that this is your homework and you really must declare countStu outside (you shouldn't in any normal code), you can simply wrap the value in some class. Add set+get accessors and pass the object as a second argument to the function. Use it then, instead of the global / static variable.
Or simply don't use the variable at all and return the result + 1. Not sure if this is allowed by your rules.
In general when you are trying to do something like is useful to try to remove the explicit state handling somehow.
For example if you have to compute a function f(x) = G(f(x-1)) you can express G as a stateless method and follow the following pattern:
public static ResultType G(ResultType input) {
// compute G stateless
}
public static ResultType F(int x) {
return G(F(x - 1));
}
That way you don't have any side effects like you have with your current code. The downside is usually minor compared with what you are doing right now (the same stack depth is used overall).
The important thing is to make sure the G and F implementations are stateless (not using variables declared outside the method body scope).
Holding the state of the recursion in the static field would not be thread-safe. Instead hold the value in the stack.
I give you both a recursive example which would risk a StackOverflowError with as little as 6k nodes with a default heap as well as a loop version which doesn't suffer from this.
public class SO3765757 {
public static int countNodeRecursive(Node<?> node) {
if(node == null) {
debug("node is null");
return 0;
}
int count = 1 + countNodeRecursive(node.getNext());
debug(count + " = " + node.toString());
return count;
}
public static int countNodeLoop(Node<?> node) {
int count = 0;
for(Node<?> currentNode = node; currentNode != null; currentNode = currentNode.getNext()) {
count += 1;
debug(count + " = " + currentNode.toString());
}
return count;
}
public static void main(String[] args) {
int count = 10;
if(args.length > 0) {
try {
count = Integer.parseInt(args[0]);
} catch(NumberFormatException e) {
}
}
Node<Student> node = getNodeTest(count);
System.out.println("Loop count = " + countNodeLoop(node));
try {
System.out.println("Recursive count = " + countNodeRecursive(node));
} catch(StackOverflowError e) {
System.out.println("Recursive count caused " + e.getClass().getName());
}
}
private static void debug(String msg) {
System.out.println("DEBUG:" + msg);
}
private static <T> Node<T> getNodeTest(int count) {
Node<T> prevNode = null;
for(int i=0;i<count;i++) {
Node<T> node;
if(prevNode == null) {
node = new NodeImpl<T>();
} else {
node = new NodeImpl<T>(prevNode);
}
prevNode = node;
}
return prevNode;
}
private static interface Node<T> {
Node<T> getNext();
}
private static class NodeImpl<T> implements Node<T> {
private final Node<T> next;
public NodeImpl() {
this.next = null;
}
public NodeImpl(Node<T> next) {
this.next = next;
}
public Node<T> getNext() {
return next;
}
}
private static interface Student {
}
}
countStudent(lst.getNext());
why do i need to call again this , if lst.getNext() has null. precompute before calling recursion, there are different types.when u call this method countStudent from main method , check the lst value for not null , before recursion starts.
public static int
countStudent(Node lst) {
countStu++;
Node<Student> _tmp;
_tmp = lst.getNext();
if (_tmp != null )
countStudent(lst.getNext());
return countStu; }