Identify the failed test cases - java

I have participated in coding contest, where I have attempt the given problem, so I am supposed to come up with solution which should not only passing all the test cases, also well optimized in terms of time and space complexity, I have passed 3 out of 7 but I am still not able to identify the rest of the test cases, it is possible that I might be missing something, please help me to rectify the below problem statement.
PROBLEM STATEMENT:
The Powerpuff Girls (100 Marks)
Professor Utonium is restless because of the increasing crime in the world. The number of villains and their activities has increased to a great extent. The current trio of Powerpuff Girls is not well to fight the evils of the whole world. Professor has decided to create the maximum number of Powerpuff Girls with the ingredients he has.
There are N ingredients required in a certain quantity to create a Powerpuff Girl. Professor has all the N ingredients in his laboratory and knows the quantity of each available ingredient. He also knows the quantity of a particular ingredient required to create a Powerpuff Girl. Professor is busy with the preparations and wants to start asap.
The villains, on the other hand, want to destroy the laboratory and stop Professor Utonium from creating more Powerpuff girls. Mojo Jojo is coming prepared with ammunition and Him is leading other villains like Princess, Amoeba Boys, Sedusa, Gangreen Gang etc.
Professor does not have much time as villains will reach the laboratory soon. He is starting the process but does not know the number of Powerpuff Girls which will be created. He needs your help in determining the maximum number of Powerpuff Girls which will be created with the current quantity of ingredients.
Example:
Professor Utonium requires 3 ingredients to make Powerpuff Girls. The 3 ingredients are present in the laboratory in the given quantity:
To make a Powerpuff Girl, Professor Utonium requires:
3 units of Ingredient A
6 units of Ingredient B
10 units of Ingredient C
The maximum number of Powerpuff Girls that can be created is 3 as, after 3, Professor will run out of Ingredient C.
Can you determine the maximum number?
Input Format
The first line of input consists of the number of ingredients, N
The second line of input consists of the N space-separated integers representing the quantity of each ingredient required to create a Powerpuff Girl.
The third line of input consists of the N space-separated integers representing the quantity of each ingredient present in the laboratory.
Constraints
1<= N <=10000000 (1e7)
0<= Quantity_of_ingredient <= LLONG_MAX
Output Format
Print the required output in a separate line.
Sample TestCase 1
Input
4
2 5 6 3
20 40 90 50
Output
8
SOLUTION CODE
package com.mzk.poi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class PowerPuffGirls {
private static final String SPACE = " ";
private static final Integer INITAL_IDX = 0;
private static final Integer LOWER_IDX = 1;
private static final Integer SECOND_IDX = 2;
private static final Integer MAX_LINES = 3;
private static final Integer UPPER_IDX = 1000000;
private static String[] UnitsArr = null;
private static String[] totIngrdientsArr = null;
private static int size = 0;
public static void main(String[] args) {
List<Integer> maxPowerPuffGirlsCreationList = new ArrayList<Integer>();
Scanner stdin = new Scanner(System.in);
String[] input = new String[MAX_LINES];
try {
for (int i = 0; i < input.length; i++) {
input[i] = stdin.nextLine();
if (validateIngredienInput(input[INITAL_IDX])) {
System.exit(INITAL_IDX);
}
}
} finally {
stdin.close();
}
int numOfIngredients = Integer.parseInt(input[INITAL_IDX]);
String units = input[LOWER_IDX];
UnitsArr = units.split(SPACE);
String ingredients = input[SECOND_IDX];
totIngrdientsArr = ingredients.split(SPACE);
size = UnitsArr.length;
int[] specifiedArrayOfUnits = convertToIntegerArray(UnitsArr);
int[] totIngredientInLabArray = convertToIntegerArray(totIngrdientsArr);
for (int i = 0; i < size; i++) {
totIngredientInLabArray[i] = Integer.parseInt(totIngrdientsArr[i]);
}
for (int i = 0; i < numOfIngredients; i++) {
maxPowerPuffGirlsCreationList.add(totIngredientInLabArray[i] / specifiedArrayOfUnits[i]);
}
System.out.println(Collections.min(maxPowerPuffGirlsCreationList));
}
/**
* This method validates the first input
* #param noOfIngredients
* #return boolean
*/
private static boolean validateIngredienInput(String noOfIngredients) {
int numOfIngredients = Integer.parseInt(noOfIngredients);
boolean result = false;
if (numOfIngredients <= LOWER_IDX && numOfIngredients <= UPPER_IDX) {
result = true;
return result;
}
return result;
}
/**
* This utility method convert the String array to Integer array
* #param size
* #param specifiedArrayOfUnits
* #return int[]
*/
private static int[] convertToIntegerArray(String[] arrayToBeParsed) {
int array[] = new int[size];
for (int i = INITAL_IDX; i < size; i++) {
array[i] = Integer.parseInt(arrayToBeParsed[i]);
}
return array;
}
}
The above solution has passed 3 test cases, remaining 7 are un identfied,Please help me to rectify or improve this code.

