Java Array exercise - java

I have this array exercise. I want to understand how things work, if someone can
we have the object array of type int called index with 4 elements
we have the object array of type String called islands with 4 elements
I don't understand how things are passing to each other, I need a good explanation.
class Dog {
public static void main(String [] args) {
int [] index = new int[4];
index[0] = 1;
index[1] = 3;
index[2] = 0;
index[3] = 2;
String [] islands = new String[4];
islands[0] = "Bermuda";
islands[1] = "Fiji";
islands[2] = "Azores";
islands[3] = "Cozumel";
int y = 0;
int ref;
while (y < 4) {
ref = index[y];
System.out.print("island = ");
System.out.println(islands[ref]);
y ++;
}
}

Take a pen and paper and make a table like this, and go through the iterations:
y ref islands[ret]
--- --- ------------
0 1 Fiji
1 3 Cozumel
2 0 Bermuda
3 2 Azores

Well, you've added index in the array named index then accessing the same value in while loop
int y=0;
ref = index[y]; // now ref = 1
islands[ref] // means islands[1] which returns the value `Fiji` that is stored in 1st position

First, you make an array that holds ints, the array has length 4 (4 variables can be in it):
int [] intArray = new int[4];
Your array is called index which may be confusing for the explanation. The index of an array is which "position" you are referring to and is between 0 and the length-1 (inclusive). You can use it in two ways:
int myInt = intArray[0]; //get whatever is at index 0 and store it in myInt
intArray[0] = 4; //store the number 4 at index 0
The following code does nothing more than get a number from the first array and use it to access a variable in the second array.
ref = index[y];
System.out.println(islands[ref])

To make it understand, take a paper and pen and jot down the arrays in table form and iterate through the loop to understand. (back in school days, our teacher(s) called it a dry run)
First we represent the data
Iteration y ref ( `ref = index[y]`) islands
1 0 1 Fiji
2 1 3 Cozumel
3 2 0 Bermuda
4 3 2 Azores
So you can go through the iterations
Iteration 1
y=0
ref = index[y], i.e. index[0] i.e 1
System.out.print("island = "); prints island =
System.out.println(islands[ref]); islands[ref] i.e islands[1] i.e Fiji
hence for iteration 1 output will be
island = Fiji

Related

Matrix filler block

In my class we have to make a matrix filler program but I have gotten very confused on how to do so by using the user input and I don't know how to at all. Iv'e tried to start coding but can't get past step 1.
package question4;
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class MatrixFiller {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Size of Matrix: ");
Random ranGen = new Random();
int matrixSize = input.nextInt();
int a = matrixSize * matrixSize;
input.close();
int[][] myMatrix = new int[matrixSize][matrixSize];
for (int x = 0; x < matrixSize; x++) {
for (int y = 0; y < matrixSize; y++) {
myMatrix[x][y] = ranGen.nextInt(a);
System.out.print(Integer.toString(myMatrix[x][y]) + " ");
}
System.out.print("\n");
}
}
}
so i fixed the code and was wandering how can i add the zero inferno of the number like 1 and 2 so it comes out 01 and 02, do i need an if loop so that it only checks numbers less then 10?
By your example code it seems that what you are missing is basic syntax knowledge. Let me refresh your memory on arrays at the most basic level with simple language.
Arrays are like a multi-dimensional list of variables of some type.
You choose the type of variables when you declare the array.
The amount of variables which an array can hold is a constant number (the length of the array) which is defined when is is initialized.
An array can also have more than one dimensions. You set the number of dimensions when you declare the array. Think of a 1 dimensional array as a list, 2 dimensions would turn the list into a matrix. In this case, you need to set the length of each dimension (when you initialize). So, if the length of the 2 dimensions is the same you get a square, otherwise you get a rectangle.
Here is some code to go along with this:
int[] myArray;
Here I declared a 1 dimensional array which holds ints.
myArray = new int[6];
Here I initialized my array and set the length of the dimension to 6.
int[] myArray2 = new int[7];
I can also do them on the same line.
long[][] myMatrix = new long[3][2];
Here I declared a 2 dimensional array which holds longs. The lengths of the dimensions are 3 and 2, so it looks like this when you imagine it:
_ _
_ _
_ _
Now we wan to access the array at a certain position. This is done by specifying the array name and the position in each dimension you want to access, like this:
myMatrix[0][1] = 63;
Remember! The position start counting from 0, so a 2 by 3 array would have the first dimension values 0 and 1; and the second dimension values 0, 1 and 2.
Now let's iterate over an array and put the number 6 in all of its slots:
int[][] exmaple = new int[3][3]; // 2 dim. array of ints with size 3 by 3.
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
example[x][y] = 6;
}
}
Not sure if you need this, but I will mention a few additional notes:
You can initialize an array with values directly and then you don't need to specify the dimensions' lengths:
int[][] array = new int[][] {{1 ,2}, {5, 65}}; // 2 by 2
You can get the length of a dimension of an array by the syntax
array.length;
array[0].length;
array[1].length;
// etc.
These return an int which you can use as a bound when looping:
for (int i = 0; i < array.length; i++) {
// ...
}

