Win a copy of Fixing your Scrum this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Rob Spoor
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Holloway
  • Piet Souris
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Himai Minh

why this bubble sort only passed 1 test and failed the other ?

 
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi experts,

I am not getting any response at the hackerRank so I hope I can get some response here regarding this bubbleSort which failed 2 out of 3 tests.

The question is per attached.

And the solution here which I was taught(really thankful to such a patient person) :



I hope someone can point out to me why the above only passed 1 test.  Tks.
30-sorting_English1024_1.jpg
[Thumbnail for 30-sorting_English1024_1.jpg]
30-sorting_English1024_2.jpg
[Thumbnail for 30-sorting_English1024_2.jpg]
30-sorting_English1024_3.jpg
[Thumbnail for 30-sorting_English1024_3.jpg]
 
Master Rancher
Posts: 4454
38
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To make it easier for others to test your code, could you provide the sample input where the program fails?
A simple way to make the testing easier is to put the input in the StringReader's constructor.  For example:

Run the program with the provided input, copy the console and paste it here so we can see what happened.
Add some comments to the output showing where the results are incorrect.
 
Saloon Keeper
Posts: 24174
165
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:\
Run the program with the provided input, copy the console and paste it here so we can see what happened.



And by "copy" we're really prefer you did a text copy-and-paste not a screenshot.

Speaking of which, those hackerRank screenshots are probably copyright violations.

I'm not sure HackerRank is the best site for you to learn from, though. Their examples aren't very friendly.
 
Saloon Keeper
Posts: 4605
182
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You exit the while-loop when 'numberOfSwaps'== 0. And that is wht you print in your answer. So you need to maintain a second variable 'totalNrOfSwaps'.
 
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:

Norm Radder wrote:\
Run the program with the provided input, copy the console and paste it here so we can see what happened.



And by "copy" we're really prefer you did a text copy-and-paste not a screenshot.

Speaking of which, those hackerRank screenshots are probably copyright violations.

I'm not sure HackerRank is the best site for you to learn from, though. Their examples aren't very friendly.



HackerRank's highest value contribution, IMHO, is that they tend to have extremely complete test sets that they run your code against.

It is so easy on non-trivial problems to miss corner cases or to have a solution that is often "good enough" but breaks down in one way or another on unexpected but totally legal inputs.

The test cases they run your code against tends to help find all these things, and to get full credit your "good enough" solution evolves to be rock-solid and very efficient.

They are not always the best place to LEARN material from in the first place, however.  Sometimes they use weird terminology or have examples that are not the clearest.

I am still chuffed that they allow us to use Java 15 for solutions now, however, and they are a great place to test that you have learned to apply something new to you well enough to stand up to vigorous testing.

The following is probably boilerplate code that HackerRank supplies.  Note that in most cases (but not all) HackerRank allows you to edit boilerplate code as well, and sometimes you need to do so to pass every test case, as too much CPU gets wasted before they even call the code you've written!  I considered that cheating at first, but they support dozens of different language choices for their problems, with a standard allocation of memory and CPU based solely on which language is being used irrespective of the problem and data.  So it just is what it is.

Looking at that boilerplate code, I consider the extra boxing to be a bit of a waste, wouldn't it be better to say Integer aItem = Integer.valueOf(aTemp[i]); in line 5?

Also, in line 2, is there any advantage in Java 11 or later to using the more expensive .replaceAll("\\s+$") rather than .stripTrailing() on the output of .readLine() which by definition will only return a single line?
Note, until very recently, HackerRank was stuck at Java 8, so no surprise their boilerplate code is 100.00% Java 8 compatible.

 
 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:

Norm Radder wrote:\

I'm not sure HackerRank is the best site for you to learn from, though. Their examples aren't very friendly.



Hi Tim,

I am using HackerRank because I do not know what other site that can help me prepare coding interview which will take place in a few days' time.

So far, I have been failing here and there and I feel defeated.

I am so used to open book and google for API methods and modify from examples.

But, I think my career really sucks ...and now if I can't pass the test, I am so scared to return to being a cashier or reduce to rubbish, being asked to do data-entry job....

 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:To make it easier for others to test your code, could you provide the sample input where the program fails?
A simple way to make the testing easier is to put the input in the StringReader's constructor.  For example:

