Trying to make a double array, numbered 2 to 50 - java

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

Related

Move array element to index 0 and move elements left to right [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So the main idea is, the last number came on roulette machine is going to be on Index[0] and the element at index "whatNumberCame" has to become the number before
public class Main {
public static void main(String[] args) {
int[] rouletteNumbers = {0, 1, 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};
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number : ");
int whatNumberCame = scanner.nextInt();
int collisionIndex;
for(int i = 0; i < rouletteNumbers.length ; i++){
if(rouletteNumbers[i] == whatNumberCame){
System.out.println("COLLISION AT " + rouletteNumbers[i]);
collisionIndex = rouletteNumbers[i];
System.out.println(collisionIndex);
for (int j = collisionIndex + 1; j <= 0 ; j--){
rouletteNumbers[j] = rouletteNumbers[j - 1];
System.out.print(rouletteNumbers);
}
}
}
}
}
for example if i enter 10 array should become :
{10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 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}
You can tweak your code like this to make it works:
public static void main (String [] args) {
int[] rouletteNumbers = {0, 1, 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};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number : ");
int whatNumberCame = scanner.nextInt();
for(int i = 0; i < rouletteNumbers.length ; i++){
if(rouletteNumbers[i] == whatNumberCame){
for (int j = i; j > 0; j--){
rouletteNumbers[j] = rouletteNumbers[j - 1];
}
rouletteNumbers[0] = whatNumberCame;
break;
}
}
System.out.println(Arrays.toString(rouletteNumbers));
}
In your loop, you used j <= 0 which is always false, so you inner loop doesn't execute at all.
And when you find the position of the number, you can break from the loop using break.
Here is a method that does the similar thing except it allows you to insert a value at whatever array index you like. With each value inserted into the array, the array will grow in length as indicated within your post example.
Usage:
To add a value to the array at index 0 (the beginning of the Array):
rouletteNumbers = insertIntoArray(rouletteNumbers, whatNumberCame, 0);
To add a value to the very end of the array:
rouletteNumbers = insertIntoArray(rouletteNumbers, whatNumberCame, rouletteNumbers.length);
To insert a value into any index within the array (say index 4):
rouletteNumbers = insertIntoArray(rouletteNumbers, whatNumberCame, 4);
The method code:
public static int[] insertIntoArray(int[] array, int valueToInsert, int insertIntoIndex) {
/* If the inertIntoIndex value is greater than the supplied Array Length
then the inertIntoIndex value is changed to the supplied Array Length.
This ensures that the valueToInsert will be place at the end of the
Array. */
if (insertIntoIndex > array.length) {
insertIntoIndex = array.length;
}
int[] tmp = new int[array.length + 1];
int idxCounter = 0;
int i = 0;
for (; i < array.length; i++) {
if (i == insertIntoIndex) {
tmp[idxCounter] = valueToInsert;
idxCounter++;
}
tmp[idxCounter] = array[i];
idxCounter++;
}
/* when at this point in code, the condition below
indicates that the desired insert index location
would be at the very end of the array. */
if (i == idxCounter) {
tmp[idxCounter] = valueToInsert;
}
return tmp;
}

How to seperate even and odd numbers in the same array?

How would I separate even and odd integers in an array with order preserved?
Modifications must be in place and the return is a void, and can only use built in methods.
An example would be:
{4, 5, 8, 16, 45, 12, 67, 13} -> {4, 8, 16, 12, 5, 45, 67, 13}
Explanation
You can easily solve this with one iteration, remembering the index of the current border and swapping elements.
So for your example, the process will be:
{ 4, 5, 8, 16, 45, 12, 67, 13 } // swap 4 with 4
^
{ 4, 5, 8, 16, 45, 12, 67, 13 }
^
{ 4, 8, 5, 16, 45, 12, 67, 13 } // swap 5 with 8
^
{ 4, 8, 16, 5, 45, 12, 67, 13 } // swap 5 with 16
^
{ 4, 8, 16, 12, 45, 5, 67, 13 } // swap 5 with 12
^
Where the ^ shows the current border index, which is always one ahead of the even values, pointing at the index where you want to swap the next even value to.
First draft
Here is the code for that:
int borderIndex = 0;
for (int i = 0; i < values.length; i++) {
int value = values[i];
if (value % 2 == 0) {
// swap
values[i] = values[borderIndex];
values[borderIndex] = value;
borderIndex++;
}
}
Preserving order
Now, this solution already preserves the order of the even numbers out of the box. But if you pay close attention you see that it does not preserve order of the odd values. It goes wrong as soon as you have multiple odd values after each other before an even value, like
..., 5, 45, 12, ...
because it will then swap 5 with 12 resulting in 12, 45, 5 instead of 12, 5, 45.
Even worse when there are multiple odd values:
..., 5, 7, 9, 11, 12, ...
resulting in 12, 7, 9, 11, 5.
In order to fix this, we have to not just swap 5 with the even value 12 but actually swap all the way back to 5. So:
swap 12 with 11
swap 12 with 9
swap 12 with 7
swap 12 with 5
basically shifting down 12 from right to left, until it stands right in front of 5.
We can do so easily with a simple loop that moves from 12 (at i) to 5 (at borderIndex):
int borderIndex = 0;
for (int i = 0; i < values.length; i++) {
int value = values[i];
if (value % 2 == 0) {
// swap from i to borderIndex
for (int j = i; j > borderIndex; j--) {
values[j] = values[j - 1];
values[j - 1] = value;
}
borderIndex++;
}
}
You can also do it like this. In this case your sorting them on their inherent nature as opposed to their relationship to each other.
Integer [] arr = {4, 5, 8, 16, 45, 12, 67, 13};
Arrays.sort(arr, Comparator.comparing(a->a % 2));
System.out.println(Arrays.toString(arr));
prints
[4, 8, 16, 12, 5, 45, 67, 13]

How to get range to first index when the loop reach end?

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

Unable to think of a way to shift array

I am stuck and can't think of a way to properly shift an array by __ units. I am trying to create an array of 30 items (numbers 1-30) which can then be shifted to the right by the number the user inputs. This would mean that the first few numbers in the array would take the index's at the end of the array, and the rest of the numbers would be shifted to the left. (Ex, if shift = 3, numbers 1,2,3 would take the index of 27,28,29, and the rest of the numbers 4-30 would shift left making index 0 =4, index 1=5, index 2=6....
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("\nEnter the shift/rotation:");
int shiftNum = input.nextInt();
int [] numArray = new int [30];
for(int i = 0; i < 30; i++){
numArray [i] = i+1;
System.out.print(numArray[i]+" ");
}
}
}
This is the code I have so far, any suggestions to how I can do this? I have tried to make a separate for loop like
numArray [i-shiftNum] = numArray[i];
But when doing this, the index of 0-shiftNum would be negative and would not work. This is the context of the problem:
Create a program that will create an array of 30 items. Then it will rotate the array by a number selected by the user.
In order to shift the numbers in the array, the following for loop works for shifting the values within the array.
// prerequisite: array is already filled with values
for(int i = 0; i < numArray.length; i++) {
arr[i] += shiftNum;
if (numArray[i] > 30) {
numArray[i] -= 30;
} else if (numArray[i] <= 0) {
numArray[i] += 30;
}
}
According to you code, the array created will contain value from 1 - 30 including 1 and 30. If you want your code to contain values from 0 - 29 instead, change numArray[i] > 30 to numArray[i] >= 30 and change numArray[i] <= 0 to numArray[i] < 0.
Use Java's convenience methods. Most people still want to write for loops. Basically, you need to save off the elements you are overwriting with the shift. Then place those saved ones back in the array. System.arraycopy is nice in that it takes care of some nasty parts of moving elements in an array.
void shift(int shiftBy, int... array) {
int[] holdInts = Arrays.copyOf(array, shiftBy);
System.arraycopy(array, shiftBy, array, 0, array.length - shiftBy);
System.arraycopy(holdInts, 0, array, array.length - shiftBy, holdInts.length);
}
Here is quick fix for you. Please check following code.
Input :
Enter the shift/rotation: 4
Output :
Rotate given array [1, 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]
After Rotate [27, 28, 29, 30, 1, 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]
public static void main(String[] args) {
RotationDemo rd = new RotationDemo();
int[] input = { 1, 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};
int k = 0;
Scanner scan = new Scanner (System.in);
try{
System.out.println("\nEnter the shift/rotation:");
int shiftNum = scan.nextInt();
if(shiftNum < 30) {
k = shiftNum;
System.out.println("Rotate given array " + Arrays.toString(input));
int[] rotatedArray = rd.rotateRight(input, input.length, k);
System.out.println("After Rotate " +
Arrays.toString(rotatedArray));
} else {
System.out.println("Shift number should be less than 30");
}
} catch(Exception ex){
} finally {
scan.close();
}
}
public int[] rotateRight(int[] input, int length, int numOfRotations) {
for (int i = 0; i < numOfRotations; i++) {
int temp = input[length - 1];
for (int j = length - 1; j > 0; j--) {
input[j] = input[j - 1];
}
input[0] = temp;
}
return input;
}
Hope this example works.

Array counting by 5's and 3's then adding the arrays

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]

Categories