Polish Matura Mistake in answers? - java

in Polish matura from IT in task 5.1 we have to count of increasing subsequence largest than 3 in file which 310 lines with int values, series is when all piervous values in smaller than next.
In Answers we have the count of increasing subsequence largest than 3 is 14, but i always gets 11, and i dont have idea why.
Some one can tell me what's wrong?
My code:
static int Series = 0;
static int Big = 0;
public static void main(String[] args){
Scanner In = new Scanner(System.in);
String Line = "Seria 1: ";
int Last = 0;
int i = 0;
while(In.hasNext()){
int Current = In.nextInt();
if(Last<Current){
Series++;
Line +=Current+" ";
}
else{
if(Series>=3){
Big++;
System.out.println(Line+"#");
Line="Seria "+(Big+1)+": ";
}
Series = 0;
}
Last = Current;
}
System.out.println(Big);
In.close();
}
There is a file with records: http://wklej.to/phpgW

Ok, as far as I know your program works correctly and returns what you expect. The problem might be the wording. "Amount of increasing subsequences >= 3" can actually refer to two distinct ways of approaching it:
First one is your way, the end of the sequence is just before the increasingness stops. You get sequences like {3,4,5} {9,12,45,23049,2123455}.
The second one is trickier - It doesn't matter if increasingness continues, if you have three numbers in an increasing sequence it counts. In that interpretation input 3,4,5,6,7 leads to {3,4,5} {4,5,6} {5,6,7}, and possibly even {3,4,5,6} {4,5,6,7} and {3,4,5,6,7}.
This is pure speculation, but it would fit quite nicely if they asked for the second interpretation (hopefully in non-ambiguous way) with sequence length = 3. Than your input would indeed return 14.

Related

How would you go about adding a space between every random number? [duplicate]

This question already has answers here:
Elegantly Insert Spaces During Loop Between Values Without Trailing Space
(3 answers)
Java: join array of primitives with separator
(9 answers)
Closed 6 months ago.
I'm trying to get the console to output 100 random numbers between 0 and 50, all on the same line with a space between each. I have everything but the formatting for the space. I know I need to use the printf function, but am completely lost on how to properly impliment it. This is what I have so far, but the output formatting is incorrect.
public static void main(String[] args) {
Random rand = new Random();
for (int count = 0; count <=100; count++)
{
int randomNum = rand.nextInt(51);
System.out.printf("%1d %1d", randomNum, randomNum);
}
}
Here's a version neither using a condition or a separate first print but avoiding any leading or trailing space.
public static void main(String[] args) {
Random rand = new Random();
String delim="";
for (int count = 0; count <100; count++)//fixed as per comments elsewhere.
{
int randomNum = rand.nextInt(51);
System.out.printf("%s%1d", delim,randomNum);
delim=" ";// Change this to delim="," to see the action!
}
}
It's a classic faff to print out n items with n-1 internal separators.
PS: printf feels like overkill on this. System.out.print(delim+randomNum); works just fine.
[1] Your code actually prints 101 numbers. Embrace the logic computers (and java) applies to loops and 'the fences' (the start and end): The first number is inclusive, the second is exclusive. By doing it that way, you just subtract the two to know how many items there are. so, for (int count = 0; count < 100; count++) - that loops 100 times. Using <= would loop 101 times.
[2] You're making this way too complicated by focusing on the notion of 'there must be a space in between 2', as if the 2 is important. What you really want is just 'after every random number, print a space'. The only downside is that this prints an extra space at the end, which probably doesn't matter:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum + " ");
}
is all you actually needed. No need to involve printf:
I know I need to use the printf function
No, you don't. No idea why you concluded this. It's overkill here.
If you don't want the extra space.. simply don't print it for the last number:
for (int count = 0; i < 100; count++) {
System.out.print(randomNum);
if (count < 99) System.out.print(" ");
}
[3] You mention that the code shuold print it all 'on one line', which perhaps suggests the line also needs to actually be a line. Add, at the very end, after the loop, System.out.println() to also go to a newline before you end.

USA Coding Olympiad 1st Timed Out and/or Too Much Memory