Run the program with the provided input, copy the console and paste it here so we can see what happened.
Add some comments to the output showing where the results are incorrect.



Hi Norm,

The sample input I believe is

 
Norm Radder
Master Rancher
Posts: 4454
38
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Did you create an instance of the StringReader class and use it as I suggested for testing?
What happened?  
Copy the contents of the console and paste it here.
Add some comments to the output showing what is wrong with it.
 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:Did you create an instance of the StringReader class and use it as I suggested for testing?
What happened?  
Copy the contents of the console and paste it here.
Add some comments to the output showing what is wrong with it.



I do not think this will work with HackerRank.  Just to confirm, you want me to create the StringReader in HackerRank console and submit or ?

Anyway, I did it on HackerRank and this time it is even worse.  Failed all the test cases.

And I am completely confused why you would want me to do it at Hackerrank site since you know at the back, they are using their own unit testing.

 
Norm Radder
Master Rancher
Posts: 4454
38
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My suggestion was for testing the code on your computer using an IDE or the command prompt.  Then the console from the test can be copied and pasted here to show the problem.

I do not think this will work with HackerRank.  


I do not know anything about how to use HackerRank.

why you would want me to do it at Hackerrank site

I don't want anything done at HackerRank.
I do not think you can execute the program for debugging when using HackerRank.  Debug the  code first on your PC then submit it to HackerRank.
My suggestion was a way for you to debug the code on your PC.
 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:My suggestion was for testing the code on your computer using an IDE or the command prompt.  Then the console from the test can be copied and pasted here to show the problem.


My suggestion was a way for you to debug the code on your PC.



I am sure this code is 100% correct because I was taught by this very super experienced guy in the discord where he spent nearly 3 hours walking me thru why I should use Do while loop instead of the nested loop which is really confusing to use.

He himself has tested it also.

Is there anything wrong that you have seen that is not right ?
 
Piet Souris
Saloon Keeper
Posts: 4605
182
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See my earlier reply
 
Norm Radder
Master Rancher
Posts: 4454
38
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I am sure this code is 100% correct


Ok, then why this:


this bubbleSort which failed 2 out of 3 tests.



What values is the test looking at?  What values does the program print out?

See Piet's post.
 
Piet Souris
Saloon Keeper
Posts: 4605
182
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To add to Norms reply: the bubblesort itself is oke, just what you report is wrong.
 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:

I am sure this code is 100% correct



What values is the test looking at?  What values does the program print out?

See Piet's post.



I tried what you suggested in my local ide what it won't work as I do not have the unit testing written in my local machine.

The console is blank...



And I am not exactly sure what Pied's suggestion of having another counter variable ?
after the while loop ? I have to count again ? why ?
 
Norm Radder
Master Rancher
Posts: 4454
38
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

 why ?


What output from your program is incorrect and causing it to fail?

The debugging is to find what is wrong so it can be fixed.

The posted code compiles and executes on my PC.
With my fixes to the code, this is the output:


before aL=[6, 4, 2, 1]
Array is sorted in 6 swaps.
First Element: 1
Last Element: 6
after aL=[1, 2, 4, 6]

 
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

tangara goh wrote:
And I am not exactly sure what Pied's suggestion of having another counter variable ?
after the while loop ? I have to count again ? why ?


This is the root of the problem and bug. You are not "counting again." You are accumulating the count of swaps.

The numberOfSwaps variable tracks how many swaps were made for one pass through the collection. If you didn't make any swap, you're done, that is, the collection is sorted.

The totalNumberOfSwaps variable will accumulate the values of numberOfSwaps throughout the entire sorting process. This is the value that the tests are expecting.

Your program will only be correct if it just happens to make 0 or 1 pass to sort the collection. It will be incorrect and thus fail any test if it has to make more than 1 pass to sort the collection.
 
Junilu Lacar
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Plus, it's right there in the problem statement, plain as day:

Hint: To complete this challenge, you will need to add a variable that keeps a running total of all swaps that occur during execution.


You haven't done that.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:My suggestion was for testing the code on your computer using an IDE or the command prompt.  Then the console from the test can be copied and pasted here to show the problem.

I do not think this will work with HackerRank.  


I do not know anything about how to use HackerRank.

