This algorithm given to us in class:
I am having trouble in my attempts to determine the output when the input is an array A[60,35,81,98,14,47].
I wanted to get used to the pseudocode syntax, so I tried to convert this to Java syntax, but the resulting program won't show a result. This is my converted code:
public class Driver
{
public static void main(String[] args)
{
int[] test = {60, 35, 81, 98, 14, 47};
int[] converse = new int[6];
converse = countSort(test);
for(int i : converse)
{
System.out.println(converse[i]);
}
}
public static int[] countSort(int[] a)
{
int[] s = new int[6];
int[] count = new int[6];
int n = a.length + 1;
for(int i = 0; i < (n-1);)
{
count[i] = 0;
}
for(int i = 0; i < (n-2);)
{
for(int j = (i+1); i < (n-1);)
{
if(a[i] < a[j])
{
count[j] = count[j]+1;//What
}
else
{
count[i] = count[i]+1;
}
}
}
for (int i = 0; i < (n-1);)
{
s[count[i]] = a[i];
}
return s;
}
}
int[] test = {60,35,81,98,14,47}; is never used.
Did you mean to pass test into countSort? and also do something with it's result.
While I haven't looked at the algorithm really, there is something else wrong here:
int n = a.length + 1;
for (int i = 0; i < (n - 1);) {
count[i] = 0;
}
This will loop indefinatetly. i never incerements.
Your array test is never used.
In your for loops, i never gets incremented. It will loop infinetely.
Instead of n = a.length+1; just use n = a.length. it makes your code easier to read. You then also have to check all your loops.
When you are running the code with a testset larger or less than 6 integer values your code wont run correctly or even fail with an ArrayOutOfBounds Exception, as you allocate the arrays s and count for only 6 values.
Try int[] count = new int[a.length]; instead of int[] count = new int[a.length];. The same for s.
Related
So, I'm new to programming and I have this exercise where I have to read an int[][] array with the age and a handicap level of people trying to start a membership in a Club, with two categories, Senior and Open.
My job is to read the array for example [[45, 12],[55,21],[19, -2]] where the first int is the age and the second the handicap level. If the age is at least 55 and the handicap level is higher than 7 then the person gets a Senior membership if not he gets an Open one. My idea was to see the int[][] as a matrix and add both numbers (age and level) and if the number is higher than 62 I would classify it as a Senior otherwise as open.
My method looks like this:
public class montecarlo {
static String[] openOrSenior(int[][] a) {
int i, j, sum;
String[] abo = new String[a[0].length];
for (i = 0; i < a.length; i++)
for (j = 0; j < a[0].length; j++ ) {
sum = 0;
int x = a[i][j];
sum = sum + x;
if (sum > 62)
abo[i] = "Senior";
else
abo[i] = "Open"; //this would be line 12
}
return abo;
}
public static void main(String[] args) {
int [][] a = {{42, 12},{55, 21},{19,-2}};
String[] x = openOrSenior(a); //this would be line 20
Out.print(x); //here was to see what i'd get if i let it run
}
}
This is the error i get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at montecarlo.openOrSenior(montecarlo.java:12) at
montecarlo.main(montecarlo.java:20)
I would really appreciate some help.
Here's a more straightforward version with syntax errors fixed.
public class montecarlo {
static String[] openOrSenior(int[][] a) {
String[] abo = new String[a.length]; // you had a[0] here instead of a
for (int i = 0; i < a.length; i++) {
if (a[i][0] >= 55 && a[i][1] > 7) {
abo[i] = "Senior";
} else {
abo[i] = "Open";
}
}
return abo;
}
}
This fixes all the array bounds problems, but as others mentioned, not the flaws in the semantics. It makes no sense to completely rewrite this answer, so I keep it as it is.
I noticed two major problems in your code that could cause said exception.
On line 12, your problem is, you define the array size wrong.
String[] abo = new String[a.length];
But there is one more problem like that, as the second cycle takes incorrect length, you need:
for (j = 0; j < a[i].length; j++ )
OK, this problem should never happen as all your arrays have same length. But should there be someone with no handicap as just {31} alongside someone with handicap, it crashes in the cycle.
For next practice - create a new class that has two int variables, age and handicap. That is how you do it in Java. An array of integers makes no difference what is age and what is handicap.
import java.util. * ;
import java.lang. * ;
import java.io. * ;
class montecarlo {
static String[] openOrSenior(int[][] a) {
int i,
j,
sum,
x;
/*Declare x here, otherwise in your code it will create a new variable everytime in your for loop*/
String[] abo = new String[a.length];
/* a.length not a[0].length */
for (i = 0; i < a.length; i++) {
sum = 0;
/* sum should initialised to zero here every time outside the inner for loop*/
for (j = 0; j < a[0].length; j++) {
x = a[i][j];
sum = sum + x;
}
/* check outside for loop whether the total sum is greater than 62 */
if (sum > 62) {
abo[i] = "Senior";
}
else {
abo[i] = "Open";
}
}
return abo;
}
public static void main(String[] args) {
int[][] a = {
{
42,
12
},
{
55,
21
},
{
19,
-2
},
{
72,
74
}
};
String[] x = openOrSenior(a);
System.out.print(x);
}
}
Here is the working demo of what you wanted.
I have pointed out your mistakes in comments.
You have done several mistakes, Please watch the code carefully and understand what you did wrong.
Also there is a flaw in your logic which you should fix yourself.
for example age=60, handicap level=3
total=60+3=63, which is greater than 62 and hence should be "Senior" according to your logic but it is wrong since the handicap level is below 7.
Try something like
public class montecarlo {
public static void main(String[] args) {
int [][] a = {{42, 12},{55, 21},{19,-2}};
String[] x = openOrSenior(a); //this would be line 20
System.out.println(Arrays.asList(x)); //here was to see what i'd get if i let it run
}
static String[] openOrSenior(int[][] a) {
int i, j, sum;
String[] abo = new String[a.length];
System.out.println(abo.length);
for (i = 0; i < a.length; i++)
for (j = 0; j < a[0].length; j++) {
sum = 0;
int x = a[i][j];
sum = sum + x;
if (sum > 62)
abo[i] = "Senior";
else abo[i] = "Open";
} //this would be line 12
return abo;
}
}
I'm new to java and I have a homework assignment where I need to find the Mean, median and Mode of an Array. For some reason my code is not putting out the correct answer.
Here is the code I was provided to create the Arrays:
public static void main(String[] args) {
int[] test01 = new int[]{2,2,2,2,2};
int[] test01Results = new int[]{2,2,2,2};
int[] test02 = new int[]{1,2,1,3,5,6,6,1,2,2,2,99,100};
int[] test02Results = new int[]{2,2,17,100};
int[] test03 = new int[]{100,200,300,400,300};
int[] test03Results = new int[]{300,300,260,400};
int[] test04 = new int[]{100};
int[] test04Results = new int[]{100,100,100,100};
int[] test05 = new int[]{100,1};
int[] test05Results = new int[]{1,100,50,100};
Here is what I came up with to try to calculate the Mode:
public int mode() {
int result = 0;
// Add your code here
int repeatAmount = 0; //the amount of repeats accumulating for the current i
int highestRepeat=0; // the highest number of repeats so far
for (int i=0; i<numberArray.length; i++) {
for (int j=i; j<numberArray.length; j++) {
if (i != j && numberArray[i] == numberArray[j]) {
repeatAmount++;
if (repeatAmount>highestRepeat) {
result=numberArray[i];
}
repeatAmount = highestRepeat;
}
repeatAmount=0; // resets repeat Count for next comparison
}
}
return result;
}
I'm getting the correct results for tests 1, 2 and 3 but getting the wrong result for Tests 4 and 5. Does anyone know what I'm doing wrong?
Thanks!
You never assign anything except 0 to highestRepeat. This should work:
public int mode() {
int result = 0;
int highestRepeat=0;
for (int i=0; i<numberArray.length; i++) {
int repeatAmount = 1;
for (int j = i + 1; j < numberArray.length; j++) {
if (numberArray[i] == numberArray[j]) {
repeatAmount++;
if (repeatAmount > highestRepeat) {
result = numberArray[i];
highestRepeat = repeatAmount;
}
}
}
}
return result;
}
Some other improvements:
By starting the inner loop at i+1 you can skip the check if i != j.
By declaring repeatAmount inside the outer loop you can skip
setting it to zero after the inner loop.
If you need some performance, consider using a HashMap for counting the equal array entries.
I'm trying to create a program to create an array of the numbers 1 through 100 and then randomize them. So far I have this, but don't know what to do next:
public class Random100Array
{
public static void main(String args[])
{
{
int[] nums = new int[100];
char current;
int a;
for (int i = 0; i <= nums.length; i++) {
nums[i] = i + 1;
}
for (int i1 = 0; i1 <=nums.length; i1++) {
double random = (Math.random() * 100) + 1;
}
}
}
}
Also, THIS ISN'T HOMEWORK. I am a student and I'm currently on winter break. This program gives me this output for some reason. What am I doing wrong?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Random100Array.main(Random100Array.java:11)
Use < instead of <= in your for loops.
Firstly, you should take care of your for-loops conditions as mentioned in other answers.
Then, for shuffling your input array, you can use this code:
import java.util.Random;
public class Program {
public static void main(String[] args)
{
int[] nums = new int[100];
for(int i = 0; i < nums.length; ++i)
{
nums[i] = i + 1;
}
Random generator = new Random();
for(int i = 0; i < nums.length; ++i)
{
int j = generator.nextInt(nums.length - i);
int tmp = nums[nums.length - 1 - i];
nums[nums.length - 1 - i] = nums[j];
nums[j] = tmp;
}
}
}
Initializing an array with the length of 100 means, you have indices ranging from 0 to 99, so you won't have index 100, thats why you receive this exception. nums.length will be 100 (since you initialize the length with 100. Basically your for-loop is ranging from 0 to 100 (which are 101 nums) this is out of bound.
Use < instead of <= inside the for loops
for shuffeling the array, try something like this:
https://stackoverflow.com/a/1520212/995320
You need to use < and not <=
Also, you can use a try catch to escape the exception, but this would not be considered good practice
Hi i need some help to improve my code. I am trying to use Radixsort to sort array of 10 numbers (for example) in increasing order.
When i run the program with array of size 10 and put 10 random int numbers in like
70
309
450
279
799
192
586
609
54
657
i get this out:
450
309
192
279
54
192
586
657
54
609
DonĀ“t see where my error is in the code.
class IntQueue
{
static class Hlekkur
{
int tala;
Hlekkur naest;
}
Hlekkur fyrsti;
Hlekkur sidasti;
int n;
public IntQueue()
{
fyrsti = sidasti = null;
}
// First number in queue.
public int first()
{
return fyrsti.tala;
}
public int get()
{
int res = fyrsti.tala;
n--;
if( fyrsti == sidasti )
fyrsti = sidasti = null;
else
fyrsti = fyrsti.naest;
return res;
}
public void put( int i )
{
Hlekkur nyr = new Hlekkur();
n++;
nyr.tala = i;
if( sidasti==null )
f yrsti = sidasti = nyr;
else
{
sidasti.naest = nyr;
sidasti = nyr;
}
}
public int count()
{
return n;
}
public static void radixSort(int [] q, int n, int d){
IntQueue [] queue = new IntQueue[n];
for (int k = 0; k < n; k++){
queue[k] = new IntQueue();
}
for (int i = d-1; i >=0; i--){
for (int j = 0; j < n; j++){
while(queue[j].count() != 0)
{
queue[j].get();
}
}
for (int index = 0; index < n; index++){
// trying to look at one of three digit to sort after.
int v=1;
int digit = (q[index]/v)%10;
v*=10;
queue[digit].put(q[index]);
}
for (int p = 0; p < n; p++){
while(queue[p].count() != 0) {
q[p] = (queue[p].get());
}
}
}
}
}
I am also thinking can I let the function take one queue as an
argument and on return that queue is in increasing order? If so how?
Please help. Sorry if my english is bad not so good in it.
Please let know if you need more details.
import java.util.Random;
public class RadTest extends IntQueue {
public static void main(String[] args)
{
int [] q = new int[10];
Random r = new Random();
int t = 0;
int size = 10;
while(t != size)
{
q[t] = (r.nextInt(1000));
t++;
}
for(int i = 0; i!= size; i++)
{
System.out.println(q[i]);
}
System.out.println("Radad: \n");
radixSort(q,size,3);
for(int i = 0; i!= size; i++)
{
System.out.println(q[i]);
}
}
}
Hope this is what you were talking about...
Thank you for your answer, I will look into it. Not looking for someone to solve the problem for me. Looking for help and Ideas how i can solve it.
in my task it says:
Implement a radix sort function for integers that sorts with queues.
The function should take one queue as an
argument and on return that queue should contain the same values in ascending
order You may assume that the values are between 0 and 999.
Can i put 100 int numbers on my queue and use radixsort function to sort it or do i need to put numbers in array and then array in radixsort function which use queues?
I understand it like i needed to put numbers in Int queue and put that queue into the function but that has not worked.
But Thank for your answers will look at them and try to solve my problem. But if you think you can help please leave comment.
This works for the test cases I tried. It's not entirely well documented, but I think that's okay. I'll leave it to you to read it, compare it to what you're currently doing, and find out why what you have might be different than mine in philosophy. There's also other things that are marked where I did them the "lazy" way, and you should do them a better way.
import java.util.*;
class Radix {
static int[] radixSort(int[] arr) {
// Bucket is only used in this method, so I declare it here
// I'm not 100% sure I recommend doing this in production code
// but it turns out, it's perfectly legal to do!
class Bucket {
private List<Integer> list = new LinkedList<Integer>();
int[] sorted;
public void add(int i) { list.add(i); sorted = null;}
public int[] getSortedArray() {
if(sorted == null) {
sorted = new int[list.size()];
int i = 0;
for(Integer val : list) {
sorted[i++] = val.intValue(); // probably could autobox, oh well
}
Arrays.sort(sorted); // use whatever method you want to sort here...
// Arrays.sort probably isn't allowed
}
return sorted;
}
}
int maxLen = 0;
for(int i : arr) {
if(i < 0) throw new IllegalArgumentException("I don't deal with negative numbers");
int len = numKeys(i);
if(len > maxLen) maxLen = len;
}
Bucket[] buckets = new Bucket[maxLen];
for(int i = 0; i < buckets.length; i++) buckets[i] = new Bucket();
for(int i : arr) buckets[numKeys(i)-1].add(i);
int[] result = new int[arr.length];
int[] posarr = new int[buckets.length]; // all int to 0
for(int i = 0; i < result.length; i++) {
// get the 'best' element, which will be the most appropriate from
// the set of earliest unused elements from each bucket
int best = -1;
int bestpos = -1;
for(int p = 0; p < posarr.length; p++) {
if(posarr[p] == buckets[p].getSortedArray().length) continue;
int oldbest = best;
best = bestOf(best, buckets[p].getSortedArray()[posarr[p]]);
if(best != oldbest) {
bestpos = p;
}
}
posarr[bestpos]++;
result[i] = best;
}
return result;
}
static int bestOf(int a, int b) {
if(a == -1) return b;
// you'll have to write this yourself :)
String as = a+"";
String bs = b+"";
if(as.compareTo(bs) < 0) return a;
return b;
}
static int numKeys(int i) {
if(i < 0) throw new IllegalArgumentException("I don't deal with negative numbers");
if(i == 0) return 1;
//return (i+"").length(); // lame method :}
int len = 0;
while(i > 0) {
len++;
i /= 10;
}
return len;
}
public static void main(String[] args) {
int[] test = {1, 6, 31, 65, 143, 316, 93, 736};
int[] res = radixSort(test);
for(int i : res) System.out.println(i);
}
}
One thing that looks strange:
for (int p = 0; p < n; p++){
while(queue[p].count() != 0) {
q[p] = (queue[p].get());
}
}
Is p supposed to be the index in q, which ranges from 0 to n-1, or in queue, which ranges from 0 to 9? It is unlikely to be both ...
Another:
for (int index = 0; index < n; index++){
// trying to look at one of three digit to sort after.
int v=1;
int digit = (q[index]/v)%10;
v*=10;
queue[digit].put(q[index]);
}
Why are you multiplying v by 10, only to overwrite it by v = 1 in the next iteration? Are you aware than v will always be one, and you will thus look at the same digit in every iteration?
Well I don't think I can help without almost posting the solution (just giving hints is more exhausting and I'm a bit tired, sorry), so I'll just contribute a nice little fuzz test so you can test your solution. How does that sound? :-)
Coming up with a good fuzztester is always a good idea if you're implementing some algorithm. While there's no 100% certainty if that runs with your implementation chances are it'll work (radix sort doesn't have any strange edge cases I'm aware of that only happen extremely rarely)
private static void fuzztest() throws Exception{
Random rnd = new Random();
int testcnt = 0;
final int NR_TESTS = 10000;
// Maximum size of array.
final int MAX_DATA_LENGTH = 1000;
// Maximum value allowed for each integer.
final int MAX_SIZE = Integer.MAX_VALUE;
while(testcnt < NR_TESTS){
int len = rnd.nextInt(MAX_DATA_LENGTH) + 1;
Integer[] array = new Integer[len];
Integer[] radix = new Integer[len];
for(int i = 0; i < len; i++){
array[i] = rnd.nextInt(MAX_SIZE);
radix[i] = new Integer(array[i]);
}
Arrays.sort(array);
sort(radix); // use your own sort function here.
for(int i = 0; i < len; i++){
if(array[i].compareTo(radix[i]) != 0){
throw new Exception("Not sorted!");
}
}
System.out.println(testcnt);
testcnt++;
}
Hi I am trying to take two arrays and turn them into one 2 dimensional array. However, I keep getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test5.sum(test5.java:12)
at test5.main(test5.java:38)
Here is my code:
public class test5 {
int[][] final23;
public int[][] sum(int[] x, int[] y) {
final23 = new int[2][x.length];
for (int i = 0; i < final23[i].length; i++) {
final23[1][i] = x[i];
final23[2][i] = y[i];
}
return final23;
}
public void print() {
for (int i = 0; i < final23[i].length; i++) {
for (int j = 0; j < final23[i].length; j++) {
System.out.print(final23[i][j] + " ");
}
}
}
public static void main(String[] args) {
int l[] = { 7, 7, 3 };
int k[] = { 4, 6, 2 };
test5 X = new test5();
X.sum(k, l);
X.print();
}
}
I am not really sure what the problem is. Sorry if the question is dumb, I am new to coding!
The problem is:
final23 [2][i] = y[i];
Java arrays always start at 0. So final23 only has [0] and [1].
Any array with n elements can go from 0 to n-1.
There is also a second problem with your program. You have this loop in both sum and print methods:
for (int i = 0; i < final23[i].length; i++)
In sum method it should be
for (int i = 0; i < final23[0].length; i++)
And in print method
for (int i = 0; i < final23.length; i++)
Otherwise you'll get ArrayIndexOutOfBoundsException again.
Note that the program works correctly only if both input arrays have the same length. This might be ok for your purposes, but keep that in mind.
Try
for (int i = 0; i < final23[i].length; i++)
{
final23 [0][i] = x[i];
final23 [1][i] = y[i];
}
Remember, all arrays are 0 based, even n-dimensional ones.