A few days ago, I participated in the USA coding olympiad for the first time, and got the same error on all my codes. I can't figure out why because it told me that I did incredibly well on the first test case, so I don't understand how the other 9 all timed out. Could someone please explain what is wrong with my code.
Problem
Error Message
import java.io.*;
public class milkmeasure {
private static int [] cows ={7,7,7};
public static void main(String[] args) throws IOException {
// initialize file I/O
BufferedReader br = new BufferedReader(new FileReader("measurement.in"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("measurement.out")));
int N = Integer.parseInt(br.readLine());
String [] entries = new String [N];
for (int i=0;i<N;i++){
entries [i]= br.readLine();
}
int topCow = 1;
int finalN = 0;
for (int i=0; i<N; i++){
String lowEntry = entries[lownum(N,entries)];
String name = lowEntry.substring(2,lowEntry.substring(2).indexOf(" ")+2);
int effect = Integer.parseInt(lowEntry.substring(lowEntry.substring(2).indexOf(" ")+3));
if (name.equals("Bessie")){cows[1]+=effect;}
else if (name.equals("Elsie")){cows[2]+=effect;}
else if (name.equals("Mildred")){cows[0]+=effect;}
int newTop = findTop();
if (newTop!=topCow){finalN++;}
topCow = newTop;
entries[lownum(N,entries)]="101 ";
}
pw.println(finalN);
pw.close();
}
private static int lownum (int N, String [] entries){
int lowNum = 101;
int returnInt=0;
for (int i =0; i<N; i++){
int a = Integer.parseInt(entries[i].substring(0,entries[i].indexOf(" ")));
if (a<lowNum){
lowNum = a;
returnInt =i;
}
}
return returnInt;
}
private static int findTop (){
int maxval = 0;
int returnval =0;
for (int i =0; i<3; i++){
if (cows[i]>= maxval){
returnval += cows[i]*cows[i];
maxval=cows[i];
}
}
return returnval;
}
}
Algorithmic complexity issue
For each entry, your main() method invokes lownum() (twice). lownum() scans all the entries to identify and return the one with the lowest day number. Overall, then, the complexity of your program scales at least as o(N2) in the number of entries.
That lower bound could be reduced to o(N log N) by sorting the entries once and then simply processing them in order.
With a reasonable bound on the maximum day number of the entries, and the given assurance that there is at most one entry per day, it could be reduced further to o(N) by assigning entries to an array or List at positions corresponding to their day numbers, so that no actual sorting is required.
It turns out that this is the main driver of your asymptotic complexity, so improving this lower bound allows you to improve the upper bound, too, all the way to O(N).
General efficiency issues
Since the problem specifies that there will be at most one entry per day for 100 days, however, you are probably in a regime that is still strongly influenced by (in-)efficiencies that affect the cost coefficient. And you in fact have quite a few inefficiencies. Among them:
You parse each entry many times, scanning to split them into fields and converting some of those into integers. That's terribly wasteful. It would be far more efficient to parse each entry just once, and then store the parsed results. In fact, you can get the parsing at input for almost free by using a Scanner.
You invoke the lownum() method twice for each entry. The current implementation of this method is expensive, as discussed above, and nothing changes between the first and second invocation that would affect the result.
(minor) you perform full string comparisons on the cow names, even though it would be sufficient to look only at their first letters
(minor) you invoke separate methods to find the next entry and to compute the new top cow. Method invocation is comparatively expensive, so it is a bit inefficient to make large numbers of invocations of methods that do very little work. That's probably not a significant effect for your particular code, however.

Code chef :ODD , fastest way to calculate the nearest power of 2 for a given large number?