How to insert a number into an array in java

Ok I am trying to do the following using an array.
Say I have one array
1 4 3 7 8
and at index 1 I want to place a 2 to get the following
1 2 4 3 7 8
How do I do this I think I have to make one array to keep everything before the index, one array to keep everything after the index.
And the add one more element to the array with everything before the index. The create a new longer array with everything before the index and everything after the index.
But I cannot seem to do it. This be what I tried.
//this program will test out how to replace an array with more stuff
public class Raton
{
public static void main(String[] args)
{
int[] gato={1,4,3,7,8};
int[] perro = new int[gato.length+1];
int[] biggie = new int[gato.length];
int index=2; //store item index 2
System.out.println("the contents of gato are ");
for(int i=0; i<gato.length;i++)
{
System.out.println(gato[i]);
}
for(int i=0;i<gato.length;i++)
{
if(i<index)
{
perro[i]=gato[i];
}
else
{
int red=0;
biggie[red]=gato[i];
red++;
}
}
//put two in the new place
for(int i=0;i<perro.length;i++)
{
System.out.println(" \n the contents of peero are " + perro[i]);
}
for(int i=0; i<biggie.length;i++)
{
System.out.println("\nthe contents of biggie are " + biggie[i]);
}
}
}
First you need to get both the new number and new index.
int newNumber = 2;
int newIndex = 1;
Create the new array with size+1 of old array
int[] gato = {1,4,3,7,8}; //old array
int[] perro = new int[gato.length+1]; //new array
Then keep track of of two counters. j for old array and i for new array.
int j = 0;
for(int i = 0; i<perro.length; i++){
if(i == newIndex){
perro[i] = newNumber;
}
else{
perro[i] = gato[j];
j++;
}
}
Here's a test run. This solution is assuming you have a constraint where you can only use arrays (not ArrayList or any other prebuilt classes in Java)
Use an ArrayList<Integer> instead of arrays, they allow easy insertion of new elements, and arraylists allow that at specific indices too.
int[] gato={1,4,3,7,8};
List<Integer> list = new ArrayList<>(Arrays.asList(gato));
list.add(1, 2);
I haven't tested this code, but something similar should do the trick.
public class Raton {
public static void main(String[] args) {
int[] originalArray = {1,4,3,7,8};
int[] modifiedArray = new int[originalArray.length + 1];
int index = 2;
for(int i = 0; i < (originalArray.length + 1); i++) {
if(i==1) {
modifiedArray[i] = index;
}
else if(i < 1){
modifiedArray[i] = originalArray[i];
}
else {
modifiedArray[i] = originalArray[i-1];
}
}
}
}
Try to look at the "before" and "after" arrays:
Before
┌─┬─┬─┬─┬─┐
│1│4│3│7│8│
└─┴─┴─┴─┴─┘
0 1 2 3 4
After
┌─┬─┬─┬─┬─┬─┐
│1│2│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
One thing you already noticed is that you need a target array that is 1 bigger than the original array. That's correct.
But you have several problems in your program.
You copy all the parts that are before the index to perro. Since perro is your target array (the one bigger than the original), you have to make sure that everything gets copied to it. But instead, you only copy the parts that are before the index.
You want to place the 2 at index 1. But you wrote index=2. This means that both the 1 and 4 will be copied to perro consecutively. Your perro will look like this:
┌─┬─┬─┬─┬─┬─┐
│1│4│0│0│0│0│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
and this means that you didn't put the 2 in the place you wanted it. That place is taken by the 4.
You try to copy the numbers after the index to biggie. But you are doing this using red. And in each iteration of the loop, you set red=0 again. So the only place in biggie that will change is 0, and that place will get all the numbers, and the last one will stay. So your biggie will be:
┌─┬─┬─┬─┬─┐
│8│0│0│0│0│
└─┴─┴─┴─┴─┘
0 1 2 3 4
You don't put the 2 anywhere!
You don't copy things from biggie to perro so you don`t get all the parts of the array together.
So let's look at our before and after arrays again:
Before
┌─┬─┬─┬─┬─┐
│1│4│3│7│8│
└─┴─┴─┴─┴─┘
0 1 2 3 4
After
┌─┬─┬─┬─┬─┬─┐
│1│2│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
So first, we have to remember that the index we want to change is 1, not 2. Now look at the after array. You notice that there are three types of numbers:
Ones that stayed in the same place (the 1)
Ones that were added (the 2)
Ones that moved one place to the right (4,3,7,8)
How do we know which of the original numbers "stay" and which ones "move"? It's easy. The ones whose index is less than index (remember, it's 1!), that is, the one at index 0, stays.
All the others (including the one that is in the index itself!) have to move to a new place. The place is their old index + 1.
So your program should look like this:
Prepare an array whose size is one bigger than the original (like your perro).
Loop on all the indexes in the old array. Suppose the loop variable is i.
If i is less than the index, copy the number at index i from the original array to the new array at the same index, that is, at i.
For all other cases, copy the number at index i from the original array to the new array, but moved by one place. That is, i+1. There is no need for another variable or a ++ here.
When you finish that loop, your array will look like:
┌─┬─┬─┬─┬─┬─┐
│1│0│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
Now don't forget to put your actual 2 there, at the index index!
Note: please give your variables meaningful names. I'm not sure, perhaps the names are meaningful in your native language, but biggie and red seem to be words in English, but they don't help us understand what these variables do. Try to use variable names that describe the function of the variable. Like original, target, temporary, nextIndex etc.
I think this is a clean and simple solution :
public static void main(String[] args) {
int[] gato = {1, 4, 3, 7, 8};
int index = 2; //store item index 2
System.out.println("the contents of gato are ");
for (int i = 0; i < gato.length; i++) {
System.out.println(gato[i]);
}
gato = Arrays.copyOf(gato, gato.length + 1);
for (int i = gato.length - 1; i > index; i--) {
gato[i] = gato[i - 1];
}
//put the element in the array
gato[index] = 2;
for (int i = 0; i < gato.length; i++) {
System.out.println(gato[i]);
}
}

