USACO Server Input Discrepancy - java

I'm retrying the USACO Silver Problem Robot Instructions.
On my computer (Macbook Air M1 2020, MacOS Big Sur version 11.3.1), when I manually input the sample case my program outputs the correct answer. However, on the USACO grading server, it displays:
The following appeared on standard error:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at RobotInstructions.main(RobotInstructions.java:33)
For reference, my current code is:
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.Math;
public class RobotInstructions {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nInstructions = in.nextInt();
int wontx = in.nextInt();
int wonty = in.nextInt();
ArrayList<int[]> a;
ArrayList<int[]> b;
int n1;
int n2;
if (nInstructions%2==0) {
n1 = (int) nInstructions/2;
n2 = (int) nInstructions/2;
} else {
n1 = ((int) (nInstructions-1)/2);
n2 = ((int) (nInstructions+1)/2);
}
/////////////////////////////////
Scanner in1 = new Scanner(System.in);
int[][] instructionList = new int[n1][2];
for (int i = 0; i<n1; i++) {
int a1 = in1.nextInt();
int b1 = in1.nextInt();
instructionList[i][0] = a1;
instructionList[i][1] = b1;
}
a = subset(n1, instructionList);
/////////////////////////////////
/////////////////////////////////
int[][] instructionList1 = new int[n2][2];
for (int i = 0; i<n2; i++) {
int a1 = in1.nextInt();
int b1 = in1.nextInt();
instructionList1[i][0] = a1;
instructionList1[i][1] = b1;
}
b = subset(n2, instructionList1);
/////////////////////////////////
int[] answers = new int[nInstructions];
for (int[] i : a) {
for (int[] j : b) {
if (i[0]+j[0]==wontx && i[1]+j[1]==wonty) {
answers[i[2]+j[2]-1]++;
}
}
}
for (int i : answers) {
System.out.println(i);
}
}
public static ArrayList<int[]> subset(int n, int[][] instructionList) {
ArrayList<int[]> sums = new ArrayList<int[]>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i< (Math.pow(2,n)) ; i++) {
sb.setLength(0);
String a = Integer.toBinaryString(i);
for (int j = 0; j<(n-a.length()); j++) {
sb.append("0");
}
sb.append(a);
String c = sb.toString();
int x = 0;
int y = 0;
int amt = 0;
for (int k = 0; k<n; k++) {
if (c.charAt(k) == '1') {
x += instructionList[k][0];
y += instructionList[k][1];
amt++;
}
}
int[] m = new int[] {x,y,amt};
sums.add(m);
}
return sums;
}
}
I would not like any feedback on the efficiency of my program, just the reason why the grading server doesn't like my input format.

Related

I am facing timeout for my solution for a HackerRank