There are several issues with your code:
try {
for (int i = 0; i < input.length; i++) {
input[i] = stdin.nextLine();
if (validateIngredienInput(input[INITAL_IDX])) {
System.exit(INITAL_IDX);
}
}
} finally {
stdin.close();
}
You don't need to check the first row each time you read one line from the input. Instead you run the test only once. You can run it once you read the first line or after you read the whole input. The code can be look like this:
for (int i = 0; i < input.length; i++) {
input[i] = stdin.nextLine();
}
if (!validateIngredienInput(input[INITAL_IDX])) {
System.exit(...);
}
Also, it is not clear what the return value of validateIngredienInput() means. Is true a correct input or is false? Your if() statements checks for the return value being true and quits if it is.
private static boolean validateIngredienInput(String noOfIngredients)
{
int numOfIngredients = Integer.parseInt(noOfIngredients);
boolean result = false;
if (numOfIngredients <= LOWER_IDX && numOfIngredients <= UPPER_IDX) {
result = true;
return result;
}
return result;
}
Your if() condition doesn't make any sense. You are checking if the number of different ingredients is <= 0 and <= 1. This also means that you could rewrite is as just if (numOfIngredients <= 0). But with the description above it is unclear if the validation should return true or false. Depending on what this method should do it can be written as:
private static boolean validateIngredienInput(String noOfIngredients)
{
int numOfIngredients = Integer.parseInt(noOfIngredients);
return numOfIngredients > 0;
}
This will return true if the value is greater than 0.
UnitsArr = units.split(SPACE);
Variable and field names should begin in lowercase, so they don't get confused with class names, which start in uppercase. It looks like UnitsArr is a class, but it is actually a field. So you should rename your field to unitsArr:
unitsArr = units.split(SPACE);
Also check the requirement/format of the input and the limits:
Constraints
1<= N <=10000000 (1e7)
0<= Quantity_of_ingredient <= LLONG_MAX
As you see the quantity of ingredient can be a long value, but you are using Integer.parseInt() and int[] arrays for storing the quantity. You must change this to long to read long values from the input.
int[] totIngredientInLabArray = convertToIntegerArray(totIngrdientsArr);
for (int i = 0; i < size; i++) {
totIngredientInLabArray[i] = Integer.parseInt(totIngrdientsArr[i]);
}
You are converting the String array to an int array with your helper method convertToIntegerArray(), but then you are doing it again with the for loop. You can skip one of the two.
You might also want to check at: What is a debugger and how can it help me diagnose problems?

Related

This program take lot of time for execution