The link to the problem on codechef is:
http://www.codechef.com/problems/DCE05
The problem is:
The contestants have to stand in a line. They are given the numbers in the order in which they stand, starting from 1. The captain then removes all the contestants that are standing at an odd position.
Initially, standing people have numbers - 1,2,3,4,5...
After first pass, people left are - 2,4,...
After second pass - 4,....
And so on.
You want to board the ship as a crew member. Given the total number of applicants for a position, find the best place to stand in the line so that you are selected.
Input
First line contains the number of test cases t (t<=10^5). The next t lines contain integer n, the number of applicants for that case. (n<=10^9)
Output
Display t lines, each containing a single integer, the place where you would stand to win a place at TITANIC.
Example
Input:
2
5
12
Output:
4
8
I noticed a pattern:
For 1 : Output=1 (2^0)
For 2 : Output=2 (2^1)
For 3 : Output=2 (2^1)
For 4 : Output=4 (2^2)
For 5 : Output=4 (2^2)
For 6 : Output=4 (2^2)
For 7 : Output=4 (2^2)
For 8 : Output=8 (2^3) ans so on
So the answer every time is the nearest power of 2 which is <=number.
Here's my code:
import java.io.*;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
int x=0;
int output[]=new int[n];
for(int i = 0; i < n; i++)
{
output[i]=(int) Math.pow(2, Math.floor(Math.log(Integer.parseInt(br.readLine()))/Math.log(2)));
}
for(int i=0; i<n;i++)
{
System.out.println(output[i]);
}
}
}
Approach 1: I used Math.pow() to calculate powers of two in a loop until is becomes <= number , which I suppose was very inefficient.
Approach 2: I replaced Math.pow() with *2 in loop. (Still time exceeded)
Approach 3: I replaced multiplication by 2 with left shift in loop. (Still time exceeded)
Approach 4: I replaced loop with that log 2 logic, I found on stackverflow). (Still time exceeded)
Still it's showing time exceeded.
What is the fastest way to do this?
Be ensured that Integer.highestOneBit is the fastest part of your code. Even your original version was most probably way faster than parsing and formatting. I tried myself and succeeded with
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (sb.length() > 100000) {
System.out.print(sb);
sb.delete(0, sb.length());
}
final int x = Integer.parseInt(br.readLine());
final int y = Integer.highestOneBit(x);
sb.append(y).append("\n");
}
System.out.print(sb);
The computation is trivial, so I guessed the problem was the output and added some buffering. There's probably a simpler way, but I don't care.
Another possibility is that the site works non-deterministically and I was just lucky.

How to create statistics from output of Java code?

Summary: I need a function based on the output. The problem is
connecting Eclipse or a Java code with another software.
I'm studying Physics. I needed a code that works the following way:
first, it declares a random number n;
then it outputs a "winner" number (based on some rules; the code
itself is irrelevant now I think), 20 times (but should be more,
first I need something to record the values, though).
I have n and 20 other numbers which are each between 1 and n (including 1 and n). I want, after compiling the code once, to see the 20 values, how they are distributed (for example, are they around one particular number, or in a region, is there a pattern (this is based on the rules, of course)).
The problem is, I'm only familiar with basic Java (I used eclipse), and have no clue on how I should register for example 2000 instead of the 20 numbers (so for an n number the code should print 2000 or more numbers, which should appear on a function: domain of the function is 1, 2, ..., n, and range is 0, 1, ..., 2000, as it might happen that all 2000 numbers are the same). I thought of Excel, but how could I connect a Java code with it? Visual interpretation is not necessary, although it would make my work easier (I hope, at least).
The code:
import java.util.Random;
public class korbeadosjo {
public static void main(String Args[]){
Random rand = new Random();
int n = (rand.nextInt(300)+2);
System.out.println("n= " + n);
int narrayban = n-1;
int jatekmester = n/2;
int jatekmesterarrayban = jatekmester-1;
System.out.println("n/2: " + jatekmester);
for(int i=0; i<400; i++){
int hanyembernelvoltmar = 1;
int voltmar[] = new int[n];
voltmar[jatekmesterarrayban]=1;
int holvan=jatekmester;
int holvanarrayban = holvan-1;
fori: for(;;){
int jobbravagybalra = rand.nextInt(2);
switch(jobbravagybalra){
case 0: //balra
if(holvanarrayban ==0){
holvanarrayban = narrayban;
}else {
--holvanarrayban;
};
if(voltmar[holvanarrayban]==0){
voltmar[holvanarrayban] =1;
++hanyembernelvoltmar;
}
break;
case 1: //jobbra
if(holvanarrayban == narrayban){
holvanarrayban = 0;
} else {++holvanarrayban;};
if(voltmar[holvanarrayban]==0){
voltmar[holvanarrayban]=1;
++hanyembernelvoltmar;
}
break;
}if(hanyembernelvoltmar==n){
System.out.println(holvanarrayban+1);
break fori;
}}}}}
basic Java (I used eclipse)
Unrelated.
I could only find two prompts in your question:
How to create statistics from output of Java code?
You are likely not wanting to get the output alone. Use those numbers in your Java program to find what you want and output it.
How did you store 2000 values? An array, list, queue...? So also iterate on that data structure and generate the statistics you need.
I thought of Excel, but how could I connect a Java code with it?
There is this site.

