package task1;
import java.lang.Thread;
public class Counter implements Runnable{
int num;
boolean odd;
boolean even;
public Counter(int i,boolean odd, boolean even){
this.num=i;
this.odd=odd;
this.even=even;
}
#Override
public void run() {
if(odd==true&even==false){
System.out.print("\nOdd numbers\n");
for(int j=this.num; j<=10; j+=2){
System.out.print(j + " ");
}
}
else if (odd==true&even==true){
System.out.print("\nEven and odd numbers paired\n");
for(int j=this.num; j<=10; j+=2){
try {
Thread.sleep(600);
} catch (InterruptedException ex) {
System.out.println("The sleeping has been interruped!");
}
System.out.print(j + " " + (j+1)+" | ");
}
}
}
}
class OddEvenNums {
public static void main(String[] args) {
Counter odd = new Counter(1,true,false);
Counter evenodd = new Counter(1,true,true);
Thread oddThread = new Thread(odd);
Thread evenOddThread = new Thread(evenodd);
oddThread.start();
evenOddThread.start();
}
}
Basically this code just has two threads that either print out the odd numbers from 1-10 or print out the odd and the even numbers paired
However the output comes out like
run:
Odd numbers
Even and odd numbers paired
1 3 5 7 9 1 2 | 3 4 | 5 6 | 7 8 | 9 10 |
Instead of what I was hoping for which would be
run:
Odd numbers
1 3 5 7 9
Even and odd numbers paired
1 2 | 3 4 | 5 6 | 7 8 | 9 10 |
I am confused about what I have done wrong to cause it to be outputted like this
Both Threads are running in parallel, not one after another (that's the purpose of Threads in the first place). That's why their output gets mixed up.
Trying to explain the output that you're seeing: The "odd" Thread gets a tiny bit of a head start, letting it print "Odd numbers" first. Then the "oddeven" Thread kicks in and prints "Event and odd numbers paired". Next thing, "oddeven" sleeps for 600 milliseconds (= half an eternity in computer time), giving "odd" all the time it needs to complete printing its sequence. Once the 600ms are elapsed, "oddeven" kicks back in and prints its own sequence (delaying another 600ms between each pair, but that doesn't really matter any more, as "odd" has long completed).
This is by no means deterministic, though. Meaning, if you run the program a couple of times you might see completely different sequences of String output.
The output is totally expected, although it is a bit random in what order exactly stuff happens. What is happening here is:
oddThread writes "Odd numbers"
evenOddThread writes "Even and odd numbers paired"
oddThread writes "1 3 5 7 9" (without newline)
evenOddThread writes "1 2 | 3 4 | 5 6 | 7 8 | 9 10 |"
So, you did nothing wrong per se. But you didn't think about what would happen when you run both threads concurrently. Either don't do that (wait for oddThread to be finished before starting evenOddThread, by calling oddThread.join()), or put some synchronization in there to make sure the output is written atomically. You are somewhat lucky to get the output you got. I could also have:
Just worked, until it randomly doesn't
mixed the output up even worse, like 1 1 2 3 | 3 4 5 7 | 5 6 9 | 7 8 | 9 10 |
put evenOddThread output above oddThread (probably unlikely but there is no guarantuee for how the threads get scheduled)
Related
Edit: For some reason my code works as intended in an online compiler. But in eclipse, the exact same code has the following problem.
I am working on a Kattis Problem called Electrical Outlets.
On the first line of input will be the number of test cases (n). On the next n lines, each line will start with an integer k, which is the number of power strips that will follow on the line. The rest of the line will contain how many outlets each of these power strips contain. Here is my code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<Integer> outlets = new ArrayList<>();
int testCases = scnr.nextInt();
int stripCount;
int appliances = 0;
for (int i = 0; i < testCases; i++) {
stripCount = scnr.nextInt();
for (int j = 0; j < stripCount; j++) {
outlets.add(scnr.nextInt());
appliances += outlets.get(j);
}
System.out.print("\nNumber of outlets: " + (appliances - (outlets.size() - 1)));
System.out.print("\n" + i);
outlets.clear();
appliances = 0;
}
}
Now for some reason, the outer for loop always runs one less time then it should.
Here is a sample input
3
3 2 3 4
10 4 4 4 4 4 4 4 4 4 4
4 10 10 10 10
And expected output
Number of outlets: 7
Number of outlets: 31
Number of outlets: 37
However, my output is
Number of outlets: 7
Number of outlets: 31
Similarly, for input
5
5 4 3 2 5 6
4 3 2 2 3
7 4 4 4 4 4 4 4
5 4 3 3 4 4
8 9 9 9 9 9 9 9 9
I expect an output of
Number of outlets: 16
Number of outlets: 7
Number of outlets: 22
Number of outlets: 14
Number of outlets: 65
But receive an output of
Number of outlets: 16
Number of outlets: 7
Number of outlets: 22
Number of outlets: 14
If I comment out the following two lines contained within for loop(int j)
for (int j = 0; j < stripCount; j++) {
//outlets.add(scnr.nextInt());
//appliances += outlets.get(j);
}
And add print(i), the for loop iterates as many times as it should.
Kattis validates your code by inspecting your program's standard output. If even a single character is different than the judge expects, your submission will fail, and Kattis will only report "Wrong answer" without any reason, actual/expected diff or other diagnostics.
Therefore, it's critical to pay close attention to the expected output format in the problem description and sample test cases.
For the first sample input, we're given:
3
3 2 3 4
10 4 4 4 4 4 4 4 4 4 4
4 10 10 10 10
And the expected output is:
7
31
37
But your output is different:
Number of outlets: 7
0
Number of outlets: 31
1
Number of outlets: 37
2
This contains unnecessary "Number of outlets: " prefixes as well as an i for each test case. Sure, to a human, this is fine, but Kattis' runner program isn't smart enough to understand that you basically got it right.
Removing the i print and changing your result print to match what Kattis is asking for passes the submission tests:
System.out.println(appliances - (outlets.size() - 1));
As for the missing last line, you're probably not flushing that final buffer in the IDE. Either add a final newline or press Enter manually if you have interactive capabilities. This appears to be an environment misunderstanding, not a code problem.
I have a code which produces result in a loop in simmilar fashion:
//loop to write header for b (0-5)
(for int a = 0; a <5 ;a++){
//System.out.print(a + "| ");
IntStream.range(b = 0, 5 ).parallel().forEach(b -> {
int result = a*b;
//System.out.print(result + " ");
});
System.out.println("");
)
This was my attempt. The commented system outs basically done what i needed, except as parallel take's stuff in whatever order, my lines got mixed. How can I make sure, to get something like this? Instead of lines with random order of numbers in?
0 | 0 0 0 0 0
1 | 0 1 2 3 4
2 | 0 2 4 6 8
....
First of all, your problem is not one that is well-suited for parallelism. The overhead that parallelism provides far outweighs any savings you get by running your sums at the same time.
That said, you may want to consider using something like toArray to collapse your sums to an array, and then print each element in the array.
I'm having a bit of trouble understanding the concept of recursion. I understand that it is basically a method that calls itself and turns a big problem into a bunch of smaller parts to solve it. What I'm having difficulty with is using recursion with an array. Here is an example in my book:
//Precondition: x is an array of n integers
public int recur(int[] x, int n)
{
int t;
if(n == 1)
return x[0];
else
{
t = recur(x, n-1);
if(x[n-1] > t)
return x[n-1];
else
return t;
}
}
If anyone has the time, could you explain what this method does and how it works? Greatly appreciated!
This function returns the largest integer of an integer array.
Lets see how, Your function recur takes an integer array x and its length n.
If the length of array is 1 then the lone element x[0] is the largest one.
Else we get the largest element from the array starting with x[0] to x[n-2](that is array of length n - 1) and so on, when we get the largest element we keep on sending it as the return value till recursion finishes, finally returning the largest value.
This method finds the biggest number among the first n elements of an array.
It works by finding the biggest number among the first n-1 elements; then checking whether the nth element is bigger. The recursion comes in when it finds the biggest number in the first n-1 elements - it does that by calling itself with n-1 in place of n.
Of course, if n is 1, then there's nothing to check - we should just return the first element. This is the "base case" of the recursion.
Note that when I say the nth element, this is actually x[n-1], not x[n] because array indexes start from zero.
In recursion we have what is called base case which is a condition to make the recursion stop. In this situation the base case is if (n==1) where the first element of x[] is returned.
Let's go to the second part of the recursion. The function is calling itself but decrementing n, until it reachs to the base case. Once the base case is returned, the function will compare the first element, now t, with the next one x[n-1] (where n is equal to 2) and return the greater of both. When one value is returned the function goes to its previous call in the stack.
In other words, to analize recursion you should go through the function calls until the base case is reached and once there, start to go back leaded by the returns or the final execution of the function.
As stated in above answers this method will return largest among the first n values in the array, i would like to show this answer pictorially
Assume array with values
{5, 4, 2, 1, 8, 6, 4, 2, 12, 33}
-----------------------------------------------------------------------------------
caller | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1
===================================================================================
t | 12 | 8 | 8 | 8 | 8 | 5 | 5 | 5 | 5 | none
===================================================================================
return | 33 | 12 | 8 | 8 | 8 | 8 | 5 | 5 | 5 | 5
Here caller is the invoker of recursive method. and in the n = 10, 33 will be compared with 12 and 33 will be returned to invoker. Hence invoker will received largest value in the array.
Hello i am a beginner in java programming, recently i am studying Threads, i am having problem in output of this program.
class s1 implements Runnable
{
int x = 0, y = 0;
int addX() {x++; return x;}
int addY() {y++; return y;}
public void run() {
for(int i = 0; i < 10; i++){
System.out.println(addX() + " " + addY());
}
}
public static void main(String args[])
{
s1 run1 = new s1();
s1 run2 = new s1();
Thread t1 = new Thread(run1);
Thread t2 = new Thread(run2);
t1.start();
t2.start();
}
}
I am getting output like this,
1 1 2 2 1 1 3 3..., please explain why?
The threads are executing asynchronously - so their output will be naturally intertwined, that's to be expected. In your case:
1 1 2 2 1 1 3 3
...The bit I've "bolded" is the output from one thread, the bit I've left plain is the (start of) the output from the other. I can only work this out because of how the program executes - if you had two threads just printing the character "1" for example, it would be impossible to distinguish what thread was printing what character.
Note that the order in which the numbers appear and the way they intertwine is completely arbitrary - it could have just as easily been something like:
1 1 1 1 2 2 3 3 2 2..
...Or any other possible combination. Don't rely on the order that you happen to get for any particular program, it's completely undefined.
Each instance of the s1 class has its own variables, so they will increment independent of each other. If you only made one instance, the output would be 1 1 2 2 3 3 ....
If you take two threads each printing 1 1 2 2 3 3 ..., you will see the two streams mixed up. As long as it outputs the correct number of each number, in the right order, it is doing what you expect. You cannot expect how the threads will be scheduled.
So, you might see 1 1 2 2 3 3 1 1 2 2 3 3... or 1 1 1 1 2 2 2 2 3 3 3 3... or any other variation.
(You might even get lucky and see 1 1 1 1 2 2 2 2 3 3 3 3 ..., one day, if the scheduler slices in a certain way)
EDIT: Also read this answer on thread-safety within the println call.
Try executing this code:
class Test extends Thread {
Test(String name) {
super(name);
}
int x = 0, y = 0;
int addX() {x++; return x;}
int addY() {y++; return y;}
public void run() {
for(int i = 0; i < 10; i++)
System.out.println(addX() + " " + addY() + ", name:" + getName());
}
public static void main(String args[]) {
Test run1 = new Test("thread1");
Test run2 = new Test("thread2");
run1.start();
run2.start();
}
}
You will get output similar to this one:
1 1, name:thread2
2 2, name:thread2
1 1, name:thread1
2 2, name:thread1
3 3, name:thread2
3 3, name:thread1
That is because treads do not execute synchronously. You don't know when will one be executed. In your code 1 1 and then later again 1 1 is just the output of two threads doing the same thing.
public class EulerProblem14 {
int chainLength=1;
public int findChainLength(int number){
System.out.println("number "+number);
System.out.println("Chainlength "+chainLength);
if(number==1){
System.out.println("the number is finally 1 return chain length");
return chainLength;
}
if(number%2==0){
chainLength++;
return findChainLength(number/2);
}
else {
chainLength++;
findChainLength(number*3+1);
}
System.out.println("THIS SHOULD NOT BE EXECUTED");
return -1;
}
public static void main(String args[]){
System.out.println(new EulerProblem14().findChainLength(13));
}
While solving Project Euler Problem 14, I came across a weird problem in method return in java I never faced before . In the above method when the number is finally 1 it should return the count of a chain . But this is the output for input 13 .
number 13 Chainlength 1
number 40 Chainlength 2
number 20 Chainlength 3
number 10 Chainlength 4
number 5 Chainlength 5
number 16 Chainlength 6
number 8 Chainlength 7
number 4 Chainlength 8
number 2 Chainlength 9
number 1 Chainlength 10
the number is finally 1 return chain length
THIS SHOULD NOT BE EXECUTED
THIS SHOULD NOT BE EXECUTED
-1
The problem is in the last part when the number becomes 1 instead of returning chainlength = 10 it somehow skips it and executes code which should never be executed and returns -1 . It runs fine for all powers of 2 like 1,2,4,8 but fails for others .
This is probably a stupid mistake on my part . Nonetheless it is a problem for me .
I haven't looked in detail, but I suspect this:
else {
chainLength++;
findChainLength(number*3+1);
}
should actually be:
else {
chainLength++;
return findChainLength(number*3+1);
}
You should then be able to remove the last two lines of the method entirely, as they're unreachable.