public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
if(t<1 || t>100){System.exit(0);}
ArrayList a=new ArrayList<>();
for(int i=0;i<t;i++){
String s=in.next().toString();
String s2=in.next().toString();
int count=0;
int first=Integer.parseInt(s);
int last=Integer.parseInt(s2);
if(first<1 || last>1000000000){System.exit(0);}
for(int k=first;k<=last;k++){
int sqrt =(int)Math.sqrt(k);
if(sqrt*sqrt==k){count++;}
}
a.add(count);
}
Iterator it=a.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
In this program when i give big input, it takes lots of time to give output. Can someone tell me how to optimize this program.
this program is for finding square root number.
Input: The first line contains , the number of test cases T. T test cases follow, each in a new line.
Each test case contains two space-separated integers denoting s and s2.
Sample Input
2
3 9
17 24
Sample output
2
0
big input:
35
465868129 988379794
181510012 293922871
395151610 407596310
481403421 520201871
309804254 776824625
304742289 566848910
267554756 828997506
387224568 926504395
244571677 871603971
444567315 582147918
334350264 342469009
400474096 410940967
488907300 943628573
26441071 801576263
182001128 267557939
115732998 974318256
192538332 862327048
45429427 307805497
358658006 842644090
92930998 431601473
231163983 893672132
275221547 298953978
351237326 981399371
484598992 985428966
103405553 529324202
37393469 768655346
30179914 482808626
208821550 538302223
154654533 791652309
68424067 854065374
246956110 517538724
51395253 876949418
57778758 368742600
227566632 606529208
This method compute the number of square between two bounds:
public static int squaredNumberInRange(int lowerBound, int upperBound){
double lowerRoot = Math.sqrt(lowerBound);
double upperRoot = Math.sqrt(upperBound);
lowerRoot = Math.ceil(lowerRoot);
upperRoot = Math.floor(upperRoot);
int spread = (int)upperRoot - (int)lowerRoot + 1;
return spread;
}
Complexity is O(1)

Java array -(parallel array)

I am struggling with Arrays (java)
Since this is the first time to learn about java in my life, I have no idea how to start it. I have just learned how to declare arrays and so on. However, this is too complicated for me. I think I can get guidelines if I see this answer. Can anybody help me out?
the prog
Read the java.util.Scanner (API). Your code works. You can do what you want with the scores, just read them from the file and cast them to the appropriate data types (integers) for calculating average scores etc.
The variables are strings, so you must cast them to numbers to make your calculation.
You can use arraylist ArrayList<TeamMember> as an instance variable of TeamMembers for your Teams or a collection with primitive types for the team but I think best is if you make classes for Team, TeamMember and Score that you instanciate in your Bowling class. You can find this information anywhere.
import java.util.Scanner;
//...
Team usa = new Team();
Team mexico = new Team();
TeamMember person = new TeamMember(usa); //Harry plays for the US
...
Scanner in = new Scanner(System.in);
int num = in.nextInt();
If you know that every third input is a score then you can check modulo 3 (% 3) to know which iteration is divisible by 3. .
I have done about 40% of your request, i think that's enough for you to go on. You should be able to finish it on your own.
If you have further question,just leave a comment.
( There are some hidden bugs for you,to handle it you should have an understanding of scope first, just for your learning. )
import java.io.*;
import java.util.*;
// declaration of the class
public class Bowling2 {
// declare arrays below
String Team, Member;
int Score, Scorew, Scoreb;
int[][] teamw = new int[10][3];
int[][] teamb = new int[10][3];
// declaration of main program
public static void main(String[] args) throws FileNotFoundException {
// 1. connect to input file
Scanner fin = new Scanner(new FileReader("bowling.txt"));
// 2) initialize array accumulators to zero
int i, j, Scoreb, Scorew = 0 ;
// 3) display a descriptive message
System.out.println(
"This program reads the lines from the file bowling.txt to determine\n"
+ "the winner of a bowling match. The winning team, members and scores\n"
+ "are displayed on the monitor.\n");
// 4) test Scanner.eof() condition
while (fin.hasNext()) {
// 5) attempt to input next line from file
Member = fin.next();
Team = fin.next();
Score = fin.nextInt();
// 6) test team color is blue
if (Team.toString() == "blue" ){
// 7) then store blue member and score
teamb[i][0] = Member;
teamb[i][1] = Team;
teamb[i][2] = Score;
// 8) increase blue array accumulator
sumArray("blue");
i++;
}
// 9) else store white member and score
else {
teamw[j][0] = Member;
teamw[j][1] = Team;
teamw[j][2] = Score;
// 10) increase white array accumulator
sumArray("white");
j++;
}
}
// 11) if blue team score is larger
// 12) then display blue team as winner
// 13) else display white team as winner
// 14 disconnect from the input file
fin.close();
}
// implement method `sumArray()` below
/* 1. initialize accumulator to 0
2. loop over initialized array indices
3. increase accumulator by indexed array element
4. return accumulator
*/
public double sumArray(string color) {
if (color == "blue") {
for (int k = 0;k < teamb.length(); k++) {
//do the calculation here, and return it
}
}else {
for (int h = 0;h < teamw.length(); h++) {
//do the calculation here, and return it
}
}
}
// implement method `printArray()` below
/* 1. display the team name as the winner
2. loop over initialized array indices
3. display member and score for that array index
*/
}

