Incorrect output on USACO 2022 Dec bronze problem 1 - java

I wrote this code and it worked on half of the test cases but failed on the other ones, and I cannot understand why since when I compared it to the solution given it was pretty similar.
import java.io.*;
import java.util.*;
public class cowcollege {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] cows = new int[n];
for (int i = 0; i < n; i++){
cows[i] = sc.nextInt();
}
Arrays.sort(cows);
long biggest = 0;
long smallest = 0;
for (int i = n - 1; i >= 0; i--){
int tut = cows[i];
if ((cows.length - i) * tut > biggest){
biggest = (cows.length - i) * tut;
smallest = tut;
}
if ((cows.length - i) * tut == biggest && tut < smallest){
smallest = tut;
}
}
System.out.print(biggest);
System.out.print(" ");
System.out.print(smallest);
}
}
Heres my code, works on test cases 1-5 and 7, but fails on the others

Related

Loop not properly modifying array elements

The loop causing issues is the second for loop.
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_POINTS = 4;
int[] dataPoints = new int[NUM_POINTS];
int controlValue;
int i;
controlValue = scnr.nextInt();
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
}
for (i = 0; dataPoints[i] < controlValue; ++i) {
dataPoints[i] = dataPoints[i] * 2;
}
for (i = 0; i < dataPoints.length; ++i) {
System.out.print(dataPoints[i] + " ");
}
System.out.println();
}
}
Currently when i run the test, this is what pops up.
Testing with inputs: 10 2 12 9 20
Output differs.
Your output
4 12 9 20
Expected output
4 12 18 20
the first number in the list of inputs is the maximum number it should multiply by 2. Since 20 is > 10, it is not multiplied. However 9 should be multiplying to 18, but it is not. If anyone could give some insight into anything i might be doing wrong when forming this loop, I would greatly appreciate it. Thank you!
Your second for loop is exiting because of the condition and the order of your input data, and will stop when a control value is reached. For example, if you instead had an input of 10 1 2 3 4, you would get the results you expect (ie. 2 4 6 8), but your for loop is exiting when the condition dataPoints[i] < controlValue is reached (in your case at 12).
Instead you should loop through the entire dataPoints array, as you do in your 3rd loop, and check the controlValue before doubling the values.
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_POINTS = 4;
int[] dataPoints = new int[NUM_POINTS];
int controlValue;
int i;
controlValue = scnr.nextInt();
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
}
for (i = 0; i < dataPoints.length; ++i) {
if (dataPoints[i] < controlValue) {
dataPoints[i] = dataPoints[i] * 2;
}
}
// This could be combined into the loop above...
for (i = 0; i < dataPoints.length; ++i) {
System.out.print(dataPoints[i] + " ");
}
System.out.println();
}
}
You could also do all of this in a single loop if you wanted to, for example:
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
if (dataPoints[i] < controlValue) {
dataPoints[i] = dataPoints[i] * 2;
}
System.out.print(dataPoints[i] + " ");
}

Maximum Integer Value java

