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;
}
}
Related
I'm supposed to modify code that I've written for an assignment:
public class ToweringStrings2 {
public static final int H = 2; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print("+");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("#");
}
System.out.println();
}
}
so that it prints sequential numbers starting at 1, instead of +s. Currently, it prints:
This is what the new code is supposed to print:
and so on.
For some reason I'm just really stuck and can't figure it out.
You can create an extra variable to print and increment
Like that:
public class ToweringStrings2 {
public static final int H = 10; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
int count = 1;
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print(count++ + " ");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("# ");
}
System.out.println();
}
}
Step 1 - make it print a variable rather than a hard-coded string. Instead of System.out.print("+"), System.out.print(counter).
For this to work you need to have declared counter somewhere in the same scope as the statement: int counter = 0.
Run this. You'll see it print "0" where it used to print "+".
Step 2 - Now you need to make counter increase by one every time it prints.
Find the right place to add:
counter = counter + 1;
Run it and see it work.
Further notes
A more concise alternative to var = var + 1 is var++.
You can even do this at the same time as you use the value of a variable:
System.out.println(var++);
This can be used to express some algorithms very concisely -- but it can be confusing for beginners, so feel free to not use this technique until you're comfortable with the basics.
I'm a total beginner of java.
I have a homework to write a complete program that calculates the factorial of 50 using array.
I can't use any method like biginteger.
I can only use array because my professor wants us to understand the logic behind, I guess...
However, he didn't really teach us the detail of array, so I'm really confused here.
Basically, I'm trying to divide the big number and put it into array slot. So if the first array gets 235, I can divide it and extract the number and put it into one array slot. Then, put the remain next array slot. And repeat the process until I get the result (which is factorial of 50, and it's a huge number..)
I tried to understand what's the logic behind, but I really can't figure it out.. So far I have this on my mind.
import java.util.Scanner;
class Factorial
{
public static void main(String[] args)
{
int n;
Scanner kb = new Scanner(System.in);
System.out.println("Enter n");
n = kb.nextInt();
System.out.println(n +"! = " + fact(n));
}
public static int fact(int n)
{
int product = 1;
int[] a = new int[100];
a[0] = 1;
for (int j = 2; j < a.length; j++)
{
for(; n >= 1; n--)
{
product = product * n;
a[j-1] = n;
a[j] = a[j]/10;
a[j+1] = a[j]%10;
}
}
return product;
}
}
But it doesn't show me the factorial of 50.
it shows me 0 as the result, so apparently, it's not working.
I'm trying to use one method (fact()), but I'm not sure that's the right way to do.
My professor mentioned about using operator / and % to assign the number to the next slot of array repeatedly.
So I'm trying to use that for this homework.
Does anyone have an idea for this homework?
Please help me!
And sorry for the confusing instruction... I'm confused also, so please forgive me.
FYI: factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000
Try this.
static int[] fact(int n) {
int[] r = new int[100];
r[0] = 1;
for (int i = 1; i <= n; ++i) {
int carry = 0;
for (int j = 0; j < r.length; ++j) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
and
int[] result = fact(50);
int i = result.length - 1;
while (i > 0 && result[i] == 0)
--i;
while (i >= 0)
System.out.print(result[i--]);
System.out.println();
// -> 30414093201713378043612608166064768844377641568960512000000000000
Her's my result:
50 factorial - 30414093201713378043612608166064768844377641568960512000000000000
And here's the code. I hard coded an array of 100 digits. When printing, I skip the leading zeroes.
public class FactorialArray {
public static void main(String[] args) {
int n = 50;
System.out.print(n + " factorial - ");
int[] result = factorial(n);
boolean firstDigit = false;
for (int digit : result) {
if (digit > 0) {
firstDigit = true;
}
if (firstDigit) {
System.out.print(digit);
}
}
System.out.println();
}
private static int[] factorial(int n) {
int[] r = new int[100];
r[r.length - 1] = 1;
for (int i = 1; i <= n; i++) {
int carry = 0;
for (int j = r.length - 1; j >= 0; j--) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
}
How about:
public static BigInteger p(int numOfAllPerson) {
if (numOfAllPerson < 0) {
throw new IllegalArgumentException();
}
if (numOfAllPerson == 0) {
return BigInteger.ONE;
}
BigInteger retBigInt = BigInteger.ONE;
for (; numOfAllPerson > 0; numOfAllPerson--) {
retBigInt = retBigInt.multiply(BigInteger.valueOf(numOfAllPerson));
}
return retBigInt;
}
Please recall basic level of math how multiplication works?
2344
X 34
= (2344*4)*10^0 + (2344*3)*10^1 = ans
2344
X334
= (2344*4)*10^0 + (2344*3)*10^1 + (2344*3)*10^2= ans
So for m digits X n digits you need n list of string array.
Each time you multiply each digits with m. and store it.
After each step you will append 0,1,2,n-1 trailing zero(s) to that string.
Finally, sum all of n listed string. You know how to do that.
So up to this you know m*n
now it is very easy to compute 1*..........*49*50.
how about:
int[] arrayOfFifty = new int[50];
//populate the array with 1 to 50
for(int i = 1; i < 51; i++){
arrayOfFifty[i-1] = i;
}
//perform the factorial
long result = 1;
for(int i = 0; i < arrayOfFifty.length; i++){
result = arrayOfFifty[i] * result;
}
Did not test this. No idea how big the number is and if it would cause error due to the size of the number.
Updated. arrays use ".length" to measure the size.
I now updated result to long data type and it returns the following - which is obviously incorrect. This is a massive number and I'm not sure what your professor is trying to get at.
-3258495067890909184
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.
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++;
}