null last element in 2D array

I have the following 2D array:
private static Object[][] myClass = new Object[6][5];
and I am looking to null the last element in the array (myClass[lastIndex][all indexes] = null) using the following code:
for(int y = 0;y < 5;y++) {
myClass[5][y] = null;
}
However it seems to be deleting the last two elements in the array, what is causing this?
EDIT:
array print out before delete:
one
1
1
1
1.0
two
2
2
2
2.0
three
3
3
3
3.0
four
4
4
4
4.0
five
5
5
5
5.0
six
6
6
6
6.0
After "deleteing" element one(In practise I want to "delete" element one by copying all the elements down one index and setting the last to null):
two
2
2
2
2.0
three
3
3
3
3.0
four
4
4
4
4.0
five
5
5
5
5.0
null
null
null
null
null
null
null
null
null
null
My full delete code:
public void deleteStudent(int studentChoice) {
for(int i = studentChoice;i < myClass.length - 1;i++) {
myClass[i] = myClass[i+1];
}
myClassCount = myClassCount - 1;
for(int y = 0;y < 5;y++) {
myClass[5][y] = null;
}
}
int studentChoice is the index of the array.
myClassCount is a variable that's incremented/de-incremented as elements are added/deletted
This is a subtle problem:
When you copy down, the references are copied, not the values in the array so that in the last step, because you don't overwrite myClass[5], myClass[5] == myClass[4] so that any changes you then make to any element in myClass[5] are replicated in myClass[4] as they are the same object! Therefore when you null each object in myClass[5], you are nulling everything in myClass[4] aswell. This can be avoided by copying the individual values down, rather than just the arrays.
You can copy the values down like this:
for(int i = studentChoice;i < myClass.length - 1;i++) {
for(int y = 0;y < 5;y ++){
myClass[i][y] = myClass[i+1][y];
}
}
As a side note, this behavior can be demonstrated by the following:
Object[] array1 = {1};
Object[] array2 = array1;
array2[0] = 2;
System.out.println(array1[0]);//Prints 2

How do I generate random numbers in an array that add up to a defined total?