Sorting an array of students by last name alphabetically in Java

I currently have this program read the contents of a text file and calculate the averages and amount of test scores taken and print them out neatly in a small data table. These are the names, amount of quizes taken and average of each student:
James Tiberius Kirk 8 91.63
Buffy Summers 7 83.14
Tom Baker 15 100.00
Malcolm Reynolds 9 84.22
Elizabeth Bennet 9 93.33
John Blutarsky 9 0.00
Dorthy Gale 6 85.83
All of these Students are stored within the Array named Anames[]. I was wondering if it was at all possible to sort these students alphabetically by last name using the code that I have now. When I run the program it gives me the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1927)
at text.reader.TextReader.compareLastNames(TextReader.java:117)
at text.reader.TextReader.main(TextReader.java:94)
Here is the code of my main class:
public static void main(String[] args)throws IOException{
Double score=0.0;
int b,j;
String tempfirst = "";
String templast = "";
Student Anames[] = new Student[30];
Student Temp[] = new Student [1];
int Stucount = 0;
Scanner reader = new Scanner(new File("quizScores.txt"));
boolean runProgram = true;
PrintWriter writer = new PrintWriter(new File("scoreReport.txt"));
//prints header for report
System.out.println("Name Number Quizes Quiz Socres");
writer.println("Name Number Quizes Quiz Socres");
//check to see if end of file string
while (!reader.hasNext("-10")){
String name="", first="", last="";
//gets the name from file
while(!reader.hasNextDouble()){
last = reader.next();
while (!reader.hasNextDouble()){
first = first+reader.next()+" ";
}
name=first+last;
}
//creates new student with given name
Student newStudent = new Student(first, last);
Anames[Stucount] = newStudent;
Stucount++;
//gets the quiz scores and makes sure does not averge in the end of file string.
while (reader.hasNextDouble()&& !reader.hasNext("-10")){
newStudent.addQuiz(reader.nextDouble());
}
//Prints out the formated data
System.out.printf("%-30s%4.0f%30.2f \n",newStudent.getName(), newStudent.getQuizNumber(), newStudent.getAverage());
writer.printf("%-30s%4.0f%30.2f",newStudent.getName(), newStudent.getQuizNumber(), newStudent.getAverage());
writer.println();
}
System.out.println("\n");
for (b = 0; b < Stucount; b++){
int INTEGERTEMP = b;
for (j= b+1; j < Stucount; j++){
int INTEGERTEMP2 = j;
if ((compareLastNames(Anames[INTEGERTEMP].getLAST(), Anames[INTEGERTEMP2].getLAST()))>0){
Temp[0] = Anames[b];
Anames[b] = Anames[j];
Anames[j] = Temp[0];
}
}
}
System.out.println("Name Number Quizes Quiz Socres");
for (int i = 0; i < Stucount; i++) {
System.out.printf("%-30s%4.0f%30.2f \n", Anames[i].getName(), Anames[i].getQuizNumber(), Anames[i].getAverage());
}
writer.close();
}
private static int compareLastNames(String a, String b){
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
Here is the Student.java which contains most of the methods used:
public Student (String inName, String inLast){
studentName=inName;
studentLast = inLast;
quizAverage = 0;
quizScore=0;
numberQuizes=0;
}
public void addQuiz(double inQuiz){
quizScore += inQuiz;
numberQuizes++;
}
public double getAverage(){
quizAverage = quizScore/numberQuizes;
return quizAverage;
}
public String getName(){
return studentName+studentLast;
}
public double getQuizNumber(){
return numberQuizes;
}
public String getLAST(){
return studentLast;
}
You can use java.util.Arrays.sort(Student [] arr, Comparator<Student> comp) instead of your own compare code. In single line you can achieve it like this:
Student arr[];//considering this array you will populate
Arrays.sort(arr,new java.util.Comparator<Student>(){
public int compare(Student o1, Student o2) {
return o1.studentLast.compareTo(o2.studentLast);
}
});
//then the arr will be sorted with studentLast name
Let's work our way back from your exception to figure out where the problem is. First, it tells us we've got a StringIndexOutOfBoundsException on line 117; that is, the line (it might actually be the surname_b line, you've removed code from the class that means I can't match up the lines properly)
String surname_a = a.substring(index_a);
You'll notice the message from the exception helpfully tells us that the index used was -1. Let's take a look at why a.lastIndexOf(" "); would return -1. We see in the documentation for String that it returns -1 when the character does not occur in the String.
Now, let's work another step back in the Exception's stack trace to figure out why there's no space in that String. The Exception tells us to check line 94, where we see
if ((compareLastNames(Anames[INTEGERTEMP].getLAST(), Anames[INTEGERTEMP2].getLAST()))>0){
So, what's going on here? We're passing in the last names (and just the last names) from each of the students into our comparison function. The last names, for the most part, have no spaces in them.
So, how do we fix this? Well, you'll have to change your function to only take substrings of the surname if there actually is a space in them, i.e. if the index returned isn't -1.
Once you've got the comparison function done, I recommend looking at how to write an Object that implements the Comparable interface. This will allow you to use library sorting functions, which will be faster and less buggy than your own sorting functions (most likely!).

Reading every other line from a txt file and saving into an array

assignment:
A school that your little cousin attends is selling cookies. If your cousin's class sells more cookies than any other class, the teacher has promised to take the whole class on a picnic. Of course, your cousin volunteered you to keep track of all the sales and determine the winner.
Each class is identified by the teacher's name. Each sales slip has the teacher's name and the number of boxes sold. You decide to create two parallel arrays: one to hold the teacher's names and one to record the number of boxes sold. Here is a sample of the data:
The first number gives the number of classes, and then a teacher's Name is followed by the number of boxes sold
15
Smith
3
Courtney
... so on so forth
My main issue (because i can just duplicate it for the "to-be" parrallel array)
is getting every other line to save into an array for the boxes sold
so array "boxSold"
would look like
[1] 15
[2] 3
package assignment5Package;
import java.util.Scanner;
import java.io.*;
public class assignment5Demo
{
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//create arrays, variables
Scanner keyboard = new Scanner(System.in);
BufferedReader input = new BufferedReader
(new FileReader ("/Users/lee/Desktop/class/cs 113/Assignment5/cookies.txt"));
System.out.println("How many sale slips are there");
int numSaleSlips = keyboard.nextInt();
int[] soldBox = new int[numSaleSlips];
//______String[] teacherName = new String[numSaleSlips];
int soldBoxIndex;
int teacherNameIndex;
//String soldBoxString; (line 50)
//initializing both strings to 0 and "_"
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
soldBox[soldBoxIndex] = 0;
}
//**for (teacherNameIndex = 0; teacherNameIndex < numSaleSlips; teacherNameIndex++)
//**{
//** teacherName[teacherNameIndex] = "_";
//**}
//reading from the cookies.txt file
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
if (soldBoxIndex % 2 != 0
{
String soldBoxString;
soldBoxString = input.readLine(); //reads in value and assigns/re-assigns
soldBox[numSaleSlips] = (int) Double.parseDouble(soldBoxString); //type-casted to fit variable type, converts to double, stores in array
System.out.println(soldBox[soldBoxIndex]);
}
else
{
System.out.println("Error at " + soldBoxIndex +".");
}
}
}
The following may be a quick-and-dirty solution, but will get the job done:
for (soldBoxIndex = 0; soldBoxIndex < numSaleSlips; soldBoxIndex++)
{
if (soldBoxIndex % 2 != 0
{
String soldBoxString;
soldBoxString = input.readLine(); //reads in value and assigns/re-assigns
soldBox[numSaleSlips] = (int) Double.parseDouble(soldBoxString); //type-casted to fit variable type, converts to double, stores in array
System.out.println(soldBox[soldBoxIndex]);
}
else
{
input.readLine(); //read the following line, but ignore its content, effectivly skipping the line
}
}
You might also need to work the numbers of the for-loop a bit, to accomodate the skipped line.

How to generate a random String in Java [duplicate]

This question already has answers here:
How to generate a random alpha-numeric string
(46 answers)
Closed 6 years ago.
I have an object called Student, and it has studentName, studentId, studentAddress, etc. For the studentId, I have to generate random string consist of seven numeric charaters,
eg.
studentId = getRandomId();
studentId = "1234567" <-- from the random generator.
And I have to make sure that there is no duplicate id.
Generating a random string of characters is easy - just use java.util.Random and a string containing all the characters you want to be available, e.g.
public static String generateString(Random rng, String characters, int length)
{
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(rng.nextInt(characters.length()));
}
return new String(text);
}
Now, for uniqueness you'll need to store the generated strings somewhere. How you do that will really depend on the rest of your application.
This is very nice:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7).
There are 10^7 equiprobable (if java.util.Random is not broken) distinct values so uniqueness may be a concern.
You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.
java.util.UUID.randomUUID().toString()
http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html
Random ran = new Random();
int top = 3;
char data = ' ';
String dat = "";
for (int i=0; i<=top; i++) {
data = (char)(ran.nextInt(25)+97);
dat = data + dat;
}
System.out.println(dat);
I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.
public class RandomNumberGenerator {
private static final Set<String> generatedNumbers = new HashSet<String>();
public RandomNumberGenerator() {
}
public static void main(String[] args) {
final int maxLength = 7;
final int maxTry = 10;
for (int i = 0; i < 10; i++) {
System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
}
}
public static String getRandomId(final int maxLength, final int maxTry) {
final Random random = new Random(System.nanoTime());
final int max = (int) Math.pow(10, maxLength);
final int maxMin = (int) Math.pow(10, maxLength-1);
int i = 0;
boolean unique = false;
int randomId = -1;
while (i < maxTry) {
randomId = random.nextInt(max - maxMin - 1) + maxMin;
synchronized (generatedNumbers) {
if (generatedNumbers.contains(randomId) == false) {
unique = true;
break;
}
}
i++;
}
if (unique == false) {
throw new RuntimeException("Cannot generate unique id!");
}
synchronized (generatedNumbers) {
generatedNumbers.add(String.valueOf(randomId));
}
return String.valueOf(randomId);
}
}
The first question you need to ask is whether you really need the ID to be random. Sometime, sequential IDs are good enough.
Now, if you do need it to be random, we first note a generated sequence of numbers that contain no duplicates can not be called random. :p Now that we get that out of the way, the fastest way to do this is to have a Hashtable or HashMap containing all the IDs already generated. Whenever a new ID is generated, check it against the hashtable, re-generate if the ID already occurs. This will generally work well if the number of students is much less than the range of the IDs. If not, you're in deeper trouble as the probability of needing to regenerate an ID increases, P(generate new ID) = number_of_id_already_generated / number_of_all_possible_ids. In this case, check back the first paragraph (do you need the ID to be random?).
Hope this helps.
Many possibilities...
You know how to generate randomly an integer right?
You can thus generate a char from it... (ex 65 -> A)
It depends what you need, the level of randomness, the security involved... but for a school project i guess getting UUID substring would fit :)

Categories

Resources