why you would want me to do it at Hackerrank site

I don't want anything done at HackerRank.
I do not think you can execute the program for debugging when using HackerRank.  Debug the  code first on your PC then submit it to HackerRank.
My suggestion was a way for you to debug the code on your PC.



Hi Guys:

What Norm said was true, what Piet said was "the answer", but I will give an answer that will help not just for this problem, but for making the best use of HackerRank as a tool to gauge your level of mastery of different parts of Java and computer science.

First, let's calm down a bit.  HackerRank is terrific when you already understand something pretty well, and want to see if you fully, totally understand it, and can make a solution that matches all edge cases and fails for none, and in fact scales well for all possible inputs.  It can be scary or frustrating when working on a problem near the limits of your current knowledge, so let's attack that, and how to best proceed!  Everyone needs to know how to do this, because there are countless problems there, from very easy to ones that many people who could pass the hardest interviews or win coding challenges would be stuck on for days.

There are two distinct options to run your code on HackerRank, actually 3:
1. "Submit Code" -- this is to be used to run your solution, which you believe to be complete and correct, against the full suite of all test cases.  It is the only way to get scored for the problem.  You will not be able to see all of the test cases by default, and you may (will, on really hard problems!) see that some test cases you can't see are generating wrong answers or timing out.  If this happens, and you believed your code was finished and complete and good enough, you now realize it is NOT yet, and have a few options:
a. you can "eyeball" your code to look for any assumptions about the input that were not justified, and perhaps just were true by accident for the simpler test cases.  Every problem shows information about what you can assume about the problem, i.e. what the input will look like and the bounds of the possible test case data you will have.  On harder problems, the descriptions are still true but will be misleading, because the sample cases they show you and the simplest test cases you run against will work with simplifying assumptions not valid in general for the problem.  Correct code will work with these and all others, but code that is "close" might work fine for those yet be making assumptions that are not generally valid as the problem is described.  There may be special cases to be considered, or you may have a suboptimal algorithm that works fine for easy test cases but consumes excessive CPU time or memory and fails, whereas a better algorithm will work for all of them.

b. When this happens, and you can't figure out why you are failing, they give you the option to "buy" test cases.  This is not some evil in-game spending ploy that costs you dollars or rupees.  You can "buy test cases" for what they call "Hackos", which you earn by successfully solving (any) problems on HackerRank.  When you buy one or more test cases (I would suggest usually starting with buying just one, that is often enough!) now you know which test case is failing, and there are two ways you can use that test case.  First save it in a plain text file somewhere, because you don't want to have to buy it again.  You have access to it for some amount of time after buying it, but better to not take a chance on losing it.

This all applies when you had hoped/thought your solution was already good enough, and are surprised that it didn't receive full points, let's talk about GETTING to that point.

2. The other option you can use while getting there is "Run Code", rather than "Submit Code".  You use this during your original build up to thinking you've got a solid solution.  You can "Run Code" as many times as you need and the system doesn't count and record all your embarrassing failures.  It also doesn't get to see all of the hardest, most complex, most interesting test cases, however.

Now, extra debugging output will always cause the run of your code to fail, because HackerRank "reads" your output which is very clearly specified, and ANY missing or extra output at all will cause it to fail.
This is why Norm said "Bring your code into your own environment so you can debug it."
On a hard enough problem, this will almost always be necessary, and is extra work because the standard HackerRank uses is to give your program all the input from STDIN and to have the checker read all the output from successive runs of your program on STDOUT.  On some trivial problems you can hack up something that will just hardcode the input, or let you enter it as parameters to your main, but is in itself a programming skill that needs to be developed.  I and others here could help you do that, but when first learning HackerRank I often found that part very challenging.  Often the interesting "magic" is in one or more functions/methods you are writing, and a standard "stub" program can be faked up in your IDE that will call it with whatever inputs to it you need.
Different people would find different thresholds on when this is necessary.  Some will start every non-trivial challenge in their IDE, doing the work up front, others would only do it as a last resort.

When you think you have it working, you can bring it back into HackerRank to "Run Code" to see if it still works for the easy test cases, and eventually to "Submit Code" and see if it works for every last darn test case they have dreamed up.  Remember, those annoying test cases that differentiate from "pretty good code" to "really good code that works for ALL inputs in time and without running out of memory" is the biggest value of HackerRank in my opinion.

