I have 3 arrays iX, iY, and iZ with each holding 20 integers.
iX goes up by 5, iY goes up by 3, and iZ is the sum of both.
for (int i=5; i <=iX.length; i+=5)
{
iX[i] = i;
System.out.print (i + "\n");
}
for (int j=3; j <iY.length; j+=3)
{
iY[j] = j;
}
for (int k=0; k < iZ.length; k++)
{
iZ[k] = iX[k]+iY[k];
}
When I run it I get:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at Quiz10RTN.main(Quiz10RTN.java:61)"
Line 61 is : iX[i] = i;
I can't seem to get it to even print out 20 numbers, because it seems to be treating my limit of 20 integers as a range to stop at. Any help would be great, Thanks.
Issue is here
for (int i=5; i <=iX.length; i+=5)
^
There is no index match with iX.length in your array.
index of array start with 0, So if size of array is n, then you only have indexes from 0 to n-1.
You can use following to avoid the exception. But you need to think some other way to archive your goal.
for (int i=5; i <iX.length; i+=5)
Edit: for your comment I was trying to print out "5, 10, 15, 20, 25...etc"
You can try something like following
for (int i=0; i <iX.length; i++) {
iX[i]=(i+1)*5; // now your array become 5,10,15,...
}
You are confusing your array indices with the values you are storing in the arrays.
So, for example, if you want your iX array to contain the 20 integers 5, 10, 15,...100, your first loop should look like:
for (int i=0; i < iX.length; ++i)
{
iX[i] = (i + 1) * 5;
System.out.print (iX[i] + "\n");
}
You aren't using the array indexes properly (they must be incremental). You might also use Arrays.toString(int[]) to print your arrays. I believe you wanted something like
int[] iX = new int[20];
int[] iY = new int[20];
int[] iZ = new int[20];
int valfive = 5; // <-- our five increments.
int valthree = 3; // <-- the three increments.
for (int i = 0; i < iX.length; i++) {
iX[i] = valfive;
iY[i] = valthree;
iZ[i] = valfive + valthree;
valfive += 5; // <-- add 5
valthree += 3; // <-- add 3
}
System.out.println("Multiples of five: " + Arrays.toString(iX));
System.out.println("Multiples of three: " + Arrays.toString(iY));
System.out.println("Sums of fives and threes: " + Arrays.toString(iZ));
Output is (formatted for SO)
Multiples of five: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70,
75, 80, 85, 90, 95, 100]
Multiples of three: [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42,
45, 48, 51, 54, 57, 60]
Sums of fives and threes: [8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96,
104, 112, 120, 128, 136, 144, 152, 160]
Related
import java.util.Random;
public class Practice_assignment {
public static void main(String[] args){
int[] winning_numbers = {0,0,0,0,0,0,0,0,0,0} ;
//The i++ for the first loop is in the second loop. I was trying to ensure it only goes to
the next value of the loop once a unique value has been gotten.
for (int i=0; i<10;){
int max = 99;
int min = 1;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
for (int j=0;j<=i;j++){
if (j<i && winning_numbers[j]==randomNum){
break;
}
else if (j==i && i<10){
winning_numbers[i] = randomNum;
System.out.println(winning_numbers[i]+" ");
i++;
}
}
}
}
}
If I understood correctly what you are trying to achieve, I think you could use something like this:
public class RandomNumbers {
public static void main(String[] args) {
int[] winning_numbers = {0,0,0,0,0,0,0,0,0,0} ;
Random random = new Random();
for(int i = 0; i < winning_numbers.length; i++) {
OptionalInt generatedInt = random.ints(1, 0, 100).findFirst(); // generates a stream of 1 number between 0 and 99 and gets the first (and only) one generated
while (contains(winning_numbers, generatedInt)) {
generatedInt = random.ints(1, 0, 100).findFirst(); // while the generated number is already in the array, generate a new one
}
winning_numbers[i] = generatedInt.getAsInt();
}
System.out.println(Arrays.toString(winning_numbers));
}
// this method will check if the given array already contains the generated int
private static boolean contains(int[] arr, OptionalInt generatedInt) {
return Arrays.stream(arr).anyMatch(number -> generatedInt.getAsInt() == number);
}
}
I ran it a couple of times and here are some outputs I generated with this code:
[52, 54, 21, 62, 47, 13, 94, 36, 82, 25]
[35, 37, 16, 81, 22, 71, 17, 94, 56, 8]
[51, 50, 80, 62, 18, 88, 1, 53, 44, 79]
[16, 95, 18, 66, 31, 4, 1, 55, 52, 26]
[4, 11, 65, 68, 22, 76, 95, 67, 35, 92]
[49, 87, 34, 88, 71, 57, 12, 76, 70, 78]
It appears you want to generate an array of winning_numbers. Here is one ways to do it.
create a helper method to look for duplicate numbers and return true if a duplicate is found.
then iterate over the array checking for the current random number and adding it if unique.
note that min, max, and rand should be initialized outside the loop.
Random rand = new Random();
int[] winning_nummbers = new int[10];
int max = 99;
int min = 1;
for (int i = 0; i < 10;) {
int randomNum = rand.nextInt((max - min) + 1) + min;
// if does not contain a duplicate, then assign
if (!contains(winning_numbers, randomNum)) {
winning_numbers[i++] = randomNum;
}
}
System.out.println(Arrays.toString(winning_numbers));
Prints something like this.
[46, 91, 5, 2, 42, 58, 74, 24, 53, 36]
The helper method.
public static boolean contains(int[] array, int v) {
for (int i = 0; i < array.length; i++) {
if (array[i] == v) {
return true;
}
}
return false;
}
If you want to use streams you can do it like so using a Random instance.
stream values form min to max inclusive.
drop duplicates with distinct
limit(10) limits to 10 values.
put them in an array
int[] winning_numbers = rand.ints(min,max+1)
.distinct()
.limit(10)
.toArray();
I've got List<List<Integer>> with several objects. Each of inner element contains randomly shuffled indexes, for example (it's only a part of indexes).
[1, 4, 5, 2, 0, 3, 6]
[4, 2, 5, 3, 1, 6, 0]
[0, 3, 6, 1, 2, 4, 5]
I've got also an array with some values (int[][] array)
And I need to do a loop for each element to get value from indexes and move forward by 1 index and when I reach last index I need to get value from this index and the first one. After that loop end and sum values. It might look difficult but pictrue will show what I mean. But I dont know how to do this (loop is required for each element, I'm gonna have a massive List of List<Integer> inside and every object gonna have multiple indexes.
I'm reading data from file and write it to array
List<String> result = new ArrayList<>();
int[][] array = new int[][]{};
try (Scanner sc = new Scanner(theFile)) {
while (sc.hasNext()) {
result.add(sc.nextLine());
}
int max = Integer.parseInt(result.get(0).trim());
array = new int[max][max];
for (int i = 1; i < result.size(); i++) {
String[] tmp = result.get(i).trim().split(" ");
for (int j = 0; j < tmp.length; j++) {
array[i - 1][j] = Integer.parseInt(tmp[j]);
array[j][i - 1] = array[i - 1][j];
}
}
List<List<Integer>> collectionWithSubjects = new ArrayList<>();
for (int i = 0; i < 40; i++) {
List<Integer> sub = new ArrayList<>();
sub = sequence(0,51);
Collections.shuffle(sub);
collectionWithSubjects.add(sub);
}
You've done a decent job of explaining the problem. It sounds like you're getting caught up on trying to do everything in a single for loop, rather than breaking down the problem into two pieces.
This is your statement:
I need to do a loop for each element to get value from indexes and move forward by 1 index and when I reach last index I need to get value from this index and the first one.
This can be divided into two pieces:
I need to do a loop for each element to get value from indexes and move forward by 1 index
This is a for loop that iterates from 0 -> size() - 1. If we go from 0 -> size() we get an overflow.
for(int i = 0; i < list.size() - 1; i++) {
int firstCoord = list.get(i);
int secondCoord = list.get(i+1);
//do stuff
}
when I reach last index I need to get value from this index and the first one.
This is getting the last element and the first element.
int firstCoord = list.get(list.size() - 1);
int secondCoord = list.get(0);
Combine both together and you've got the framework for getting the coordinates.
for(int i = 0; i < list.size() - 1; i++) {
int firstCoord = list.get(i);
int secondCoord = list.get(i+1);
//do stuff
}
int firstCoord = list.get(list.size() - 1);
int secondCoord = list.get(0);
//do stuff
I'll leave the actual implementation up to you.
// given array
int[][] array = [[31, 21, 34, 22, 67, 14, 41],
[17, 42, 31, 57, 26, 23, 52],
[5, 92, 52, 52, 31, 22, 62],
[17, 42, 31, 57, 26, 23, 52],
[5, 92, 52, 52, 31, 22, 62],
[31, 21, 34, 22, 67, 14, 41],
[5, 92, 52, 52, 31, 22, 62]];
// given list of lists of randomly-ordered indices
List<List<Integer>> indexList = Arrays.toList([
Arrays.toList([1, 4, 5, 2, 0, 3, 6]),
Arrays.toList([4, 2, 5, 3, 1, 6, 0]),
Arrays.toList([0, 3, 6, 1, 2, 4, 5])
]);
// first, create a place to store the sums corresponding to each random list
List<Integer> sums = new ArrayList<Integer>();
// iterate over each of the lists of random elements
for(List<Integer> randomIndices: indexList){
// create a running sum for this list
int randomSum = 0;
// iterate over each element of the randomized index list
for(int j = 0; j < randomIndices.size(); j++){
// read the current and next index (using modulo to wrap around)
current = randomIndices.get(j);
next = randomIndices.get((j + 1) % randomIndices.size());
// add the relevant index in array to the running sum
randomSum += array[current][next];
}
// add the recorded randomSum to the sums list.
// Its index is the same as the random list we just iterated over
sums.add(randomSum);
}
System.out.println(sums);
You may iterate over the alues of each List<Integer> then look them by pair (use % to go back at the beginning) and use them to index the 2d array
for (List<Integer> l : list) {
int sum = 0;
for (int i = 0; i < l.size(); i++) {
int p1 = l.get(i % l.size());
int p2 = l.get((i + 1) % l.size());
sum += values[p1][p2];
}
System.out.println(sum);
}
With this as initial data
List<List<Integer>> list = List.of(List.of(1, 4, 5, 2, 0, 3, 6), List.of(4, 2, 5, 3, 1, 6, 0));
int[][] values = new int[][]{new int[]{31, 21, 34, 22, 67, 14, 41}, new int[]{17, 42, 31, 57, 26, 23, 52}, new int[]{5, 92, 52, 52, 31, 22, 62},
new int[]{17, 42, 31, 57, 26, 23, 52}, new int[]{5, 92, 52, 52, 31, 22, 62}, new int[]{31, 21, 34, 22, 67, 14, 41}, new int[]{5, 92, 52, 52, 31, 22, 62},};
it'll print
253
262
I am attempting to implement a recursive merge sort algorithm to sort a simple array of integers but I am getting weird values for the indexes in the second half of my array. The first half seems to sort fine which is confusing given that its implemented recursively. The array of random integers is initialized in my main method.
public class MergeSort {
public static int Rounds = 1;
public static void MergeSort(Comparable[] ToSort, Comparable[] temp, int first, int last) {
if(first < last) {
int mid = (first + last) / 2;
//Test Block
System.out.print("For Round " + Rounds + ":\n");
System.out.print("first = " + first + " mid = " + mid + " last = " + last + "\n");
Rounds++;
System.out.print("Array in Round " + (Rounds - 1) + " = {");
for(int i = 0; i <= ToSort.length - 1; i++) {
System.out.print(ToSort[i]);
if(i < ToSort.length - 1)
System.out.print(", ");
else {
System.out.print("}\n\n");
}
}
MergeSort(ToSort, temp, first, mid);
MergeSort(ToSort, temp, mid + 1, last);
Merge(ToSort, temp, first, mid + 1, last);
}
}
public static void Merge(Comparable[] ToSort, Comparable[] temp, int first, int mid, int last) {
int beginHalf1 = first;
int endHalf1 = mid - 1;
int beginHalf2 = mid;
int endHalf2 = last;
int index = first;
int Elements = (last - first) + 1;
while(beginHalf1 <= endHalf1 && beginHalf2 <= endHalf2) {
if(ToSort[beginHalf1].compareTo(ToSort[beginHalf2]) < 0) temp[index++] = ToSort[beginHalf1++];
else temp[index++] = ToSort[beginHalf2++];
}
while(beginHalf1 <= endHalf1) temp[index++] = ToSort[beginHalf1++];
while(beginHalf2 <= endHalf2) temp[index++] = ToSort[beginHalf2++];
for(int i = 0; i < Elements; i++, last--) ToSort[last] = temp[last];
}
}
This produces the following output:
UNSORTED ARRAY = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}
For Round 1:
first = 0 mid = 4 last = 9
Array in Round 1 = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}
For Round 2:
first = 0 mid = 2 last = 4
Array in Round 2 = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}
For Round 3:
first = 0 mid = 1 last = 2
Array in Round 3 = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}
For Round 4:
first = 0 mid = 0 last = 1
Array in Round 4 = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}
For Round 5:
first = 3 mid = 3 last = 4
Array in Round 5 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}
For Round 6:
first = 5 mid = 7 last = 9
Array in Round 6 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}
For Round 7:
first = 5 mid = 6 last = 7
Array in Round 7 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}
For Round 8:
first = 5 mid = 5 last = 6
Array in Round 8 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}
For Round 9:
first = 8 mid = 8 last = 9
Array in Round 9 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}
There is no mistake in your implementation. If you print your array after applying MergeSort method, it is sorted:
Comparable[] a = new Comparable[]{15, 9, 12, 19, 49, 43, 57, 70, 78, 87};
Comparable[] b = new Comparable[a.length];
MergeSort.MergeSort(a, b, 0, a.length - 1);
for (int i = 0; i <= a.length - 1; i++) {
System.out.print(a[i]);
if (i < a.length - 1)
System.out.print(", ");
else {
System.out.print("}\n\n");
}
}
will print 9, 12, 15, 19, 43, 49, 57, 70, 78, 87}
I have created a method which takes generate random numbers with the condition that the next random number doesn't match with the previous one inside the array here's the code
// some code
int k=0;
//some code....
randomgenerator(k); // method call
public void randomgenerator(int j)
{
for(j=0; j<=99; j++){
if(j >= 1){
if (randomset.get(j) == randomset.get(j-1)){
randomset.add(0 + ( j , int)(Math.random() * ((99 - 0) + 1)));
}
else{
randomset.add(0 + (int)(Math.random() * ((99 - 0) + 1)));
}
}
}
}
The error I get is java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
Because initially randomset is empty therefore its size is 0 and returns exception at index 1. The best way to add randomset.add(0 + (int)(Math.random() * ((99 - 0) + 1))); if j < 1 (not >=1).
Correct code:
public void randomgenerator(int j)
{
for(j=0; j<=99; j++){
if(j >= 1){
if (randomset.get(j) == randomset.get(j-1)){
randomset.add(0 + ( j , int)(Math.random() * ((99 - 0) + 1)));
}
else{
randomset.add(0 + (int)(Math.random() * ((99 - 0) + 1)));
}
}
else {
randomset.add(0 + (int)(Math.random() * ((99 - 0) + 1)));
}
}
}
Use
for(j=0; j<randomset.size(); j++){
Don't use the same variable as your input parameter and your loop variable.
public void randomgenerator(int length)
{
for (int j = 0; j < length; j ++) ...
I'm not sure I follow the rest of the code, but that's a start.
You can't reference an element of ArrayList whose index is not in bounds [0, size() - 1]. Creating ArrayList via ArrayList() creates a list of size 0. To add elements to this array you must call one of the methods that adds an element, e.g. add(). Your first call is to get(), but the list has size 0, so even get(0) will cause an IndexOutOfBoundsException.
What to do depends on the expected contents of the list. In your case, I would recommend writing a helper function that generates a random number in range excluding specified number. You could use that function in a simple loop to generate the whole list, passing previous element to mentioned helper function.
Example:
public static int randomInRange(int a, int b) {
return (int)(Math.random() * (b - a + 1));
}
public static int randomInRangeExcluding(int a, int b, int excluding) {
int result = (int)(Math.random() * (b - a));
if (result == excluding) {
result++;
}
return result;
}
public static List<Integer> generateRandomList(int size) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int j = 0; j <= size; j++) {
if (j > 0) {
result.add(randomInRangeExcluding(0, size - 1, result.get(j - 1)));
} else {
result.add(randomInRange(0, size - 1));
}
}
return result;
}
and get the value using:
generateRandomList(100);
Calling this results in a list of random integers having no two consecutive elements equal:
[27, 34, 53, 92, 56, 93, 21, 22, 45, 95, 48, 25, 18, 26, 54, 1, 82, 26, 5, 62, 84, 23, 8, 84, 25, 0, 36, 37, 54, 95, 4, 26, 65, 53, 81, 16, 47, 56, 73, 46, 60, 50, 37, 89, 61, 84, 23, 79, 47, 87, 68, 49, 15, 17, 55, 71, 17, 55, 71, 51, 67, 33, 80, 47, 81, 24, 10, 41, 76, 60, 12, 17, 96, 43, 57, 55, 41, 56, 21, 85, 98, 40, 9, 39, 53, 28, 93, 70, 89, 80, 40, 41, 30, 81, 33, 53, 73, 28, 38, 87, 29]
What is with you're function? You receive a parameter named j and then you reassigned it?
randomset.get(j) == randomset.get(j-1) <- at this line you have a java.lang.IndexOutOfBoundsException because you call for the value from position 1 but in you're list you have only a value on position 0; so an error is thrown
and, what is this ? ((99 - 0) + 1)) ,you could white 100, it is easy, and more readable
by the way, at this line you have an error, randomset.add(0 + ( j , (int)(Math.random() * ((99 - 0) + 1)));
You should write a cleaner code.
I've prepared a solution for you: a function which generates a List with random numbers and respects you condition: two consecutive numbers are not the same.
You must call this method generateRandomList with the number of elements you want to generate.
public static final Integer MAX_RANDOM_NUMBER = 100;
public static List<Integer> generateRandomList(int randomNumbers) {
return generateRandomList(randomNumbers, -1);
}
private static List<Integer> generateRandomList(final int randomNumbers, final int previousNumber) {
if (randomNumbers == 1) {
return new ArrayList<Integer>() {
{
add(getNextNumber(previousNumber));
}
};
} else {
return new ArrayList<Integer>() {
{
int value = getNextNumber(previousNumber);
add(value);
addAll(generateRandomList(randomNumbers - 1, value));
}
};
}
}
private static int getNextNumber(int previousNumber) {
boolean generateNewValue = true;
int currentValue = 0;
while (generateNewValue) {
currentValue = (int) (Math.random() * MAX_RANDOM_NUMBER);
generateNewValue = currentValue == previousNumber;
}
return currentValue;
}
I'm trying to make a 5 by 10 table using a double array. The first box should be blank, then the rest numbered 2-50.
I have this so far but it is not working.
int array[][] = new int[5][10];
for(int row=1; row<5;row++){
for(int col=1;col<10;col++)
array[row][col] = row*col;}
System.out.println(array);
row * col cannot give you consecutive numbers from 2 to 50. And in your code, you are not just leaving the first box, but you are leaving out first row and first column completely.
You should run the loop normally from 0 to max. And for [0][0], don't print anything.
Also, for printing from 2 to 50, just have a count variable which starts with 2, and after printing it, increment it by 1.
Here's the modified code: -
int array[][] = new int[5][10];
int count = 2;
for(int row=0; row<5;row++){
for(int col=0;col<10;col++) {
if (row == 0 && col == 0) {
continue;
}
array[row][col] = count++;
}
}
for (int[] inner: array) {
System.out.println(Arrays.toString(inner));
}
OUTPUT : -
[0, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
NOTE: -
Since you want your first box to be blank, you can't use Arrays.toString here. You would have to use one more loop, and print your array in simple ways. And when your indices are [0][0], just sysout("");
The first box can't be blank... it could be zero, is that what you want?
Changes:
Use 0 indices, not 1 indices
You have to print the contents of the array manually, see where I print a comma below
row * col isn't the correct value. use row * 10 + col + 1
Try this:
int array[][] = new int[5][10];
for(int row=0; row<5;row++){
for(int col=0;col<10;col++) {
array[row][col] = row * 10 + col + 1;
if (array[row][col] < 2) {
System.out.print(" ");
} else {
System.out.print(array[row][col]);
}
if (col < 9) System.out.print(",");
}
System.out.println();
}
Output:
,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20
21,22,23,24,25,26,27,28,29,30
31,32,33,34,35,36,37,38,39,40
41,42,43,44,45,46,47,48,49,50