Average of n numbers in java

Using loop I want to calculate the average of n numbers in Java and when user enters 0 the loop ends.
Here is the code that I have written:
public class start {
public static void main(String[] args) {
System.out.println("Enter an int value, the program exits if the input is 0");
Scanner input = new Scanner (System.in);
int h = 0;
while (input.nextInt() == 0){
int inp = input.nextInt();
int j = inp;
int i = 0;
h = j + i;
break;
}
System.out.println("The total is: "+ h);
}
}
Am I making any logical error?
Don't name the sum h, but sum.
The while-condition is wrong
Why do you use inp and j and i?
There is an unconditional break - why?
You talk about the average. Do you know what the average is?
Your output message is not about average - it is about the sum.
"Am I making any logical error?"
Yes. This looks like a homework problem so I won't spell it out for you, but think about what the value of i is, and what h = j + i means in this case.
You also need to be careful about calling input.nextInt(). What will happen when you call it twice each time through the loop (which is what you are doing)?
Homework, right?
Calling input.nextInt() in the while loop condition and also to fill in int inp means that each trip through the loop is reading two numbers (one of which is ignored). You need to figure out a way to only read one number per loop iteration and use it for both the == 0 comparison as well as for inp.
Additionally, you've done the right thing having h outside the while loop, but I think you're confusing yourself with j and i inside the loop. You might consider slightly more descriptive names--which will make your code much easier to reason about.
You need to keep a counter of how many numbers you read so you can divide the total by this number to get the average.
Edited the while loop:
while(true){
int e=input.nextInt();
if(e==0) break;
h+=e;
numberOfItems++;
}
Your original implementation called nextInt() twice, which has the effect of discarding every other number (which is definitely not what you intended to do).
Assuming that you asking the user only once, to enter and if the number if zero you simply want to display the average. you need a variable declared outside the while loop that will keep adding different numbers entered by the user, along with a second variable which track the number of cases entered by the user and keep incrementing itself by one till number is not zero as entered by the user. And as the user Enters 0, the loop will break and here our Average will be displayed.
import java.util.Scanner;
public class LoopAverage
{
public static void main(String[] args0)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Integer value : ");
int value = -1, sum = 0, count = 0;
while((value = scan.nextInt()) != 0)
{
count++;
sum = sum + value;
}
System.out.println("Average : " + (sum / count));
}
}
Hope that might help,
Regards
yes, oodles of logical errors.
your while loop condition is wrong, you're consuming the first value
you enter and unless that number is 0 you never enter the loop at all
i var has no purpose
you're breaking after one iteration
you're not calculating a running total
you're not incrementing a count for the average dividend
you're not calculating an average
This looks like you threw some code together and posted it. The most
glaring errors would have been found just by attempting to run it.
Some other things to consider:
Make sure to check for divide by 0
If you do an integer division, you might end up with an incorrect
average, as it will be rounded. Best to cast either the divisor or
dividend to a float
variable names should be helpful, get into the habit of using them
I recommend you to refer to the condition of "while" loop: if condition meets, what would the program do?
(If you know a little bit VB, what is the difference between do...until... and do...while...?)
Also, when you call scanner.nextInt(), what does the program do? For each input, how should you call it?
Last but not least, when should you use "break" or "continue"?
For the fundamentals, if you are in a course, recommend you to understand the notes. Or you can find some good books explaining details of Java. e.g. Thinking in Java
Enjoy learning Java.

Categories