So, there are two things that may make you feel you need to go to this length:
1. You actually need to run in a full debugger.  You can not set breakpoints in HackerRank runs, there is no use of breakpoints or stepping thru the code available as an option.  If you are at a point where you need to do this, it is time to bring your code to your favorite IDE.  This will take some work/time.  You may also need to bring over a test case that you have had to buy because everything "works great" for the ones everyone gets to see for free.
2. You are failing a test case or two (or more) that you feel you could get thru just by running it and watching what happens, perhaps with print statement debugging that used to be the only kind people could do in dinosaur days, and rarely need to do nowadays, because the problem can only be reproduced somewhere you don't have access to an IDE or debugger.  This skill back from "the Old Days" will often get you thru HackerRank problems, once you see what was wrong you need to remove or comment out any debugging output you have added, because if the checker sees it, you will fail the tests even if your code was otherwise correct.

How do you do this?  When you "Run Code" there is a Check Box for [ ] "Test against Custom Input".
This will allow you to run your code against ANY test case, either one you made up on purpose or one you bought because you were surprised and dismayed that your solution failed for.  You can paste your test case input into a box at this point.  If the test case is extremely large, it may not fit into the supplied box and that just sucks, it has happened to me in the past.  I'm not sure what to tell you if that ever happens, I have in the past sometimes had to buy a second or third failing test case until I found one small enough.  This should be very rare, however.
Now, you can run your sample code against any random input that would be valid (or not, please be careful!) and see what happens including any debugging print statements you have added.  You won't be able to set breakpoints or view variable values by just mousing over them, but this is quite often enough.  It will not "grade" you on this, but many times this will show you what is going on in a run of your program as it is with specific input data.  I have found and then fixed problems in hundreds of submissions using this technique.

These approaches have gotten people thru hundreds or thousands of HackerRank challenges that were difficult (or seemed almost impossible) at the time.

The good news is that you have become stuck for the moment on a relatively very easy problem.  What Piet said was "the answer" and should get you thru this specific challenge but everything I wrote will eventually be necessary for everyone who is neither hopeless nor a one in a million absolute genius.  Read what Piet said and re-read the problem statement, you may not need to do any of these things.

At the minimum, learn how to "Run Code" with custom input and some print statement debugging that you will remove before you "Submit Code".  Almost everyone will hit situations where they need to do (at least) that, and it is much easier than moving back and forth to your personal local IDE that gives you full and total control of a run, at the cost of setting up all the input in a way that will be read the same way as in "Run Code"/"Submit Code".  People here can help you do that, I usually edit the boilerplate code they give you for input reading to read from a text file -- you probably do NOT need to do this at this point.

So relax, I sympathize with your larger-scale problem of wanting to advance in your programming skills as well as the issues with "How do I productively use HackerRank to do so??" which I have addressed in this reply.
 
Junilu Lacar
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm not sure why you decided to rewrite the code given in the problem. Most of what you need is already given in the original statement. The fact that the first input value is the number of elements to be sorted strongly suggests using a fixed-length data structure like an array instead of an ArrayList as you are doing. All you really needed to do was to add the totalSwaps variable and print out the results. In all, it would have been at most 10 lines of code in addition to what was already given. You just made it much harder for yourself by rewriting the base algorithm code.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The answers others have given you explains why this problem was failing, and should be all you need for this problem.

Eventually, you will almost certainly need the stuff I said if you keep going on harder problems.

One of the skills HackerRank tests, beyond computer science and the use of the programming language you choose to code the solutions in is READING THE PROBLEM CORRECTLY.

I have had ones where I was using cool Java tricks, advanced data structures and algorithms and was surprised my code failed on "Run Code".

Oops, I needed to read the problem better!  On HackerRank, you must always produce precisely and exactly the output that is asked for.  Nothing more or less.  Otherwise you break the auto-checker and get no points.

Don't stress, but DO fully read the problem and be sure you know EXACTLY what they are asking you to output.

On later, harder problems, they might ask you to count things that your code is generating.  You would run out of memory if you tried to have your program remember them all, and would fail the test if you did print them out.  They just want to see the final total count of whatever you did, not have you print them out.