I am solving a problem on hackerrank
Hacker Rank ICPC Team Problem
I have created the following code as solution for problem.
import java.math.BigInteger;
import java.util.Scanner;
public class ACMICPCTeam {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),m=sc.nextInt(),count=0,maxCount=0,teams=0;
sc.nextLine();
String subjectArray[]=new String[n];
for(int i=0;i<n;i++){
subjectArray[i]=sc.nextLine();
}
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
String temp=""+(new BigInteger(subjectArray[i]).add(new BigInteger(subjectArray[j])));
//System.out.println(temp);
count=temp.replace("0","").length();
if(count>maxCount)
{
maxCount=count;
teams=1;
}
else if(count==maxCount)
{
teams++;
}
}
}
System.out.println(maxCount);
System.out.println(teams);
sc.close();
}
}
So what I am trying to do is I am adding the two teams subjects and I am counting non-zeros of resultant string. The highest count is number of subjects and the occurrence of highest counts are teams which know max number of subject. Even after spending a lot time I am not able to any better solution than this one still I am facing time out as it is not efficient.
I have gone through forum of the question but it was of no help.
Don't use string logic for this.
Parse the string into a BitSet, before entering your loops, i.e. as you read them.
Then use methods or(BitSet set), and cardinality().
I just completed challenge doing that. No timeouts.
Your solution is not optimal you should try something better.
You can utilize BigInteger method or BitSet class to make it easy.
For forming a team you have to use bitwise OR
Here are solutions--
// 1st approach
static int[] acmTeam(String[] topic) {
int n = topic.length;
BigInteger[] bi = new BigInteger[n];
for (int i = 0; i < n; i++)
bi[i] = new BigInteger(topic[i], 2);
int maxTopic = 0;
int teamCount = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
BigInteger iuj = bi[i].or(bi[j]);
int bitCount = iuj.bitCount();
if (bitCount > maxTopic) {
maxTopic = bitCount;
teamCount = 1;
} else if (bitCount == maxTopic) {
teamCount++;
}
}
}
int result[] = { maxTopic, teamCount };
return result;
}
// 2nd approach--using java BitSet class
static int[] acmTeamUsingBitSet(String[] topic) {
int teamCount = 0, maxTopic = 0;
int size = topic.length;
BitSet[] bitset = new BitSet[size];
for (int i = 0; i < size; i++) {
BigInteger b1 = new BigInteger(topic[i], 2);
bitset[i] = BitSet.valueOf(b1.toByteArray());
}
for (int i = 0; i < size - 1; i++) {
BitSet bitset1 = bitset[i];
for (int j = i + 1; j < size; j++) {
BitSet bitset2 = bitset[j];
BitSet tmpset = new BitSet();
tmpset.or(bitset1);
tmpset.or(bitset2);
if (tmpset.cardinality() > maxTopic) {
maxTopic = tmpset.cardinality();
teamCount = 1;
} else if (maxTopic == tmpset.cardinality()) {
teamCount++;
}
}
}
int result[] = { maxTopic, teamCount };
return result;
}
You can refer this link for a detailed video explanation.
I got good result using Java 8.
static int[] acmTeam(String[] topic) {
List<List<Integer>> res = IntStream.range(0, topic.length)
.mapToObj(s -> IntStream.range(0, topic[s].length()).boxed()
.collect(Collectors.groupingBy(i -> topic[s].charAt(i))))
.map(m -> m.get('1'))
.collect(toList());
long maxTopic = 0;
int teamCount = 0;
for (int i = 0; i < res.size(); i++) {
for (int j = i + 1; j < res.size(); j++) {
long topics = Stream.concat(res.get(i).stream(), res.get(j).stream()).distinct().count();
if (topics > maxTopic) {
maxTopic = topics;
teamCount = 1;
} else if (topics == maxTopic) {
teamCount++;
}
}
}
return new int[]{(int) maxTopic, teamCount};
}

Computing Jaccard Similarity in Java