I need to randomly generate an array with 7 slots in Java. All these slots must have a value of at LEAST 1, but combined, have a total value of another defined number. They also all need to be an int value, no 1.5 or 0.9816465684646 numbers.
Example:
int a=10;
int[] ar = new int[7]
ar[0] = 1
ar[1] = 1
ar[2] = 2
ar[3] = 2
ar[4] = 1
ar[5] = 2
ar[6] = 1
I want it to generate something like that, but if int a=15, all the numbers would total 15 in any order
The standard way to generate N random numbers that add to a given sum is to think of your sum as a number line, generate N-1 random points on the line, sort them, then use the differences between the points as your final values. To get the minimum 1, start by subtracting N from your sum, run the algorithm given, then add 1 back to each segment.
public class Rand {
public static void main(String[] args) {
int count = 8;
int sum = 100;
java.util.Random g = new java.util.Random();
int vals[] = new int[count];
sum -= count;
for (int i = 0; i < count-1; ++i) {
vals[i] = g.nextInt(sum);
}
vals[count-1] = sum;
java.util.Arrays.sort(vals);
for (int i = count-1; i > 0; --i) {
vals[i] -= vals[i-1];
}
for (int i = 0; i < count; ++i) { ++vals[i]; }
for (int i = 0; i < count; ++i) {
System.out.printf("%4d", vals[i]);
}
System.out.printf("\n");
}
}
A good way to achieve uniformity is, for example, to fill up a = 15 units into an 8 element array:
Put 1 in each element in the array as this is your requirement, you have now 7 values left to distribute
Roll a random number between 0 and the max index of the array, and add 1 to that element, and subtract 1 from 7. Do this until 7 goes down to zero.
In this way, you'll meet your minimum conditions by having each element have minimum value 1. Then you distribute the remaining totals in a completely random way.
Adding on to what #Kon said, you could use two random numbers rather than one for more randomness. That is:
Fill every element in the array with the value 1
valuesToDistribute = a - array.length-1
randomIndex = Roll a number between 0 and array.length-1
randomValue = Roll a number between 1 and valuesToDistribute
Add to randomIndex the value randomValue
Subtract randomValue from valuesToDistribute
Repeat until valuesToDistribute = 0
My java is horrible, so I'm not providing the actual code here, as it would probably be wrong. I've done this exact thing in SQL before though, so I know it works...
Let Y be the Total value you want the elements to add up to
Begin a loop with variable Z going from 1 to X where X is the number elements in your array (here called AR)
In the loop, set AR(Z) to a random number between 1 and Y-X+Z
Subtract the new value from Y, so Y = Y - AR(Z)
End loop : back to step 2, advancing Z by 1

Pseudo code needed if possible?

I was wondering if I could have some pseudo code for working out the following
i need to loop through a 2d array(the method i am working on takes an int). It starts at the position of the value passed in and then goes down until it hits the same value on the left hand side. As its doing this every int in the 2d array is added to a local variable.
Now we are at position (x,x) i guess? Then from here i need to loop across to the right adding all variables to the same previous local var and then return that number
The 2d array for illustration purposed looks something like this for example
1 2 3 4
2 3 4 5
1 2 3 4
3 2 1 4
So if i were to pass in 2 we would start at the number 3 top line i guess, we would loop down until position 3,3 ( 3 + 4 + 3) and then loop to the right until the end (+ 4)
those numbers would be added and returned.
I hope pseudo code is possible and I haven't just given it already myself lol (thus proving i cant actually code it lol :D )
if not any examples you could provide me with that my help me out :D
thanks guys
I think this pseudocode should do what you're looking for:
array[][] := ...
position := ...
sum := 0
//add the contents of the outer array
for i := 0 to array.length do
sum := sum + array[i][position]
//if we're at (pos, pos) then start looping over the inner array
if i = position then
//note we start at pos + 1 so as not to count array[i][position] twice
for j := position + 1 to array[j].length do
sum := sum + array[i][j]
end
break from loop
end
end
Not sure what you are trying to achieve, I assume this is just an assignment.
If you are looping to the right, shouldn't 1 be included if not the 2 as well?
i.e. then loop to the right until the end (+1 + 4)
The answer depends on whether you store the columns or the rows of matrix. Assuming you have a n * n size matrix and you store the rows, so
A = [[1,2,3,4], [2,3,4,5], [1,2,3,4], [3,2,1,4]]
and the starting point is i, you should go from the array no. m = i div n (the integer part of the division, rounding down), and inside the array, the staring element should be the no. p = i mod n (the modulus). And from that point, you can select every array from m to n, and in every array, the pth element, until the most recent element is the same as your original.
In Java-like code:
int n = 4;
int[][] A = new int[n][n];
... // initialize A
int sumValues(int i) {
int original = A[i/n][i%n];
int sum = original;
int p = i % n;
for (m = i/n + 1, m<n, ++m) {
if (A[m][p] != orginal) sum += A[m][p];
else break;
}
return sum;
}
If you are storing the columns, so
A = [[1,2,1,3], [2,3,2,2], [3,4,3,1], [4,5,4,4]]
then m and p are inversed, meaning that from A you should select array no. m = i mod n and inside that array, element no. p = i div n. After this, you stay in your selected array, and just increase p until A[m][p] equals to the originally selected value.
In Java-like code:
int n = 4;
int[][] A = new int[n][n];
... // initialize A
int sumValues(int i) {
int original = A[i%n][i/n];
int sum = original;
int p = i / n;
for (p = i/n +1, p<n, ++p) {
if (A[m][p] != orginal) sum += A[m][p];
else break;
}
return sum;
}
But correct me, if I'm wrong :)

Categories