This early problem is actually good real world experience for harder and more complex problems later.
 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Norm Radder wrote:

 why ?


What output from your program is incorrect and causing it to fail?

The debugging is to find what is wrong so it can be fixed.

The posted code compiles and executes on my PC.



But, why is it that mine there is nothing showing up in my console ?

It shouldn't require me to do any input since it is hard coded as suggested by you.

How did you manage to make your ide compile?
 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Piet Souris wrote:To add to Norms reply: the bubblesort itself is oke, just what you report is wrong.



What I reported is wrong? The picture is taken from the output from HackerRank.

I didn't create it myself.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Additionally, Norm's StringReader() trick is fantastic.
There will be a bunch of times I will use that when cutting-and-pasting into an IDE from HackerRank.
It won't always work well because many times that I needed to debug all inputs less than like, 10000 lines were working just fine, and it is not too easy to throw 12000 lines into a StringReader, but if the input is small but one nevertheless needs IDE-level debugging it is a great trick.
Other times, using "Run Code" with "Custom Input" and some print statement debugging will be quicker and easier, as I'd described above.

All of the replies will eventually be useful if the OP keeps on with HackerRank long enough, but the one-line-takeaway here is probably "Read the Problem Carefully.  Make sure your output matches exactly what was requested, nothing more or less."
 
Norm Radder
Master Rancher
Posts: 4454
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I saved the source in my testing folder and used the javac command in the command prompt:
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

tangara goh wrote:

Piet Souris wrote:To add to Norms reply: the bubblesort itself is oke, just what you report is wrong.



What I reported is wrong? The picture is taken from the output from HackerRank.

I didn't create it myself.



Your output does not match what is requested for the problem.

This is an easy case of what will undoubtedly happen again sometime later on harder problems.

Reading the problem statement and following thru giving the exact output requested is a skill developed across many different problems of many types on HackerRank.

Some would consider it equally important to testing your knowledge of Java or other languages or of data structures and algorithms.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:I'm not sure why you decided to rewrite the code given in the problem. Most of what you need is already given in the original statement. The fact that the first input value is the number of elements to be sorted strongly suggests using a fixed-length data structure like an array instead of an ArrayList as you are doing. All you really needed to do was to add the totalSwaps variable and print out the results. In all, it would have been at most 10 lines of code in addition to what was already given. You just made it much harder for yourself by rewriting the base algorithm code.



I agree that it is rarely appropriate to so radically re-write the given code on an Easy or Medium HackerRank problem.
The Hard ones are another world entirely to themselves, this is not one of those.

I suspect the problem came about because he asked someone "too smart" about how to do this!

Looking at the problem statement, he needed a method like this:


I see the problem now!!!
In their sample code, they want a void method named "swap" that takes two inputs by reference and swaps their values.
This is trivial in nearly every language I know except Java, because Java only allows "pass by value".

So, the code needed to be changed from:


to:


calling the static method I suggested.
Instead of making that one change and adding that one simple function, the person the OP went to for assistance built him a time machine and a spaceship.
Except for the swap method, the original problem statement already gave almost everything needed in this case.

You don't even necessarily need to write the method I showed, because you can replace the call to swap(...)
with the inline code:
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;

The example as existing didn't adapt too well to Java, I can remember when I first focused on Java I called up a long-term C/C++ programmer friend and said "I can't write a function to swap two ints in Java!!  Nobody can!!"  It was a revelation.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

tangara goh wrote:

I am sure this code is 100% correct because I was taught by this very super experienced guy in the discord where he spent nearly 3 hours walking me thru why I should use Do while loop instead of the nested loop which is really confusing to use.



I am almost sure that it is not good for the nested loop to be really confusing to someone for this problem.
Bubble Sort was the first sort I ever learned, and the only one I knew for somewhere between 4 and 8 years.
I used nested for loops to do it because the language I was using had neither while nor do while.

It is perhaps a good idea to prefer while to for , and to make use of enhanced for loops (foreach loops) where they work well, and abuse of break and continue can make code harder to read.

But it would probably be important for you to be able to read and work with code like the original example implementing it as for { for { } if break } even if you don't make that your coding style.

I note that the very interesting Wikipedia article does show it with a combination of "repeat until" wrapped around a for loop.
That shows the huge influence of Pascal in Computer Science circles, and the closest Java gives us is do { } while ().