I have following the code that loop through array list(mainItems) and find the most similar two arrays and put them in sortedTransactions. It is working fine for small data (10000 transactions) but it is running forever for 88000 transactions. What can be done to make it work for big data.
import java.util.*;
public class Sort {
static private List<Transactions> trans = ReadFile.transactions;
static public List<int[]> mainItems;
static public ArrayList<int[]> sortedTransactions = new ArrayList<int[]>();
static {
mainItems = new ArrayList<int[]>();
for (Transactions t : trans) {
mainItems.add(t.getItems());
}
}
static private double jaccardSimilarity(int[] a, int[] b) {
Set<Integer> s1 = new LinkedHashSet<Integer>();
for(int i =0; i< a.length; i++){
s1.add(a[i]);
}
Set<Integer> s2 = new LinkedHashSet<Integer>();
for(int i =0; i< b.length; i++){
s2.add(b[i]);
}
Set<Integer> intersection = new LinkedHashSet<>(s1);
intersection.retainAll(s2);
Set<Integer> union = new LinkedHashSet<Integer>(s1);
union.addAll(s2);
double jaccardSimilarity = (double)intersection.size()/ (double)union.size();
//System.out.println(intersection);
return jaccardSimilarity;
}
static private boolean isAllEqual(List<Double> a){
for(int i=1; i<a.size(); i++){
if(a.get(0) != a.get(i)){
return false;
}
}
return true;
}
static public void generatePairs() {
for (int i = 0; i < mainItems.size() - 1; i++) {
if (!sortedTransactions.contains(mainItems.get(i))) {
List<Double> myd = new ArrayList<Double>();
List<int[]> mys = new ArrayList<int[]>();
for (int j = i + 1; j < mainItems.size(); j++) {
if (!sortedTransactions.contains(mainItems.get(j))) {
myd.add(jaccardSimilarity(mainItems.get(i),mainItems.get(j)));
mys.add(mainItems.get(j));
}
}
if (isAllEqual(myd) == false) {
sortedTransactions.add(mainItems.get(i));
sortedTransactions.add(mys.get(maxValue(myd)));
}
}
}
}
static private int maxValue(List<Double> d) {
double max = d.get(0);
int f = 0;
for(int i =1; i< d.size(); i++){
if(d.get(i) > max){
max= d.get(i);
f= i;
}
}
return f;
}
}
You don't have to create the union set (union(s1, s2).size() is s1.size() + s2.size() - intersection(s1, s2).size()).
static private double jaccardSimilarity(int[] a, int[] b) {
Set<Integer> s1 = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
s1.add(a[i]);
}
Set<Integer> s2 = new HashSet<Integer>();
for (int i = 0; i < b.length; i++) {
s2.add(b[i]);
}
final int sa = s1.size();
final int sb = s2.size();
s1.retainAll(s2);
final int intersection = s1.size();
return 1d / (sa + sb - intersection) * intersection;
}

NoSuchElement Exception while implementing Scanner Class

The main point to keep in mind that the time and space complexity should be minimal. So to achieve this, I combined two for loops in one, and then error java.util.NoSuchElementException occurred.
Error is on the following line : a = in.nextInt();
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int M = in.nextInt();
long m[] = new long[N];
long big=0;
int a = in.nextInt();
int b = in.nextInt();
int k = in.nextInt();
int i;
int j;
for( i=0,j=a-1 ; i<M && j<=N ; j++)
{
m[j] = m[j] + k;
big = Math.max(big, m[j]);
if(j==b-1)
{
a = in.nextInt();
b = in.nextInt();
k = in.nextInt();
j = a-1;
i=i+1;
}
}
System.out.print(big);
}
}
The middle code that prior worked was as follows:
for(int i=0;i<M;i++)
{
int a = in.nextInt();
int b = in.nextInt();
int k = in.nextInt();
for(int j=a-1;j<=b-1;j++)
{
m[j] = m[j] + k;
if(m[j]>big)
{
big = m[j];
}
}
}
What is the guarantee that m[a-1] exists, a is dynamic input and you are not checking whether it is >=0 and
It seems to me that the root cause is in the loop test:
for( i=0,j=a-1 ; i<M && j<=N ; j++)
Indeed the array is declared as:
long m[] = new long[N];
so the test should be:
for( i=0,j=a-1 ; i<M && j<N ; j++)

closest pair of points, recursion not stopping at the correct area