I was trying to solve the Maximum Integer Value problem form Geeksforgeeks.
The problem states the following:
Given a string S of digits(0-9), your task is to find the maximum value that can be obtained from the string by putting either '*' or '+' operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input denoting the string.
Output:
For each testcase, print the maximum value obtained.
this is what I did:
class GFG
{
public static void sort(int[] numbers)
{
int n = numbers.length;
for (int i = 1; i < n; ++i)
{
int key = numbers[i];
int j = i - 1;
while (j >= 0 && numbers[j] > key)
{
numbers[j + 1] = numbers[j];
j = j -1 ;
}
numbers[j + 1] = key;
}
System.out.println(numbers.length - 1);
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
int [] maxNum;
for(int i = 0; i< testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
maxNum = new int [cNumbers.length];
for(int j = 0; j + 1 < cNumbers.length; j++)
{
int sum = 0;
int mult = 0;
sum = cNumbers[j] + cNumbers[j + 1];
mult = cNumbers[j] * cNumbers[j + 1];
int maxNumber = Math.max(sum, mult);
maxNum[i] = maxNumber;
}
sort(maxNum);
}
}
}
an example of Input:
2
01230
891
My Output:
-1
4
Correct Output:
9
73
What is wrong with my code?!
Just quick glance it would seem if your digit is less than two it should be added. 2 or larger should get multiplied. Not at a PC to test though.
The idea is to put the operators alternatively and choose the maximum results.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.parseInt(sc.nextLine());
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
int max = 0;
for (int j = 0; j + 1 < numbers.length(); j++) {
int next = Integer.parseInt(numbers.substring(j, j+1));
if (max + next > max * next)
max = max + next;
else
max = max * next;
}
System.out.println(max);
}
sc.close();
}
}
After the execution of
int testCases = sc.nextInt();
the buffer contains a new line character. So when executing the line
String numbers = sc.nextLine();
it read '\n' into numbers, so you got -1 as the first output.
Also you need to convert character to Integer before using it any arithmetic operations.
sum = cNumbers[j] + cNumbers[j+1];
mult = cNumbers[j] * cNumbers[j+1];
So the above code will give you wrong results.
I tried the following sample and worked.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputAsString = sc.nextLine();
int testCases = Integer.parseInt(inputAsString);
int maxNumber = 0;
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
if(!numbers.matches("\\d+")){
System.out.println("Only numeric values are expected.");
continue;
}
char[] cNumbers = numbers.toCharArray();
int sum = 0;
int mult = 1;
for (int j = 0; j < cNumbers.length; j++) {
int nextNumber = Character.getNumericValue(cNumbers[j]);
sum = sum + nextNumber;
mult = mult * nextNumber;
maxNumber = mult > sum ? mult : sum;
sum = maxNumber;
mult = maxNumber;
}
System.out.println(maxNumber);
}
sc.close();
}
I read your description and what you do is wrong. please read question carefully specially the example in reference site.
as mentioned in comments by moilejter you use sc.nextInt() which doesn't read '\n' and make problem. the next sc.nextLine() will read only a empty string and your program throw exception.
Second problem is that you must calculate max continuously and you don't need an int array (you calculate max result of operation between two successive number and save them in an array which is not correspond to max integer value. you only find max between each two digit but not max of operation on all digit).
Third problem is that you use character as numbers which is made incorrect result. (you must convert them to integer)
So there is a code that works for your output:
public class GFG
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.valueOf(sc.nextLine());
for (int i = 0; i < testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
long maxUntilNow = cNumbers[0] - '0';
for (int j = 1; j < cNumbers.length; j++)
{
int numberOfThisPlace = cNumbers[j] - '0';
maxUntilNow = Math.max(maxUntilNow + numberOfThisPlace,
maxUntilNow * numberOfThisPlace);
}
System.out.println(maxUntilNow);
}
}
}
I hope this is what you want.
As per the problem statement, we need to obtain maximum value from the string by putting either * or + operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
So, this can be solved in O(n) without using any sorting algorithm.
The simple logic behind the solution is whenever you find "0" or "1" in any of the operands use "+" and the rest of the places use "*".
Here is my solution which got successfully submitted:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int T = Integer.parseInt(scan.nextLine());
while(T-- > 0) {
String str = scan.nextLine();
maxValue(str);
}
}
static void maxValue(String str) {
long maxNumber = 0;
for(int i = 0; i < str.length(); i++) {
int n = Character.getNumericValue(str.charAt(i));
if (maxNumber == 0 || maxNumber == 1 ||
n == 0 || n == 1) {
maxNumber += n;
} else {
maxNumber *= n;
}
}
System.out.println(maxNumber);
}
}

What am I missing in order to swap numbers in this array? Java