I find it slightly easier to understand that version than the original version which relies on if (exit_condition) break

But both should be understandable to you, and I would say that making the minimum changes on Easy and Medium problems should be your usual goal.

In this case, the code as shown was fine for several languages but hard in Java, which has no void swap(int i1, int i2) method.
Once you got by that hurdle, the next five kinds of sort you learned could all use that same solution for swapping elements.
I therefore consider this problem to not be "Easy" in Java unless someone explains this issue to you and shows you how to swap.

I would make that a separate, additional 0th problem in a series on implementing sorts in Java, before I treated any specific algorithms.

Are you comfortable with what I said about how to implement swap(  ) ?  Can you understand the original HackerRank solution using two for loops and a break?

Like everyone, I first noticed your solution didn't print out what was asked of it, but HOW your code got so very far away from what they gave you to start with seemed a more interesting question to me.

You should probably convince yourself of the equivalence of the code provided by HackerRank (with nested for loops and a break) and the code the person who helped you gave you (which looks as much like the Wikipedia pseudocode as you can get in Java).  I think it would be good to get comfortable with that before moving on.  The introduction of the ArrayList just to access a standard swap method was inappropriate for this problem, which should stay as close to the original code as is possible in whatever language you are using.

Additionally, I will say one last time to always be sure that your code outputs exactly what they ask for.
It is possible to spend a LONG time doing all the very hard work and getting zero points for it otherwise.
Normally "Run Code" will confirm this part for you.
For more Entry Level programming jobs, the most important skill from their point of view may be following instructions exactly, so this skill is work-related.

Cheers!
 
Junilu Lacar
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

tangara goh wrote:I am sure this code is 100% correct because I was taught by this very super experienced guy in the discord where he spent nearly 3 hours walking me thru why I should use Do while loop instead of the nested loop which is really confusing to use.


"It ain't so much the things that people don't know that makes trouble in this world, as it is the things that people know for sure that ain't so."— Mark Twain.

Is there anything wrong that you have seen that is not right ?


You have been told multiple times what's wrong with your program but you refuse to listen. Your super experienced guy is wrong. It's not the first time that has ever happened, nor will it be the last.
 
Junilu Lacar
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The way the input is processed is fairly straightforward if you just used a Scanner.

This code will work without user interaction if you use either a pipe or redirection which is how I bet HackerRank is doing it on their end:
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Agreed that Scanner version is neater and should work fine with either piping 'cat input.txt' or < input.txt on command line.

However, so should his originally posted code, no?

I see now that he had been having trouble with doing input redirection in Eclipse and others tried to help him with that in another thread.

There is a lot of useful information on this thread (and the other recent one) about how to bring a HackerRank solution over to an IDE and back.

I recently had an interview-related coding challenge that was 90 minutes long, and I needed every minute of it.

I had less than 60 seconds left to bring all-of-my-solution-but-main-which-I-had-re-written-to-work-in-the-IDE into HackerRank and SUBMIT CODE.

The problem was hard, and I literally didn't even have time for a RUN CODE before SUBMIT, actually exactly one and there was some stupid error from bringing it over.

Fixed that and hit SUBMIT CODE, wound up getting 100% score on a pretty difficult problem.  Well, it seemed difficult in the 90 minutes.  For the next six hours I kept getting ideas about how to do it better or easier, after it was submitted!

Bottom line, for anyone using HackerRank, developing skills at moving stuff to and from IDE and HackerRank is a long-term useful skill in itself.
I'd been muddling thru with some approaches, workable but a bit clunky, and learned some new tricks/shortcuts that are great for acheiving this when they apply.
 
Junilu Lacar
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think a lot of the difficulty OP is having comes from not knowing how to use Eclipse. The code I gave can be easily run from Eclipse: all you have to do hit the Run button then go to the Console tab and type in a number and hit enter (to set the value of the n variable) and then type in n integers separated by spaces and hit enter to set the elements of the array to be sorted. For that matter, OP's original code could be used the same way, too.

Give me a little time and I'll try to post a quick screencast to demo this.

Here's the link:  https://youtu.be/PvmdPGBAtXk  