Working on a closest point algorithm here. I am taking a 2d array of ints in. For some reason I am not getting the right answer. What is wrong with my recursion in conquer? I think that is the problem.
package ClosestPair;
import java.awt.Point;
import java.util.Arrays;
public class ClosestPair{
public double divide(int[][] data){
int size = data.length;
int[][] X_L = new int[size/2][2];
int[][] X_R = new int[size/2][2];
int[][] Y_L = new int[size/2][2];
int[][] Y_R = new int[size/2][2];
int[][] P_L = new int[size][2];
int[][] P_R = new int[size][2];
////////// X Portion ////////////////////////////
//sort the points
int[][] temp = data;
Arrays.sort(temp, new ColumnComparator(0));
//split the points
for (int i = 0; i < temp.length/2; i++){
X_L[i][0] = temp[i][0];
X_L[i][1] = temp[i+1][1];
X_R[i][0] = temp[i+temp.length/2][0];
X_R[i][1] = temp[i+temp.length/2][1];
}
////////// Y Portion ////////////////////////////
Arrays.sort(temp, new ColumnComparator(1));
//split the points
for (int i = 0; i < temp.length/2; i++){
Y_L[i][0] = temp[i][0];
Y_L[i][1] = temp[i+1][1];
Y_R[i][0] = temp[i+temp.length/2][0];
Y_R[i][1] = temp[i+temp.length/2][1];
}
//P_L
P_L= appendArrays(X_L, Y_L);
//P_R
P_R= appendArrays(X_R, Y_R);
if(conquer(P_L)< conquer(P_R)) return conquer(P_L);
return conquer(P_R);
}
public double conquer(int[][] array){
if(array.length == 2){
return distance(array);
}
int[][] temp1 = new int[array.length/2][2];
int[][] temp2 = new int[array.length/2][2];
int length = array.length/4;
for (int i = 0; i < length; i++){
temp1[i][0] = array[i][0];
temp1[i][1] = array[i+1][1];
temp2[i][0] = array[i+array.length/2][0];
temp2[i][1] = array[i+array.length/2][1];
}
return conquer(temp1);
}
private static int[][] appendArrays(int[][] array1, int[][] array2) {
int[][] ret = new int[array1.length + array2.length][];
int i = 0;
for (;i<array1.length;i++) {
ret[i] = array1[i];
}
for (int j = 0;j<array2.length;j++) {
ret[i++] = array2[j];
}
return ret;
}
public double distance(int[][] points){
//pair distance
int a = (points[0][0]+points[1][0]);
int b = (points[1][1]+points[1][1]);
return Math.sqrt( Math.pow(a, 2) + Math.pow(b, 2) );
}
}
You have wrong formula for calculation distance. It should be
int a = (points[0][0]-points[1][0]);
int b = (points[1][1]-points[1][1]);
return Math.sqrt( Math.pow(a, 2) + Math.pow(b, 2) );
Or you could use special function:
int x = (points[0][0]-points[1][0]);
int y = (points[1][1]-points[1][1]);
return Math.hypot(x,y);

Code compiles and executes, but does not print anything

The time-limit-extended is the status when executing the successfully compiled class file of the following code.
import java.io.*;
public class CandidateCode {
public static int ThirstyCrowProblem(int[] input1, int input2, int input3) {
int[] arrK = new int[input3];
int minstones = 0;
for (int i = 0; i < input3; i++) //create an array of k Os.
{
int smallest = input1[0], place = 0;
for (int j = 0; j < input2; j++) {
if ((smallest >= input1[j]) && (input1[j] >= 0)) {
smallest = input1[j];
place = j;
}
}
input1[place] = -1;
arrK[i] = smallest;
}
int n = input2, i = 0;
while (i < input3)
minstones = minstones + arrK[i] * (n - i);
return minstones;
}
public static void main(String[] args) {
int[] arr = new int[] {
5, 58
};
int stones_min = CandidateCode.ThirstyCrowProblem(arr, 2, 1);
System.out.println("The result is" + stones_min);
}
}
The cursor is waiting and waiting, but I don't think there is an error in the code!??
Option A :
Change your while into an if statement :
if(i<input3) {
minstones= minstones + arrK[i]*(n-i);
}
Option B : or increment i (i++) but I don't this that's what you want
while(i<input3) {
minstones = minstones + arrK[i]*(n-i);
i++;
}
You need to increment i in your while loop.Since you are not incrementing,its going in infinite loop.
while(i<input3)
{
minstones= minstones + arrK[i]*(n-i);
i++;
}
After making this change,I got
The result is10

Categories

Resources