So in my assignment, I'm halfway of solving this particular java array (this is an online book; percentage is at 50% in testing phase). However I cannot figure out what I'm missing. For this code, I have to make the input reverse two numbers (of whatever amount is requested). I tried looking online for similar situation but none answered what I needed.
Directions: Write a method swapArrayEnds() that swaps the first and last elements of its array parameter. Ex: sortArray = {10, 20, 30, 40} becomes {40, 20, 30, 10}. The array's size may differ from 4.
import java.util.Scanner;
public class ModifyArray {
// ANYTHING ABOVE THIS COMMENT CANNOT BE MODIFIED
public static void swapArrayEnds(int[] sortArray, int numElem) {
numElem = 4;
int i = 0; // Loop index
int tmpStore = 0; // Temp variable for swapping
for (i = 0; i < numElem; ++i) {
tmpStore = sortArray[i]; // Do swap
sortArray[i] = sortArray[numElem - 1];
sortArray[numElem - 1] = tmpStore;
}
return;
}
// ANYTHING BELOW THIS COMMENT CANNOT BE MODIFIED
public static void main (String [] args) {
int numElem = 4;
int[] sortArray = new int[numElem];
int i = 0;
sortArray[0] = 10;
sortArray[1] = 20;
sortArray[2] = 30;
sortArray[3] = 40;
swapArrayEnds(sortArray, numElem);
for (i = 0; i < numElem; ++i) {
System.out.print(sortArray[i]);
System.out.print(" ");
}
System.out.println("");
return;
}
}
At the moment, my error code is:
Testing with original sortArray = {10, 20, 30, 40}
Expected output: 40 20 30 10
Your output: 40 10 20 30
Tests aborted.
I'm not sure how my input became like that, but it merely placed the original last number in front of the original first. How do I have it that the first and last numbers are swapped?
Since only the ends need to be swapped, and this swap need to happen exactly once (not repeatedly), how about:
// Why do you need yo swap it in a cycle, thus many times???
/* Commenting faulty code out
for (i = 0; i < numElem; ++i) {
tmpStore = sortArray[i]; // Do swap
sortArray[i] = sortArray[numElem - 1];
sortArray[numElem - 1] = tmpStore;
}
*/
// A single time should do
tmpStore = sortArray[0]; // Do swap with the starting end
sortArray[0] = sortArray[numElem - 1];
sortArray[numElem - 1] = tmpStore;
(note: I think I'm getting tired of inane comments/answers sending a beginner on fool's errands)
public static void swapArrayEnds(int sortArray[],int numElem ) {
int t;
t = sortArray[numElem-1];
//assigning last element to temporary variable
sortArray[numElem-1]=sortArray[0];
//swapping last element with first element
sortArray[0]=t;
}
You may try this approach outlined below.
public static void swapArrayEnds(int[] newArray){
int num = newArray[0] ;
newArray[0] = newArray[newArray.length-1];
newArray[newArray.length-1] = num;
}
package net.code.java;
import java.util.Scanner;
public class ModifyArray {
public static void swapArrayEnds(int[] sortArray) {
int temp = 0;
temp = sortArray[0];
sortArray[0] = sortArray[sortArray.length-1];
sortArray[sortArray.length-1] = temp;
return;
}
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
int numElem = 4;
int[] sortArray = new int[numElem];
int i;
int userNum;
for (i = 0; i < sortArray.length; ++i) {
sortArray[i] = scnr.nextInt();
}
swapArrayEnds(sortArray);
for (i = 0; i < sortArray.length; ++i) {
System.out.print(sortArray[i]);
System.out.print(" ");
}
System.out.println("");
}
}
//a fix the the first answer provided
import java.util.Scanner;
public class ModifyArray {
// ANYTHING ABOVE THIS COMMENT CANNOT BE MODIFIED
for (int i = 0; i < numElem; i++) {
int temp = sortArray[i];
sortArray[i] = sortArray[numElem - 1];
sortArray[numElem - 1] = temp;
return;
}
}
// ANYTHING BELOW THIS COMMENT CANNOT BE MODIFIED
public static void main (String [] args) {
int numElem = 4;
int[] sortArray = new int[numElem];
int i = 0;
sortArray[0] = 10;
sortArray[1] = 20;
sortArray[2] = 30;
sortArray[3] = 40;
swapArrayEnds(sortArray, numElem);
for (i = 0; i < numElem; ++i) {
System.out.print(sortArray[i]);
System.out.print(" ");
}
System.out.println("");
return;
}
}
public static void swapArrayEnds(int sortArray [],int numElem) {
int temp = sortArray[0];
sortArray[0] = sortArray[numElem - 1];
sortArray[numElem - 1] = temp;
}
This is how I would do it:
import java.util.Scanner;
public class ModifyArray {
/* Your solution goes here */
public static void swapArrayEnds(int[] arr) {
int temp = arr[0];
arr[0] = arr[arr.length-1];
arr[arr.length-1] = temp;
}
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
int numElem = 4;
int[] sortArray = new int[numElem];
int i;
int userNum;
for (i = 0; i < sortArray.length; ++i) {
sortArray[i] = scnr.nextInt();
}
swapArrayEnds(sortArray);
for (i = 0; i < sortArray.length; ++i) {
System.out.print(sortArray[i]);
System.out.print(" ");
}
System.out.println("");
}
}

