I get the following error:
quicksort(int[],int,int)cannot be applied to(int[])
When I compile this:
import java.util.*;
public class Sort {
public static void main(String[] args){
Random rand = new Random();
int[] tab = new int[10];
for(int i = 0; i < tab.length; i++) {
tab[i] = rand.nextInt(100);
System.out.println("Before: ");
show(tab);
quicksort (tab);
System.out.println("After: ");
show(tab);
}
}
static void quicksort(int tab[], int x, int y) {
int i,j,v,temp;
i=x;
j=y;
v=tab[(x+y) / 2];
do {
while (tab[i]<v)
i++;
while (v<tab[j])
j--;
if (i<=j) {
temp=tab[i];
tab[i]=tab[j];
tab[j]=temp;
i++;
j--;
}
}
while (i<=j);
if (x<j)
quicksort(tab,x,j);
if (i<y)
quicksort(tab,i,y);
}
static void show (int tab[]) {
for (int i = 0; i <tab.length; i++) {
System.out.println(tab[i]);
}
}
}
What am I doing wrong?
Just after the line to print out "before", you have:
quicksort (tab);
The function you designed needs three arguments. You can either add the extra arguments:
quicksort (tab, 0, tab.length - 1)
Or add a new function such as:
public quicksort(int[]) {
quicksort(tab, 0, tab.length - 1);
}
the function "quicksort" that you define asks for 3 parameters, but you are only providing one.
Because your quicksort function has 3 parameters, but your call gives only one.
Edit: second :(
your code should call
quicksort (tab,0,10);
In your outer calll, so you can sort the list.
Without knowing what you're writing code in, I strongly recommend using an IDE if you haven't adopted one already. Particularly Eclipse for Java.
Eclipse would underline the offending line of code and make some suggestions to you, (in addition to offering code completion). A text editor, like JEdit does not.
Note: I've been told IntelliJ is good, but you can't beat Eclipse's price (free).
BTW: You could just use Arrays.sort() which is a built in function. You wouldn't write a function like this in real life. (only as homework)
Related
What I am trying to do is create an array that pulls even numbers from another array. I'm not sure if I have gone about it the right way. I've look for ways of returning from statements like you would functions/methods and I can't find anything, not even sure if it is possible.
Anyway, the issue I am having here is the 'return evenArray' below 'cannot find symbol.' I am not sure what this means?
public static int[] getEvenArray(int[] array)
{
int dividedBy = 2;
int evenElement;
int evenCount = 0;
for(int i = 0; i < array.length; i++)
{
int[] evenArray;
evenElement = array[i] % dividedBy;
if(evenElement == 0)
{
evenCount++;
}
else
{
array[i] = 0;
}
evenArray = new int[evenCount];
for(int x = 0; x < evenArray.length; x++)
{
if(array[i] != 0)
{
evenArray[x] = array[i];
}
}
}
return evenArray;
}
This is for a tutorial from one of my lectures, it's a little bit challenging to say the least :-)0
evenArray is defined within the scope of the for loop. (Actually a little worse than that; you're redeclaring it on each iteration so discarding the previous contents).
So once you're outside the for loop you can't refer to it.
Quickest fix is to use a std::vector<int> for this type, and declare it at the start of the function. Also change the return type of the function to the same. Don't forget to size the vector appropriately.
(Moving on, a smart lecturer will ask you about returning a std::vector which could potentially take a deep copy of that vector. Pre C++11 you'd mention return value optimisation, now you can talk about r-value references. No deep copy will be taken since the move constructor will be used).
Variable declared inside a block is not visible outside of it; move this int[] evenArray; to very start of function.
I'm trying to make a program that will read in a class file and if you give it a variable for example you give it "i" in the following example:
public class Example {
public static void main( String[] args) {
int i = 1;
int j = 5;
int k = 2;
i = i + k;
System.out.println(i);
}
}
Then my program will return
int i = 1;
int k = 2;
i = i + k;
System.out.println(i);
Since these are variables that affect i.
I'm not sure how to do this. So far I've tried using javaparser which takes in the file and finds all the VariableDeclarationExpr using a visitor pattern. However, this won't print out the bottom two cases in the code above.
Can anyone give me any hints to how to find them?
The VariableDeclarationExpr represents only declarations (like in your case int i = 1;). But the other two statements in your code are not declarations. They are assignments (probably AssignmentExpr) and a method call (probably MethodCallExpr). So I would first think about where the variable i can appear and then cover all the cases individually. I hope that helps
I am trying to write a method to remove a chromosome from my population. The method I have written is below. I am getting an out of bounds error when I run the code. Population is constructed with an ArrayList. The getChromosomeFitness method returns an int value score. Can someone spot my error?
void removeWorst()
{
int worst = population.get(0).getChromosomeFitness();
int temp = 0;
for(int i = 1; i < population.size(); i++)
{
if (population.get(i).getChromosomeFitness() < population.get(worst).getChromosomeFitness())
{
worst = population.get(i).getChromosomeFitness();
temp = i;
}
}
Chromosome x = population.get(temp);
population.remove(x);
}
You should probably change
if (population.get(i).getChromosomeFitness() < population.get(worst).getChromosomeFitness())
to
if (population.get(i).getChromosomeFitness() < worst)
You don't assure that in this line population has an element with the index 0:
int worst= population.get(0).getChromosomeFitness();
Try to add this to your method:
void removeWorst() {
if (population.isEmpty()) {
return;
}
...
There are several potential problems in your code:
int worst= population.get(0).getChromosomeFitness();
you need to make sure that population.isEmpty() is false
population.get(worst).getChromosomeFitness()
same thing, you need to make sure that (worst >= 0 && worst < population.size()).
The issue seems that you are getting the actual fitness rather than the object itself. The issue is with this line: int worst= population.get(0).getChromosomeFitness();. This is returning an integer value which is not related to the List's dimensions, as you said, it is the fitness of the chromozome, which could be well over the size of the list.
This should solve the problem:
void removeWorst()
{
int temp=0;
for(int i=1; i <population.size();i++)
{
if (population.get(i).getChromosomeFitness() < population.get(temp).getChromosomeFitness())
{
temp=i;
}
}
Chromosome x= population.get(temp);
population.remove(x);
}
That being said, a probably neater way of doing this would be to use a custom comparator to sort the list and then simply remove the last element.
Make sure population has something in it before trying to remove something from it?
I am very interested in how to sort 5 items using only 7 comparisons.
I think I understand the theory how to do it but unfortunately I'm not able to write it as a code.
Here I found an example in LISP
I really tried to understand it but it seems to me be not working. For example on the numbers 5,4,3,2,1.
Could anybody please give me an example code, but not in LISP? I prefer Java or C/C++. It would really help me in school.
Thank you in advance
P.S. Sorry for my english
Edit:
Here I add some piece of code I wrote in Java.
Variables a,b,c,d,e are there only for my better orientation in code.
I'm able to write specific code for specific input items, that's no problem.
But I can't write general code.
public static void sort(int p[]) {
int a = 0;
int b = 1;
int c = 2;
int d = 3;
int e = 4;
if (p[a] > p[b]) {
swap(p,a,b);
}
if (p[c] > p[d]){
swap(p,c,d);
}
if (p[b] > p[d]){
swap(p,b,d);
}
if (p[e] < p[b]) {
if (p[e] < p[a]) {
swap(p,a,e);
swap(p,d,e);
//swap(p,b,d);//BLBE
}else{
swap(p,b,e);
swap(p,d,e);
}
}else {
if (p[e] < p[d]) {
swap(p,d,e);
}
}
if (p[c] < p[b]) {
if (p[c] < p[a]) {
swap(p,a,c);
swap(p,b,c);
}else
{
swap(p,c,b);
}
}else {
if (p[c] > p[d]) {
swap(p,d,c);
}
}
}
Writing a general comparison-based sorting algorithm takes O(n lg n) comparisons. If I'm not mistaken, then all O(n lg n) sorting algorithms will sort 5 items in about 7 comparisons. Mergesort, Heapsort and Quicksort if you're lucky.
Write a program to print out all possible values of int data type from the smallest to the largest, using Java.
Some notable solutions as of 8th of May 2009, 10:44 GMT:
1) Daniel Lew was the first to post correctly working code.
2) Kris has provided the simplest solution for the given problem.
3) Tom Hawtin - tackline, came up arguably with the most elegant solution.
4) mmyers pointed out that printing is likely to become a bottleneck and can be improved through buffering.
5) Jay's brute force approach is notable since, besides defying the core point of programming, the resulting source code takes about 128 GB and will blow compiler limits.
As a side note I believe that the answers do demonstrate that it could be a good interview question, as long as the emphasis is not on the ability to remember trivia about the data type overflow and its implications (that can be easily spotted during unit testing), or the way of obtaining MAX and MIN limits (can easily be looked up in the documentation) but rather on the analysis of various ways of dealing with the problem.
class Test {
public static void main(String[] args) {
for (int a = Integer.MIN_VALUE; a < Integer.MAX_VALUE; a++) {
System.out.println(a);
}
System.out.println(Integer.MAX_VALUE);
}
}
Am I hired?
Simplest form (minimum code):
for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) {
System.out.println(i);
}
No integer overflow, no extra checks (just a little more memory usage, but who doesn't have 32 spare bits lying around).
While I suppose
for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++)
System.out.println(i);
has fewer characters, I can't really say that it is simpler. Shorter isn't necessarily simpler, it does have less code though.
I just have to add an answer...
public class PrintInts {
public static void main(String[] args) {
int i = Integer.MIN_VALUE;
do {
System.out.println(i);
++i;
} while (i != Integer.MIN_VALUE);
}
}
We don't want the body repeated (think of the maintenance!)
It doesn't loop forever.
It uses an appropriate type for the counter.
It doesn't require some wild third-party weirdo library.
Ah, and here I had just started writing
System.out.println(-2147483648);
System.out.println(-2147483647);
System.out.println(-2147483646);
Okay, just give me a few weeks to finish typing this up ...
The instructions didn't say I have to use a loop, and at least this method doesn't have any overflow problems.
Is there something tricky that I'm not catching? There probably is... (edit: yes, there is!)
class AllInts {
public static void main(String[] args) {
// wrong -- i <= Integer.MAX_VALUE will never be false, since
// incrementing Integer.MAX_VALUE overflows to Integer.MIN_VALUE.
for (int i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) {
System.out.println(i);
}
}
}
Since the printing is the bottleneck, a buffer would improve the speed quite a lot (I know because I just tried it):
class AllInts {
public static void main(String[] args) {
// a rather large cache; I did no calculations to optimize the cache
// size, but adding the first group of numbers will make the buffer
// as large as it will ever need to be.
StringBuilder buffer = new StringBuilder(10000000);
int counter = 0;
// note that termination check is now <
// this means Integer.MAX_VALUE won't be printed in the loop
for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) {
buffer.append(i).append('\n');
if (++counter > 5000000) {
System.out.print(buffer);
buffer.delete(0, buffer.length()-1);
counter = 0;
}
}
// take care of the last value (also means we don't have to check
// if the buffer is empty before printing it)
buffer.append(Integer.MAX_VALUE);
System.out.println(buffer);
}
}
Also, this version will actually terminate (thanks to Daniel Lew for pointing out that there was, in fact, something tricky that I wasn't catching).
The total run time for this version (run with -Xmx512m) was 1:53. That's over 600000 numbers/second; not bad at all! But I suspect that it would have been slower if I hadn't run it minimized.
When I first looked at this, my first question was 'how do you define smallest and largest'. For what I thought was the most obvious definition ('smallest' == 'closest to 0') the answer would be
for (int i = 0; i >= 0; i++) {
System.out.println(i);
System.out.println(-i-1);
}
But everyone else seems to read 'smallest' as 'minimum' and 'largest' as 'maximum'
Come on folks, it said using java. It didn't say use an int in the for loop. :-)
public class Silly {
public static void main(String[] args) {
for (long x = Integer.MIN_VALUE; x <= Integer.MAX_VALUE; x++) {
System.out.println(x);
}
}
}
Another way to loop through every value using an int type.
public static void main(String[] args) {
int i = Integer.MIN_VALUE;
do {
System.out.println(i);
} while (i++ < Integer.MAX_VALUE);
}
Given the overview of the best answers, I realized that we're seriously lacking in the brute-force department. Jay's answer is nice, but it won't actually work. In the name of Science, I present - Bozo Range:
import java.util.Random;
import java.util.HashSet;
class Test {
public static void main(String[] args) {
Random rand = new Random();
HashSet<Integer> found = new HashSet<Integer>();
long range = Math.abs(Integer.MAX_VALUE - (long) Integer.MIN_VALUE);
while (found.size() < range) {
int n = rand.nextInt();
if (!found.contains(n)) {
found.add(n);
System.out.println(n);
}
}
}
}
Note that you'll need to set aside at least 4 GB of RAM in order to run this program. (Possibly 8 GB, if you're on a 64-bit machine, which you'll probably require to actually run this program...). This analysis doesn't count the bloat that the Integer class adds to any given int, either, nor the size of the HashSet itself.
The maximum value for int is Integer.MAX_VALUE and the minimum is Integer.MIN_VALUE. Use a loop to print all of them.
Package fj is from here.
import static fj.pre.Show.intShow;
import static fj.pre.Show.unlineShow;
import static fj.data.Stream.range;
import static java.lang.Integer.MIN_VALUE;
import static java.lang.Integer.MAX_VALUE;
public class ShowInts
{public static void main(final String[] args)
{unlineShow(intShow).println(range(MIN_VALUE, MAX_VALUE + 1L));}}
At 1000 lines/sec you'll be done in about 7 weeks. Should we get coffee now?
Just improving the StringBuilder's approach a little:
2 threads + 2 buffers (i.e. StringBuilder): The main idea is that one thread fills one buffer while the other thread dumps the content of the other buffer.
Obviously, the "dumper" thread will always run slower than the "filler" thread.
If the interviewer was looking for all the Integer values possible in Java, You might try giving him a solution using Long:
class AllIntegers{
public static void main(String[] args) {
for (int i = Integer.MIN_VALUE; i < Long.MAX_VALUE; i++) {
System.out.println(i);
}
System.out.println(Long.MAX_VALUE);
}
}
This should print a range from -9223372036854775808 to 9223372036854775807 which is way more than you would achieve using Integer.