I've written code for a foobar challenge that works in my IDE but not in the solutions file provided by foobar. Also, is there anyway to show the output even if the test fails? Possibly to with it being a static method or the input being {1, 2, 3, 4} whereas mine is working with new int {1,2,3,4,5}? My code is:
public static int solution(int[] l) {
List<Integer> numberList = Arrays.stream(l).boxed().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
while (true) {
StringBuilder number = new StringBuilder();
int i = 0;
while (i < numberList.size()) {
number.append(numberList.get(i));
i++;
}
List<Integer> startingList = Arrays.stream(l).boxed().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
int testValue = numberList.size();
for (Integer integer : numberList) {
if (startingList.contains(integer)) {
startingList.remove(integer);
testValue--;
}
}
if (testValue == 0) {
int f = 0;
int total = 0;
while (f < numberList.size()) {
total = total + numberList.get(f);
f++;
}
if (total % 3 == 0) {
StringBuilder answer = new StringBuilder();
int c = 0;
while (c < numberList.size()) {
answer.append(numberList.get(c));
c++;
}
return Integer.parseInt(answer.toString());
}
}
Integer nextNumber = Integer.parseInt(number.toString()) - 1;
String[] stringArray = valueOf(nextNumber).split("");
numberList = new ArrayList<>();
for (String s : stringArray) {
numberList.add(Integer.parseInt(s));
}
}
}
Pretty rubbish but it does the job (at least in my IDE!)
As mentioned in a comment on the question, you should undoubtedly give some more context for your questions (since it is pretty unclear what your code is intended to do). I'm pretty sure I've inferred the actual question from context though, and I can suggest a couple of problems. In short (and a pretty good assumption for coding in general) the issue is not the environment running your code incorrectly, but rather your code having missed bugs due to lack of comprehensive testing. If you had presented a number of sample inputs and results I would guess you would have seen that your solution does not work locally.
The Java List.remove() method takes an index rather than a value to be removed (https://docs.oracle.com/javase/8/docs/api/java/util/List.html). The way it is used in your sample will result in throwing exceptions in a number of circumstances. Proper testing would have identified this (and will pick up most of your problems if fixed)
What happens if there is no solution? For example, an input of {1, 1} is going to get into a pretty messy state as the 'nextNumber' value slips below 0. You should know what the desired behavior is in this situation, and your tests should cover it before you try to upload a solution
This happened to me as well, but I then realized that my compilation was not successful because I have not imported the package that I am using at the top of the source code file like all java programs are write
Related
I tried to solve
https://leetcode.com/problems/maximum-subarray/submissions/
using Java
I usually try these things using Eclipse before submit on online.
Here I attached codes in Eclipse
public class PrintAnnotationExample{
public static void main(String[] args) {
int index = 0;
int max =0;
int temp = 0;
int[] test = new int[] {-2,1,-3,4,-1,2,1,-5,4};
while(index<test.length) {
temp+= test[index];
if(temp <0) {
while(index<test.length-1 && test[index]<0) {
++index;
}
temp = 0;
}
max = (max >= temp ) ? max : temp;
++index;
}
///
System.out.println(max);
}
}
It worked! the expected output is 6, and it makes 6 either.
However,
In Leetcode submission page, It doesn't work
class Solution {
public int index = 0;
public int max =0;
public int temp = 0;
public int maxSubArray(int[] nums) {
while(index<nums.length) {//아직 배열범위 안에 있을경우
temp+= nums[index];
if(temp <0) {
while(index<nums.length-1 && nums[index]<0) {
++index;
}
temp = 0;
}
max = (max >= temp ) ? max : temp;
++index;
}
return max;
}
}
It shows me 1, not 6...
weird, may be I got something wrong in my head about Java semantics..
The codes you are executing in Eclipse and Leetcode are clearly different, so you need to focus on the differences between them ... rather than concluding (incorrectly) that there are compiler / language differences.
One of the differences is that in the Eclipse version index, max and temp are local variables. In the Leetcode version they are instance variables that don't get initialized each time your method is called. If LeetCode instantiates your class once and calls the method multiple times, this will lead to incorrect behavior.
may be I got something wrong in my head about Java semantics.
Maybe. Or it could just be a mistake.
But either way, it is inadvisable to use instance variables to hold the state of a method call. Use local variables for instead:
Using local variables for this avoids the mistake you made; i.e. forgetting to reinitialize.
Using instance variables for this makes the method non-reentrant; i.e. concurrent or overlapping calls to the method will interfere with each other. This will be problematic if the method is called recursively, or if it is called from multiple threads.
I'm new to Java ans struggling with Arrays. I need help with an array code. There are 20 errors but I can't seem to find them (except 7). Also, I'm new to StackOverflow so sorry for the format.
Code is:
public clas ArrayProcessing
{
public void main (String [] args)
{
int iElement = 0,
int iSmallest = 0,
int iPossible = 0;
String strElements, strSmallest, strPossibles = "";
strElements = joptionPane.showInputDialog("How many elements would you like to be included in the array?");
iElements= Integer.parseInt(strElements);
strSmallest =joptionPane.showInputDialog("What would you like the smallest number in the array to be?");
iSmallest = Integer.parseInt(strSmallest);
strPossibles = joptionPane.showInputDialog("How many possible unique numbers would you like to have?");
iPossibleS= Integer.parseInt(strPossible);
int[] intArray = int[iElement];
displayArray(intArray[0]);
loadArray(intArray, iSmallest, iPossbles)
displayArray(intArray);
}
public static void loadArray(int intArray, int iSmallest, int iPossibles)
{
for (index =0; index < intArray.length(); index++)
{
intArray[index] = iSmallest + (int) (Math.random()* iPossibles);
}
}
public void displayArray(int[] intArray)
{
String strOutput="";
for (iCounter = 0, iCounter<intArray.length, iCounter++);
{
Output += intArray[iCounter] + "";
}
jOptionPane.showMessageDialog(null, "These are the values in your array: \n" + strOutput, "Arrays", JOptionPane.INFORMATION_MESSAGE);
}
You DEFINITELY need to learn the basics. Get an IDE to display the errors. Eclipse or someone suggested BlueJ (I haven't heard of it) but it will help you. Besides showing errors, it can format your code, too. You can click on the error and it will go to the error line.
use semicolons instead of commas.
If you have a "{" following a for loop, don't use semicolon.
To use swing components (i.e. JOptionPane) you need to have a JFrame to display them in.
Indenting is important for YOU and those reading the program. Makes it a lot easier to determine scope.
In a nutshell, you have the concept of programming, but you don't have the basics and you need that first. Start off with an example of, say, JOptionPane and expand on it to include your code.
Good luck. And hang in there. We've all been where you are, but we stuck with it.
There are two questions here actually. The first one:
1) Is Java smart enough not to copy one array element into itself?
What I mean by that is :
int i = 1;
char [] chars=... //some chars
char[1] = char[i]; // first element into itself
2) Are the benchmarking's that guava made available to the public?
And what I mean by that is: I was looking into the source code of CharMatcher removeFrom method and saw this :
// This unusual loop comes from extensive benchmarking
OUT: while (true) {
pos++;
while (true) {
if (pos == chars.length) {
break OUT;
}
if (isLetter(chars[pos])) {
break;
}
chars[pos - spread] = chars[pos];
pos++;
}
spread++;
}
return new String(chars, 0, pos - spread);
I really liked the idea, but coded my own method:
public static String removeMine(String input){
char [] chars = input.toCharArray();
int howManyLetters = 0;
for(int i=0;i<chars.length;++i){
if(isLetter(chars[i])) {
chars[howManyLetters++] = chars[i];
}
else {
if(i == (chars.length - 1)) break;
chars[i] = chars[i+1];
}
}
return new String(chars, 0, howManyLetters);
}
I then added some benchmarks (I will put them on github if needed), here are the results:
https://microbenchmarks.appspot.com/runs/61e76bdc-b0d6-4145-8b8b-c1683287f038#r:scenario.benchmarkSpec.parameters.input,scenario.benchmarkSpec.methodName
I have (serious?) doubts that creators of guava did not have a version like that and I assume there was a strong reason to drop it (the comment is more then obvious). What I would like to see is either the actual benchmarks that they made or some serious reason to have such a method. I assume it has to do with the type of JVM that you run your code into, but actual proof would be appreciated.
P.S. I am still to test this with jmh also, will provide results once I'm done.
I know how to calculate easy expression without variables. But how to do, when in line we have expression with "x"?
For example
(x+1)*(x-1)
In this example program should to return: x^2 - 1
It's a non-trivial endeavor. I would strongly suggest you look at what's out there. For example Symja
You might want to look at the scripting feature of java. It seems that you can execute Javascript (or other scripting languages) from Java using this scripting engine.
You will find some examples at https://today.java.net/pub/a/today/2006/04/11/scripting-for-java-platform.html.
What you are asking for, is letting a program transform (and possibly solve) mathematical equations. This is of course possible and there are tools and certainly APIs around which do it, but it's definitely beyond hacking a java program by your own.
In case you just like to calculate the result of a given formula, then this is doable. Interestingly, you can just throw an equation at Google (e.g. (5 + 3) * (8-4)) and it will give you the result. So, why not just use it? ;-)
When we go to the interview they asking the this logical type of question. i to met the same problem. but i couldn't able to success the interview because this type of questions. Later i found the result of my own after i search in in the internet. Friends who are all want to do this..
follow this operation. i will give this full of free.
I will enter the equation as string Like.
a*b*c+d/m-x.
get this equation as string object. and use following functions.#
public void calc() throws IOException
{
String equation,store,get;
StringBuilder sb= new StringBuilder();
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter the equation");
equation= dis.readLine();
equation="%"+equation+"%";
byte[] buf= equation.getBytes();
for(int i=0;i<equation.length();i++)
{
if(buf[i]>=97&&buf[i]<=122)
{
System.out.println("Enter the value for "+(char)buf[i]);
get=dis.readLine();
sb.append(get);
}
else
sb.append((char)buf[i]);
}
store= sb.toString();
char[] buf1= new char[25];
for(int i=0;i<store.length();i++)
{
buf1[i]=store.charAt(i);
}
for(int i=0;i<buf1.length;i++)
{
no.append(buf1[i]);
}
System.out.println(no.toString());
int m,n=0;
for(int i=0;i<no.length()-1;i++)
{
if('/'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) / findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length()-1;i++)
{
if('*'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) * findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length()-1;i++)
{
if('+'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) + findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length()-1;i++)
{
if('-'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) - findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length();i++)
{
if('%'==no.charAt(i))
{
no.deleteCharAt(i);
i=0;
}
}
System.out.println(no.toString());
}
public int findLeftValue(int i)
{
StringBuilder sb= new StringBuilder();
int x=0;
while(no.charAt(i)!='*'&&no.charAt(i)!='+'&&no.charAt(i)!='-'&&no.charAt(i)!='/' &&no.charAt(i)!='%')
{
leftCount++;
sb.insert(0, no.charAt(i));
i--;
}
x=Integer.parseInt(sb.toString());
return x;
}
public int findRightValue(int i)
{
StringBuilder sb= new StringBuilder();
int x;
while(no.charAt(i)!='*'&&no.charAt(i)!='+'&&no.charAt(i)!='-'&&no.charAt(i)!='/' &&no.charAt(i)!='%')
{
rightCount++;
sb.append(no.charAt(i));
i++;
}
x=Integer.parseInt(sb.toString());
return x;
}
here may be unused variable may be there.please find and remove it.
I didn't set any preferences to the calculation. just i made up with the flow. if you change the flow the answer will be different. so, Keep in mind. and you can do the same for different operators also.
And One more thing is that, Please verify the equation before proceeding the function. because, it will not check whether the equation is correct or wrong.(a+*d++c). it is not correct equation.
The equation should be correct format.. Like a+b*c-d/x.
Enjoy ..Break the interview and get your correct job..
I am a newbie Computer Science high school student and I have trouble with a small snippet of code. Basically, my code should perform a basic CLI search in an array of integers. However, what happens is I get what appears to be an infinite loop (BlueJ, the compiler I'm using, gets stuck and I have to reset the machine). I have set break points but I still don't quite get the problem...(I don't even understand most of the things that it tells me)
Here's the offending code (assume that "ArrayUtil" works, because it does):
import java.util.Scanner;
public class intSearch
{
public static void main(String[] args)
{
search();
}
public static void search()
{
int[] randomArray = ArrayUtil.randomIntArray(20, 100);
Scanner searchInput = new Scanner(System.in);
int searchInt = searchInput.nextInt();
if (findNumber(randomArray, searchInt) == -1)
{
System.out.println("Error");
}else System.out.println("Searched Number: " + findNumber(randomArray, searchInt));
}
private static int findNumber(int[] searchedArray, int searchTerm)
{
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
}
}
This has been bugging me for some time now...please help me identify the problem!
I don't know about the infinite loop but the following code is not going to work as you intended. The i++ can never be reached so i will always have the value 0.
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
You probably mean this:
for (int i = 0; i < searchedArray.length; i++)
{
if (searchedArray[i] == searchTerm)
{
return i;
}
}
return -1;
I don't know what is the class ArrayUtil (I can not import is using my Netbeans). When I try to change that line with the line int[] randomArray = {1 , 2, 3, 5, 7, 10, 1 , 5}; It works perfectly.
And you should change the loop condition. I will not tell you why but try with my array and you will see the bug soon. After you see it, you can fix it:)
There are 4 basic issues here.
1. Putting searchedArray[i] == searchTerm before i < searchedArray.length can result in an out-of-bounds exception. You must always prevent that kind of code.
2. Your intention seems to be the opposite of your code. Your method name implies finding a search term. But, your code implies that you want to continue your loop scan until the search term is not found, although your loop won't do that either. Think of "for (; this ;) { that } " as "while this do that".
3. Place a break point at the beginning of "search". Then, with a small array, step through the code line by line with the debugger and watch the variables. They don't lie. They will tell you exactly what's happening.
4. Please use a standard IDE and compiler, such as Eclipse and Sun's JDK 6 or 7. Eclipse with JDK 7 is a serious combination that doesn't exhibit a strange "infinite loop" as you describe above.