Project Euler #34: Digit factorials - review code : Java

A digital factorial need to be found out. This no. is easily divisible by sum of factorials of all the digits of the no.
I am trying this on HackerRank : https://www.hackerrank.com/contests/projecteuler/challenges/euler034/
My code is passing only one test case i.e. if n < 20.Other test cases are not passing.
Code is below.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int len,newt=0,pos = 0,ans=0;
long fac,sum;
for(int i=10;i<=n;i++){
newt = i;
sum =0;
len = String.valueOf(newt).length();
while(len>0){
fac=1;
pos = newt % 10;
newt = newt/10;
for(int k=1;k<=pos;k++){
fac = fac*k;
}
sum+=fac;
len--;
}
// System.out.print(sum+" "+i);
// System.out.println();
if(sum%i==0){
ans = i;
}
}
System.out.print(ans);
}
}
Your code for iterating the digits of a number n seems overly complex. It's a simple as this:
if (n <= 0)
throw new IllegalArgumentException("Not a positive number: " + n);
for (; n > 0; n /= 10) {
int digit = n % 10;
// use digit here
}
Your code can also be improved by using methods to separate the logic into independent parts, e.g.
private static int sumCuriousNumbers(int n) {
int sum = 0;
for (int i = 10; i <= n; i++)
if (isCuriousNumber(i))
sum += i;
return sum;
}
private static boolean isCuriousNumber(int number) {
int sum = 0;
for (int i = number; i > 0; i /= 10)
sum += factorial(i % 10);
return (sum % number == 0);
}
private static int factorial(int n) {
int f = 1;
for (int i = 1; i <= n; i++)
f *= i;
return f;
}
This helps document the code and the 3 methods can now be unit-tested too.

stuck in contraints in a easy exercise

I am trying to solve this exercise, It seems easy this, but I can not understand the contraints -rules, It says:
the number may be represented on one or two hands;
if the number is represented on two hands, the larger number is given first
The rule number 2 I can not understand for example if it says 3, I have 3, 2+1, 1+2 (this not because its repeated), if it says 6 we have 6, 5+1, 4+2, 3+3, 2+4 + 1+5 but the correct output is 3, can someone guide me in this problem?? for 7 is 2, and 8 is 2, 9 is 1, and 10 is 1.
this is my code:
import java.util.Scanner;
class j1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tot = 5;
int n = sc.nextInt();
int sum = 0;
int count = 1;
for (int i = 1; i <= tot; i++) {
for (int j = 1; j <= tot; j++) {
sum = i + j;
if (sum == n) {
System.out.println(i);
System.out.println(j);
count++;
}
}
}
System.out.println(count);
sc.close();
}
}
Its simple - if you are going to give the number using both the hands (2 hands) then you will first need to give the larger number which comprises the overall number -
eg for 7 (4+3 OR 5+2) when represented using 2 hands - give 4 first !
other option for 7 (3+4, 2+5) are invalid since it will make us to list the smaller number first which violates the rule #2
The number of the second hand must always be less than or equal to the number of the first hand. I believe the code below will work.
import java.util.Scanner;
class j1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tot = 5;
int n = sc.nextInt();
int sum = 0;
int count = 1;
for (int i = 1; i <= tot; i++) {
for (int j = 1; j <= i; j++) {
sum = i + j;
if (sum == n) {
System.out.println(i);
System.out.println(j);
count++;
}
}
}
System.out.println(count);
sc.close();
}
}

Categories