Why am i getting Time limit exceeded for ans for my this code?
I tried this question on CodeChef.My logic is correct but my answer is showing time limit exceeded , i don't know why ?
http://www.codechef.com/problems/CHEFRP
package test;
import java.io.*;
import java.util.*;
public class Test
{
public static void main(String[] args)throws IOException{
int TESTCASES;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
TESTCASES=Integer.parseInt(br.readLine());
int b=2*TESTCASES,i=0,m,l;
int a;
String[] lines=new String[b];
int[] N=new int[TESTCASES];
int[][] Ai =new int[TESTCASES][100001];
int[] min=new int[TESTCASES];
int flag=0,minusonecase=-1;
int[] sum=new int[TESTCASES]
;
for(a=0;a<b;a++)
{
lines[a]=br.readLine();
if(a%2==0)
{
N[a/2]=Integer.parseInt(lines[a]);
}
if(a%2!=0)
{
StringTokenizer stz=new StringTokenizer(lines[a]);
for(l=0;l<100001;l++)
{
if(stz.countTokens()!=0)
{
Ai[((a-1)/2)][l]=Integer.parseInt(stz.nextToken());
}
else{
break;
}
}
}
}
for(a=0;a<TESTCASES;a++)
{
min[a]=Ai[a][0];
for(l=0;l<N[a];l++)
{
if(min[a]>Ai[a][l])
{
min[a]=Ai[a][l];
}
sum[a]=sum[a]+Ai[a][l];
}
sum[a]=sum[a]+2-min[a];
}
for(a=0;a<TESTCASES;a++)
{
for(l=0;l<N[a];l++)
{
if(Ai[a][l]==1)
{
System.out.println(minusonecase);
flag=1;
break;
}
}
if(flag==1)
{
flag=0;
continue;
}
System.out.println(sum[a]);
}
}
}
Please read the question correctly -
Rupsa recently started to intern under Chef. He gave her N type of ingredients of varying quantity A1, A2, ..., AN respectively to store it. But as she is lazy to arrange them she puts them all in a storage box.
Chef comes up with a new recipe and decides to prepare it. He asks Rupsa to get two units of each type ingredient for the dish. But when she went to retrieve the ingredients, she realizes that she can only pick one item at a time from the box and can know its type only after she has picked it out. The picked item is not put back in the bag.
She, being lazy, wants to know the maximum number of times she would need to pick items from the box in the worst case so that it is guaranteed that she gets at least two units of each type of ingredient. If it is impossible to pick items in such a way, print -1.
You are not handling the case , where one of the ingredients has less than 2 unit, in which case you should be printing -1.
Related
As title says I need to do the following. But I somehow am getting the wrong answer, perhaps something with the loops is wrong?
And here's what I have coded so far, but it seems to be giving me the wrong results. Any ideas, help, tips, fixes?
import java.util.ArrayList;
public class pro1
{
private String lettersLeft;
private ArrayList<String> subsets;
public pro1(String input)
{
lettersLeft = input;
subsets = new ArrayList<String>();
}
public void createSubsets()
{
if(lettersLeft.length() == 1)
{
subsets.add(lettersLeft);
}
else
{
String removed = lettersLeft.substring(0,1);
lettersLeft = lettersLeft.substring(1);
createSubsets();
for (int i = 0; i <= lettersLeft.length(); i++)
{
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
public void showSubsets()
{
System.out.print(subsets);
}
}
My test class is here:
public class pro1
{
public static void main(String[] args)
{
pro1s = new pro1("abba");
s.createSubsets();
s.showSubsets();
}
}
Try
int numSubsets = (int)java.lang.Math.pow(2,toSubset.length());
for (int i=1;i<numSubsets;i++) {
String subset = "";
for (int j=0;j<toSubset.length();j++) {
if ((i&(1<<j))>0) {
subset = subset+toSubset.substring(j,j+1);
}
}
if (!subsets.contains(subset)) {
subsets.add(subset);
}
}
where toSubset is the string that you wish to subset (String toSubset="abba" in your example) and subsets is the ArrayList to contain the results.
To do this we actually iterate over the power set (the set of all subsets), which has size 2^A where A is the size of the original set (in this case the length of your string).
Each subset can be uniquely identified with a number from 0 to 2^A-1 where the value of the jth bit (0 indexed) indicates if that element is present or not with a 1 indicating presence and 0 indicating absence. Note that the number 0 represents the binary string 00...0 which corresponds to the empty set. Thus we start counting at 1 (your example did not show the empty set as a desired subset).
For each value we build a subset string by looking at each bit position and determining if it is a 1 or 0 using bitwise arithmetic. 1<<j is the integer with a 1 in the jth binary place and i&(i<<j) is the integer with 1's only in the places both integers have a 1 (thus is either 0 or 1 based on if i has a 1 in the jth binary digit). If i has a 1 in the jth binary digit, we append the jth element of the string.
Finally, as you asked for unique subsets, we check if we have already used that subset, if not, we add it to the ArrayList.
It is easy to get your head all turned around when working with recursion. Generally, I suspect your problem is that one of the strings you are storing on the way down the recursion rabbit hole for use on the way back up is a class member variable and that your recursive method is a method of that same class. Try making lettersLeft a local variable in the createSubsets() method. Something like:
public class Problem1
{
private String originalInput;
private ArrayList<String> subsets;
public Problem1(String input)
{
originalInput = input;
subsets = new ArrayList<String>();
}
// This is overloading, not recursion.
public void createSubsets()
{
createSubsets(originalInput);
}
public void createSubsets(String in)
{
if(in.length() == 1)
{
// this is the stopping condition, the bottom of the rabbit hole
subsets.add(in);
}
else
{
String removed = in.substring(0,1);
String lettersLeft = in.substring(1);
// this is the recursive call, and you know the input is getting
// smaller and smaller heading toward the stopping condition
createSubsets(lettersLeft);
// this is the "actual work" which doesn't get performed
// until after the above recursive call returns
for (int i = 0; i <= lettersLeft.length(); i++)
{
// possible "index out of bounds" here if subsets is
// smaller than lettersLeft
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
Something to remember when you are walking through your code trying to think through how it will run... You have structured your recursive method such that the execution pointer goes all the way down the recursion rabbit hole before doing any "real work", just pulling letters off of the input and pushing them onto the stack. All the "real work" is being done coming back out of the rabbit hole while letters are popping off of the stack. Therefore, the first 'a' in your subsets list is actually the last 'a' in your input string 'abba'. I.E. The first letter that is added to your subsets list is because lettersLeft.length() == 1. (in.length() == 1 in my example). Also, the debugger is your friend. Step-debugging is a great way to validate that your code is actually doing what you expect it to be doing at every step along the way.
I am writing a program that will import values from a txt file in to an array, I then need to count how many of those elements are greater than or equal to 36. The data imports fine, and the total amount of values it displays is correct, but I can not get it display the amount of times the number 36 is found in the file. Thanks for any help!
public static void main(String[] args) throws Exception {
int[] enrollments = new int [100];
int count;
int FullClass;
double ClassPercentage;
return count (number of data items)
count = CreateArray(enrollments);
System.out.println (count );
FullClass = AddValues (enrollments);
System.out.println (FullClass)
ClassPercentage= FullClass/count;
System.out.print(ClassPercentage +"% of classes are full");
}//end main
/**
*
* #param classSizes
*/
public static int CreateArray(int[] classSizes) throws Exception{
int count = 0;
File enrollments = new File("enrollments.txt");
Scanner infile = new Scanner (enrollments);
while (infile.hasNextInt()){
classSizes[count] = infile.nextInt();
count++}//end while
return count; //number of items in an array
} // end CreateArray
/**************************************************************************/
/**
*
* #throws java.lang.Exception
*/
public static int AddValues (int[] enrollments) throws Exception{
{
int number = 0;
int countOf36s = 0;
while (infile.hasNextInt()) {
number = infile.next();
classSizes[count] = number;
if(number>=36) {
countOf36s++;
}
count++;
}
return countOf36s;
}// end AddValues
}//end main
Try this code to count the numbers that are greater than or equal to 36 while you are reading the file only. Change the code in your createArray method or write the below logic where ever you want to.
I tried executing this program. It works as expected. See below code
import java.util.*;
import java.io.*;
public class Test { //Name this to your actual class name
public static void main(String[] args) throws Exception {
int[] enrollments = new int [100]; //assuming not more than 100 numbers in the text file
int count; //count of all the numbers in text file
int FullClass; //count of numbers whose value is >=36
double ClassPercentage;
count = CreateArray(enrollments);
System.out.println (count);
FullClass = AddValues (enrollments);
System.out.println (FullClass);
ClassPercentage= FullClass/count;
System.out.print(ClassPercentage +"% of classes are full");
}
//Method to read all the numbers from the text file and store them in the array
public static int CreateArray(int[] classSizes) throws Exception {
int count = 0;
File enrollments = new File("enrollments.txt"); //path should be correct or else you get an exception.
Scanner infile = new Scanner (enrollments);
while (infile.hasNextInt()) {
classSizes[count] = infile.nextInt();
count++;
}
return count; //number of items in an array
}
//Method to read numbers from the array and store the count of numbers >=36
public static int AddValues (int[] enrollments) throws Exception{
int number = 0;
int countOf36s = 0;
for(int i=0; i<enrollments.length; i++) {
number = enrollments[i];
if(number>=36) {
countOf36s++;
}
}
return countOf36s;
}
}
Your code indicates that you might have misunderstood a couple of concepts and stylistic things. As you say in your comments you are new at this and would like some guidance as well as the answer to the question - here it is:
Style
Method names and variable names are by convention written starting with a lower case letter and then in camel case. This is in contrast to classes that are named starting with an upper case letter and camel case. Sticking to these conventions make code easier to read and maintain. A full list of conventions is published - this comment particularly refers to naming conventions.
Similarly, by convention, closing braces are put on a separate line when they close loops or if-else blocks.
throws Exception is very general - it's usual to limit as much as possible what Exceptions your code actually throws - in your case throws FileNotFoundException should be sufficient as this is what Scanner or File can throw at runtime. This specificity can be useful to any code that uses any of your code in the future.
Substance
You are creating the array up front with 100 members. You then call CreateArray which reads from a file while that file has more integers in it. Your code does not know how many that is - let's call it N. If N <= 100 (there are 100 integers or less), that's fine and your array will be populated from 0 to N-1. This approach is prone to confusion, though - the length of your array will be 100 no matter how many values it has read from the file - so you have to keep track of the count returned by CreateArray.
If N > 100 you have trouble - the file reading code will keep going, trying to add numbers to the array beyond its maximum index and you will get a runtime error (index out of bounds)
A better approach might be to have CreateArray return an ArrayList, which can have dynamic length and you can check how many there are using ArrayList.size()
Your original version of AddValues called CreateArray a second time, even though you pass in the array which already contains the values read from file. This is inefficient as it does all the file I/O again. Not a problem with this small example, but you should avoid duplication in general.
The main problem. As per prudhvi you are checking the number of integers in the file against 36, not each value. You can rectify this as suggested in that answer.
You do ClassPercentage= FullClass/count; Although ClassPercentage is a double, somewhat counter intuitively - because both the variables on the Right Hand Side (RHS) are int, you will have an int returned from the division which will always round down to zero. To make this work properly - you have to change (cast) one of the variables on the RHS to double before division e.g. ClassPercentage= ((double)FullClass)/count;.
If you do keep using arrays rather than ArrayList, be careful what happens when you pass them into methods. You are passing by reference, which means that if you change an element of an array in your method, it remains changed when you return from that method.
In your new version you do
...
classSizes[count] = number;
if(number>=36) {
...
You almost certainly mean
...
number = classSizes[count];
if(number>=36) {
...
which is to say in programing the order of the assignment equals is important, so a = b is not equivalent to b = a
Code
A cleaned up version of your code - observing all the above (I hope):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ClassCounter
{
public static void main(String[] args) throws FileNotFoundException
{
int count;
int fullClass;
double classPercentage;
ArrayList<Integer> enrollments = createArray();
count = enrollments.size();
System.out.println(count);
fullClass = addValues(enrollments);
System.out.println(fullClass);
classPercentage = fullClass / count;
System.out.print(classPercentage + "% of classes are full");
}
/**
* scans file "enrollments.txt", which must contain a list of integers, and
* returns an ArrayList populated with those integers.
*
* #throws FileNotFoundException
*/
public static ArrayList<Integer> createArray() throws FileNotFoundException
{
ArrayList<Integer> listToReturn = new ArrayList<Integer>();
File enrollments = new File("enrollments.txt");
Scanner infile = new Scanner(enrollments);
while (infile.hasNextInt())
{
listToReturn.add(infile.nextInt());
}
return listToReturn;
}
/**
* returns the number of cases where enrollments >= 36 from the list of
* all enrollments
*
* #param enrollments - the list of enrollments in each class
* #throws FileNotFoundException
*/
public static int addValues(ArrayList<Integer> enrollments)
{
int number = 0;
int countOf36s = 0;
int i = 0;
while (i < enrollments.size())
{
number = enrollments.get(i);
if (number >= 36)
{
countOf36s++;
}
}
return countOf36s;
}
}
I am trying to solve a question on Hackerearth. The competition had ended long time back.
http://www.hackerearth.com/lenskart-hiring-challenge/algorithm/big-p-and-punishment-5/description/
The Problem Statement
Big P has become a Physical Education teacher at Hack International School.
Today, the students of class XII have been very indisciplined and he decides to punish them all.
He makes all of the N student (numbered 1 to N ) to stand in a line and asks them to sit down on their knees.
Students know that Big P is a very cruel and sadistic person and students start to sit down themselves when they see a friend sit down.
However, there are always some students who do not follow the trend. Now when Big P sees that happen , he slaps that student and makes him sit down. The same process as above is followed and is stopped when any - one student in the line refuses to sit down by himself.
Given the students that Big P slaps to make them sit down , you need to tell the total no. of students who sat down in that line.
Note: It is not necessary that if A is friend of B then B is also friend of A.
Input Format :
First Line Contains an integer T denoting no of test cases. Each test case begins with a line containing three integers N, F, S where N is the number of students in the line . Next F lines have two integers A and B denoting the friendship between the students A and B. Next S lines have one integer X denoting the student that was slapped by Big P .
Output Format:
For each test case, output a line containing one integer, the total number of students that sit down in that line.
[ T<=10 , N ,F , S <=10000 ]
Sample Input
1
3 2 1
1 2
2 3
2
Sample Output
2
I have written a Java Code for the same.
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Arrays;
#SuppressWarnings("unchecked")
class Graph
{
static int visited[];
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcases;
int N,F,S,n;
int a,b;
testcases=Integer.parseInt(br.readLine());
while(--testcases>=0)
{
String[] s = br.readLine().split(" ");
N=Integer.parseInt(s[0]);
F=n=Integer.parseInt(s[1]);
S=Integer.parseInt(s[2]);
visited=new int[N+1];
Arrays.fill(visited,0);
ArrayList[] adj=new ArrayList[N+1];
while(--n>=0)
{
s = br.readLine().split(" ");
a=Integer.parseInt(s[0]);
b=Integer.parseInt(s[1]);
if(adj[a]==null){
adj[a]=new ArrayList<Integer>();
}
(adj[a]).add(b);
}
int root;
for(int i=1;i<=S;i++)
{
root=Integer.parseInt(br.readLine());
dfs(adj,root);
}
int ans=0;
for(int i=1;i<=N;i++)
{
if(visited[i]==1){
++ans;
}
}
System.out.println(ans);
}
}
static void dfs(ArrayList adj[],int r)
{
int curr;
if(visited[r]!=1)
{
ArrayList base=adj[r];
if(base!=null)
{
Iterator itr=base.iterator();
while(itr.hasNext())
{
curr=(int)itr.next();
if(visited[curr]==0)
{
dfs(adj,curr);
}
}
}
visited[r]=1;
//System.out.println(r);
}
}
}
It passes for the 1st testcase,but gives an NZEC error for the remaining testcases.
I tried making changes like :
Used Scanner instead of Stream Reader.
Removing static arrays
None of these is helping.
Please help me out in identifying the fault.
I've been working ahead in my intro class and I've almost finished my last project, Keno. its a betting game that rewards money according to how many numbers you matched with the dealer. I'm having issues on where to put the betting aspect, they start with 100$ and are asked to wage a certain amount of money. I don't know which method that would go under for it to still work because my methods aren't voids, so i wont be able to return more than one data value.
My second issue, maybe the more important one, is that they need to be unique numbers. To do that i would need to search the array of numbers every time to see if they match, or use an array of booleans to keep track of the numbers. I don't know how i would do the second but i have a good idea of what i would do with the first. The issue is that im using a do while already, im not sure how i could add the for loop with a nested for loop in. Here is my code, sorry if its messy, i know my teacher hates my curly braces:
package Keno;
import cs1.Keyboard;
public class Keno {
public static void main(String[]args){
int userArr[]=user();
int compArr[]=computer();
int howMany=matchNums(compArr,userArr);
int moneyGained=betting(howMany);
System.out.println("You matched "+howMany+" numbers");
System.out.println("You have gained "+moneyGained+" dollars!");
}
public static int[] computer(){
int []compChoice=new int[20];
for(int x=0;x<compChoice.length;x++){
compChoice[x]=(int)(Math.random()*81);
}
return compChoice;
}
public static int[] user(){
int choice[]=new int[7];
System.out.println("Welcome to Keno!");
System.out.println("Choose 7 unique numbers ranging from 1-80");
System.out.println("*************************************************");
//assigns numbers to choice array
for(int x=0;x<choice.length;x++){
do{
int temp=x+1;
System.out.println("number "+temp+": ");
choice[x]=Keyboard.readInt();
}while(choice[x]<0||choice[x]>80);
}
System.out.println("Thanks!");
System.out.println("*************************************************");
return choice;
}
public static int matchNums(int arr1[], int arr2[]){
int count=0;
//checks each array slot individually to see if they match
for(int x=0;x<arr1.length;x++){
for(int y=0;y<arr2.length;y++){
if(arr1[x]==arr2[y]){
count++;
}
}
}
return count;
}
public static int betting(int matches){
int moneyGained=0;
if(matches==7){
moneyGained=12000;
}else if(matches==6){
moneyGained=200;
}else if(matches==5){
moneyGained=20;
}else if(moneyGained==4){
moneyGained=1;
}
return moneyGained;
}
}
The simplest way to add the betting/money concept would be to add an integer which represents how much money the player has (starting at 100). You will have to ask the player how much they want to wager, and then adjust their money accordingly.
public static void main(String[] args) {
int playerMoney = 100;
int wagered = getWager(); // dont forget it has to be 0 < wagered <= 100
// adjust players money according to the wager, and how much they won
For ensuring uniqueness, either one of your ideas would work. I like just checking for the numbers existence already in the array, but the boolean array of size 80 would work too. It just seems like a lot for only 7 numbers though.
Here is a question about Stack on StackOverflow.
My question might seem very very vague but if you check my program which I have written then you might understand what I am trying to ask.
I have implemented the stack myself. I present the user with 3 choices. Push, Pop and View the stack. When view(display) method is called then bunch of 0s show instead of nothing. We know the stack contains nothing unless we put something on it. But since my implemented stack is stack of integers using array, the display method when called shows bunch of 0s(the default values of integers in the array). How do I show nothing instead of 0s. I know I can add ASCII for whitespace character but I think it would still violate the rule of stack(Stack should be empty when there is not element, not even code for whitespace).
Here is my program:
import java.util.Scanner;
public class StackClass
{
public static void main(String []args)
{
Scanner input=new Scanner(System.in);
int choice=0;
int push;
Stack stack=new Stack();
do
{
System.out.println("Please select a stack operation:\n1. Press 1 for adding to stack\n2. Press 2 for removing elements from stack\n3. View the stack");
choice=input.nextInt();
switch(choice)
{
case 1:
System.out.println("Please enter the number that you want to store to stack");
push=input.nextInt();
stack.push(push);
case 2:
stack.pop();
case 3:
stack.display();
}
}
while((choice==1)||(choice==2)||(choice==3));
}
}
class Stack
{
private int size;
private int[] stackPlaces=new int[15];
private int stackIndex;
Stack()
{
this.size=0;
this.stackIndex=0;
}
public void push(int push)
{
if(size<15)
{
stackPlaces[stackIndex]=push;
size++;
stackIndex++;
}
else
{
System.out.println("The stack is already full. Pop some elements and then try again");
}
}
public void pop()
{
if(size==0)
{
System.out.println("The stack is already empty");
}
else
{
stackPlaces[stackIndex]=0;
size--;
stackIndex--;
}
}
public void display()
{
System.out.println("The stack contains:");
for(int i=0;i<stackPlaces.length-1;i++)
{
System.out.println(stackPlaces[i]);
}
}
}
In display(), simply change your loop to use size for the loop condition, so that you display the logical number of elements:
for (int i=0;i < size; i++)
{
System.out.println(stackPlaces[i]);
}
Note that your existing loop was only showing 14 of the 15 values, too...
You initialize an array of int-s, of size 15. The int datatype defaults to 0 (as opposed to its wrapper class Integer which defaults to null), so what you are really doing is creating an int array with 15 0's. So, when you loop through the array and print its content, you will get, well, 15 0's.
The solution is, as implied by others, exchange the loop limitation to the size of the stack (the number of elements actually added), rather than the size of the array.
instead of for(int i=0;i<stackPlaces.length-1;i++), do for(int i=0;i<stackIndex;i++)