I made the video with QuickTime on my Mac; not sure the video quality is very good (first time doing this with QT) but you should still be able to make out what I'm doing in the Console tab.
 
Junilu Lacar
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bonus demo for how to use code templates in Eclipse to reduce your typing effort and make the IDE do it for you:
https://youtu.be/8KKM_oPbxN4

Summary of what I demo in this video:

Code templates
=========
main - to quickly generate a public static void main method
new - to quickly declare a new object
for - to quickly type out a for loop skeleton
sysout - to generate a System.out.println() statement

Also:
Cmd + 1 - to activate the Quick Fix feature (Windows: Ctrl+1)
Ctrl + Space - to bring up contextual suggestions (Windows: Ctrl+Space)

To get Eclipse to suggest a name, just type out the first letters of the camelcase name, e.g. "nI", and Eclipse will suggest all names that match that pattern when you hit Ctrl+Space. This is contextual so if you do this at the start of a line where a type name can be used, you'll get a list of matching class/interface/enum names. If you do it where a method name could be entered, for example, after typing "Math." then Eclipse will bring up a list of methods of the class that match the name pattern you give.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So much extremely useful advice on this thread which is now somewhat poorly named, because the advice is so generally applicable.

Anyway, as to why the OP got help re-writing the code, does anyone else find it odd that with all of the stuff added to Arrays helper class to make them feel more like Collections,

that there is no swap() method for arrays?

Is there something obvious I am missing?

I mean, obviously, you would need overloads for int[], short[], float[], Object[] etc. but they do that for several other useful things from Collections that people needed in Arrays too because Project Valhalla is taking forever to get here...

I was presuming it was there and I forgot to reference it, but no, definitely no .swap() method in Arrays helper class -- at the moment I don't see why.
 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:Plus, it's right there in the problem statement, plain as day:

Hint: To complete this challenge, you will need to add a variable that keeps a running total of all swaps that occur during execution.


You haven't done that.



Tks Junilu, after I add in one more variable totalCount and indeed it gives me the correct no of swap.

The thing is I am puzzled at Allison P's solution here where she uses 2 loops to do the job.

But, when I changed the nest loop to one, it works as well.

So, why use 2 loops when you can use one will do?  
 
Junilu Lacar
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

tangara goh wrote:
The thing is I am puzzled at Allison P's solution here where she uses 2 loops to do the job.

But, when I changed the nest loop to one, it works as well.


Are you sure it works for all data? What data did you use to come to the conclusion that it works with just one loop?
 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

tangara goh wrote:
Are you sure it works for all data? What data did you use to come to the conclusion that it works with just one loop?



Hi Junilu,

That's the reason I am asking in this forum because I know Alison P is a super top coder.

"4 55 44 66 7"

There must be a reason things are done like that.

Hope you could explain things to me.

Tks.

 
Junilu Lacar
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are jumping to (invalid) conclusions because the output of the program appears to be the same.

Try doing this after the call to bubbleSort():

This will show you if the array is actually sorted and not just with the biggest and smallest elements correctly placed. Alternatively, you could also do this:


 
tangara goh
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:You are jumping to (invalid) conclusions because the output of the program appears to be the same.

Try doing this after the call to bubbleSort():
[code=java:firstline[54]]
System.out.println("Array is sorted in " + bubbleSort(n) + " swaps.");



I did it with the above lines of code with the 1 loop and 2 loops and it ended up the same hence my question here.
 
Junilu Lacar
Sheriff
Posts: 16564
272
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

tangara goh wrote:That's the reason I am asking in this forum because I know Alison P is a super top coder.


I'm not saying her original program was wrong but you have to remember that no programmer is perfect. Even the best programmers can make mistakes. That's why testing is super important.

But now that we're here, none of the solutions so far have shown a simple optimization to the algorithm that can significantly reduce the number of comparisons made. Given an unsorted array, each pass of the bubble sort algorithm is guaranteed to result in at least the largest misplaced element being put where it needs to be in the sorted array. This means that you can reduce the number of elements you compare on each successive round. This Wikipedia article describes how the bubble sort implementations you have shown so far can be optimized to reduce the number of comparisons made: https://en.wikipedia.org/wiki/Bubble_sort
 
Do not meddle in the affairs of dragons - for you are crunchy and good with ketchup. Crunchy tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic