What is the use of .length here? What could be substituted with .length in the code below? I just wanted to understand the code better, Exams tomorrow! W00t!
public class twoDimension{
public static void main(String[] args) {
int[][] a2 = new int[10][5];
for (int i=0; i<a2.length; i++) {
for (int j=0; j<a2[i].length; j++) {
a2[i][j] = i;
System.out.print(" " + a2[i][j]);
}
System.out.println("");
}
}
}
You have declared an array of arrays of int type and initialized it.
10 inside the first square bracket says that you are going to store 10 values for the row and is the size of the array ‘n’ where n=10. The row length is 10.
5 inside the second square bracket says that you are going to store 5 values for the column and is the size of the array ‘n’ where n=5. The column length is 5.
In this case, you have one array with 10 locations
streetX[house_1]
streetX[house_2]
streetX[house_3]
streetX[house_4]
streetX[house_5]
streetX[house_6]
streetX[house_7]
streetX[house_8]
streetX[house_9]
streetX[house_10]
and inside each of the location is another 5 different locations
{house_i[room_number1], house_i[room_number2], house_i[room_number3], house_i[room_number4], house_i[room_number5]}
where i can represent any of 1 to 10
Think of it as 10 houses on a street. Each of the houses having 5 rooms. Each house will have a unique address to distinguish it from other houses on the street. In the same manner, each room in one house will be different from the rest. You can now keep different stuffs in each room.
The street is has an array of houses and each house has an array of room.
Therefore, you will have: You can think of a2 as streetX, i.e. a2 = streetX
streetX has 10 houses, therefore, there are 10 locations in a2. The size of a2 is 10 meaning that the length is 10. Therefore, a2.length = 10
NOTE: When you refer the array values, the index starts from 0 ‘zero’ to ‘n-1′. An array index is always a whole number and it can be a int, short, byte, or char.
house_i (where i ranges from 1 t0 10) but we usually count the index from 0. We'll have index 0 to 9. house_i is similar to a2[i]. There are 5 rooms, hence 5 locations. The size of any a2[i] (i.e. any house a2[0], a2[1], a2[2], a2[3] or a2[4])) is 5 meaning that the length is 5. Therefore, a2[i].length = 5
a2[house1][room1] a2[house1][room2] a2[house1][room3] a2[house1][room4] a2[house1][room5]
a2[house2][room1] a2[house2][room2] a2[house2][room3] a2[house2][room4] a2[house2][room5]
a2[house3][room1] a2[house3][room2] a2[house3][room3] a2[house3][room4] a2[house3][room5]
a2[house4][room1] a2[house4][room2] a2[house4][room3] a2[house4][room4] a2[house4][room5]
a2[house5][room1] a2[house5][room2] a2[house5][room3] a2[house5][room4] a2[house5][room5]
a2[house6][room1] a2[house6][room2] a2[house6][room3] a2[house6][room4] a2[house6][room5]
a2[house7][room1] a2[house7][room2] a2[house7][room3] a2[house7][room4] a2[house7][room5]
a2[house8][room1] a2[house8][room2] a2[house8][room3] a2[house8][room4] a2[house8][room5]
a2[house9][room1] a2[house9][room2] a2[house9][room3] a2[house9][room4] a2[house9][room5]
a2[house10][room1] a2[house10][room2] a2[house10][room3] a2[house10][room4] a2[house10[room5]
NOTE: When you refer the array values, the index starts from 0 ‘zero’ to ‘n-1′. An array index is always a whole number and it can be a int, short, byte, or char.
If n = 10, we'll have 0 ... 9
If n = 5, we'll have 0 ... 4
As an example, streetX[house1][room1] = a2[house1[room1] will become a2[0][0]
Eventually, you will have:
a2[0][0] a2[0][1] a2[0][2] a2[0][3] a2[0][4]
a2[1][0] a2[1][1] a2[1][2] a2[1][3] a2[1][4]
a2[2][0] a2[2][1] a2[2][2] a2[2][3] a2[2][4]
a2[3][0] a2[3][1] a2[3][2] a2[3][3] a2[3][4]
a2[4][0] a2[4][1] a2[4][2] a2[4][3] a2[4][4]
a2[5][0] a2[5][1] a2[5][2] a2[5][3] a2[5][4]
a2[6][0] a2[6][1] a2[6][2] a2[6][3] a2[6][4]
a2[7][0] a2[7][1] a2[7][2] a2[7][3] a2[7][4]
a2[8][0] a2[8][1] a2[8][2] a2[8][3] a2[8][4]
a2[9][0] a2[9][1] a2[9][2] a2[9][3] a2[9][4]
The outer for...loop will be repeated 10 times, remember, a2.length = 10 and the inner for ... loop is repeated 5 times, remember, a2[].length = 5
You initialized a2[i][j] = i, therefore for each inner loop, you will have the index of i (the house) will be the stored as the value or number of things in each room for the house.
Hence, when you execute the program, you will get the output or result below printed out.
Count the number of rows and columns and observe that on each line the values are the same.
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
7 7 7 7 7
8 8 8 8 8
9 9 9 9 9
For an array you can use [array_object_name].length or specify the size in number. E.g. a2.length or 10, or a2[i].length or 5 in you example program. Where i equals any of 0, 1, 2, 3, 4. Note that length in .length is a static variable ( You can read more about static variables from here http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html and learn about static methods and static classes as well)
In summary, the length is the size of an array
You can learn more about array from here - http://javapapers.com/core-java/java-array/
What is the use of .length here?
no different from one dimensional array: to get number of elements in the array, if you treat two dimensional array as a table, then assuming the first .length is the row length, the second .length is the column length. get it?
What could be substituted with .length in the code below?
What do you see in the declaration (construction to be precise)?
a2.length is the number of rows. In this case the outer loop will iterate 10 times.
a2[i].length is the length of one specific row.
Related
I'm learning java and have some misunderstanding about array elements:
import java.util.Random;
class One {
public static void main (String[]args) {
Random R1 = new Random();
int mat [] = new int [6];
for ( int chance =0; chance<99; chance++ ) {
++mat[1+R1.nextInt(5)];
}
System.out.println("M\tNumber");
for(int M =1;M <mat.length;M++) {
System.out.println(M + "\t" + mat[M]);
}
}
}
And after running this code I got something like:
M Number
1 30
2 15
3 17
4 23
5 14
I did a lot of attempts and usually Number <=20, which is a bit confusing for me cause I assighn chance <99 hence I asume it should be a bigger number in general. Could you point on my mistake?
I think there is no mistake.
It is very likely that numbers will be about 20 because:
You repeat the following sequence 99 times:
1. Get one random(one of six) element from array.
2. Increase element value (plus one).
Let's assume (of course it doesn't) that random method works in the way it gets for 99 execution :
20 times value 0
20 times value 1
20 times value 2
20 times value 3
20 times value 4
19 times value 5
So we get:
20 in first array element
20 in second array element
and so on...
So, to get bigger number you need to decrease array length or change condition in for loop to bigger "chance" number (in your case: for ( int chance =0; chance<200; chance++ ) ).
Consider an array of integers A having N elements in which each element has a one- to-one relation with another array element.
For each i, where 1≤i≤N there exists a 1−>1 relation between element i and element N−i+1
The Task is to perform following operations on this array which are as follows:
Given two integers (L,R) we have to swap each element in that range with its related element.(See Sample explanation below)
Sample Input
5
1 2 3 4 5
2
1 2
2 3
Sample Output
5 2 3 4 1
Explanation
For first query,we will swap 1 with 5 and 2 with 4.
Now the array becomes- 5 4 3 2 1
Similarly now ,for the second query we will swap 4 with 2 and 3 with itself.
So the final array will be 5 2 3 4 1
My Program goes like this:
import java.util.Scanner;
public class ProfessorAndOps {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int n=in.nextInt();//length of array
int a[]=new int[n];//array declaration
for(int i=0;i<n;i++){
//inputting array elements
a[i]=in.nextInt();
}
int q=in.nextInt();//number of queries
for(int i=0;i<q;i++){
int l=in.nextInt();//left limit
int r=in.nextInt();//right limit
//swapping while iterating over the given range of array elements:
for(int j=l-1;j<=r-1;j++){
int temp=a[j];
a[j]=a[n-j-1];
a[n-j-1]=temp;
}
}
//Printing the output array:
for(int i=0;i<n;i++){
if(i!=n-1){
System.out.print(a[i]+" ");
}
else{
System.out.println(a[i]);
}
}
}
}
I could only come up with BruteForce solution. I'm pretty sure there will be some pre-processing step or some optimisation technique with l and r variables, whatever I could think of, giving me wrong answer. Please help me optimise this code. To be specific, I would need my code's time complexity to be reduced from O(N+ Q*(R-L)) to something like O(Q+N)
Here's an O(Q + N) time, O(N) space algorithm. Imagine a list of the corresponding swap counts only for L and R over the elements (we'll use a negative number for the R counts). What if we maintained a virtual stack while traversing it? (By "virtual," I mean it's not a real stack, just an integer that bears some theoretical similarity.)
For example:
1 2 3 4 5 6 7 8 9 10
O(Q) processing:
q [1,3]
1 9 8 7 5 ... <- what would happen to the array
0 1 0 -1 0 <- counts (what we actually store)
q [2,4]
1 9 3 4 6 ... <- what would happen to the array
0 1 1 -1 -1 <- counts (what we actually store)
O(N) traversal:
index 0 didn't move, no change, stack: 0
index 1 moved once, odd count, changed, stack: 1
index 2 moved 2 (stack + 1), even count, no change, stack: 2
index 3 moved 2 (stack), even count, no change, stack: 2 - 1
index 4 moved 1 (stack), odd count, changed, stack: 1 - 1
Understanding the -1 in the for loop, need detailed explanation with for and if lines of code included?
int[] array = { 2, 5, 1, 2, 3, 5 };
Arrays.sort(array);
// why does this start counting from 1, and if l put 0 it goes to error, out of bounds?
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) { // - 1?
System.out.print(array[i]);
}
}
There is nothing inherently wrong with it.
It just makes the iteration to start with i=1 up to the array's length, but since indexing in arrays are zero-based you have to offset it when getting the value.
That is why is array[i-1]
If you put i=0 then you also have to change the ending condition to array.length-1, and you have to access the values by array[i] in order to avoid going out of bounds.
For questions like this, take the code one line at a time and try to follow what it is doing.
The first thing you do here is to create an array, then sort it. After the Arrays.sort(array) call, your array will contain the following:
index 0 1 2 3 4 5
----------------------
contents 1 2 2 3 5 5
Remember, arrays are zero-indexed - that means the very first element is located at index 0. (The contents of the array don't matter, it's the index you want to pay attention to.)
Arrays cannot have indexes less then zero, and they also cannot have indexes greater than their length-1. So, for your example, that means you cannot use -1 as an index because it is less than 0. You also cannot use 6 as an index, since 6 is greater than the length of the array (6) minus one.
In the initialization of the for-loop, you set i equal to 1 for the first iteration. Though unconventional, it's perfectly legal. This simply represents which index we will start from in the array. So for the first iteration of the loop, array[i] will be pointing to the value 2, and array[i-1] points to the value 1.
index 0 1 2 3 4 5
----------------------
contents 1 2 2 3 5 5
i ^
i-1 ^
Now, what if you set i to start at index 0 instead? Well, then array[i] will point to the 0th index (value 1)... but what does array[i-1] point to?
index 0 1 2 3 4 5
----------------------
contents 1 2 2 3 5 5
i ^
i-1 ^
It's pointing to index -1. Since arrays can't have indexes of -1, this is causing your IndexOutOfBoundsException. Hopefully that makes sense.
I am trying to store each line of a file into a String array.
/*
*Input file
*2 1 1 1 1 1 1.33 1
*4 2 15 3 9 3 0.185
*/
String[][] data_array = new String[1][7];
int i = 0;
int j = 0;
//file read
StringTokenizer tokenizer =new StringTokenizer(line,delim);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
data_array[i][j] = token;
j++;
}
But showing
java.lang.Exception: java.lang.ArrayIndexOutOfBoundsException: 7
But When I am trying with
String[][] data_array = new String[1][8];
I am not getting this exception instead I am getting below as the output.
2 1 1 1 1 1 1.33 1 null
4 2 15 3 9 3 0.185 null
In java, arrays are 0-based, that is the first element will have index 0 and the last element will have index n - 1 (where n is the length of the array).
As your array is declared [1][7], the last index will be number 6. Your first row contains 8 values, therefore you end up trying to load the 8th value (index 7) into an array containing 7 elements. Using index 7 results in an IndexOutOfBoundException.
Moreover, in your particular case, the first row of the input contains 8 elements, but the second row only contains 7 elements. If you try to load 7 values into the array containing 8 elements, the last one will be null. For the input you specified, with array declared as having length 8, the output would be:
2 1 1 1 1 1 1.33 1
4 2 15 3 9 3 0.185 null
(Note that I added extra spaces to indicate better how the array is populated.)
Further, it makes little sense to declare a two-dimensional array with the first dimension being 1 - it's the same as declaring a single-dimension array. What you probably want to do is have an array with first dimension referring to rows in the file and second dimension referring to values in rows.
The elements of an array with length i are numbered 0 to i-1.
I assume you are using blanks as delimeters. Is there a trailing blank at the end of the line? This would explain why you are getting one surplus token.
you must use array in your method not in the body of your class!
and arrays first element have index=> 0 and the lastest element have index=> N-1
After a tennis tournament each player was asked how many matches he had.
An athlete can't play more than one match with another athlete.
As an input the only thing you have is the number of athletes and the matches each athlete had. As an output you will have 1 if the tournament was possible to be done according to the athletes answers or 0 if not. For example:
Input: 4 3 3 3 3 Output: 1
Input: 6 2 4 5 5 2 1 Output: 0
Input: 2 1 1 Output: 1
Input: 1 0 Output: 0
Input: 3 1 1 1 Output: 0
Input: 3 2 2 0 Output: 0
Input: 3 4 3 2 Output: 0
the first number of the input is not part of the athletes answer it's the number of athletes that took part in the tournament for example in 6 2 4 5 5 2 1 we have 6 athletes that took part and their answers were 2 4 5 5 2 1.
So far this is what we wrote but didn't work that great:
import java.util.Scanner;
import java.util.Arrays;
public class Tennis {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String N;
int count;
int sum = 0;
int max;
int activeAthletes;
int flag;
System.out.printf("Give: ");
N = input.nextLine();
String[] arr = N.split(" ");
int[] array = new int[arr.length];
for (count = 0; count < arr.length; count++) {
array[count] = Integer.parseInt(arr[count]);
//System.out.print(arr[count] + " ");
}
for (count = 1; count < arr.length; count++) {
sum += array[count];
}
//System.out.println("\n" + sum);
activeAthletes = array[0];
for (count = 1; count < array.length; count++) {
if (array[count] == 0) {
activeAthletes--;
}
}
max = array[1];
for (count = 2; count < array.length; count++) {
if (array[count] > max) {
max = array[count];
}
}
// System.out.println(max);
if ((sum % 2 == 0) && (max < activeAthletes)) {
flag = 1;
} else{
flag = 0;
}
System.out.println(flag);
}
}
I do not want a straight solution just maybe some tips and hints because we really have no idea what else to do and I repeat even though I'll tag it as a homework (because I feel the moderators will close it again) it is not, it's just something my brother found and we are trying to solve.
Well many of you have answered and I'm really grateful but as I have work tomorrow I need to go to sleep, so I'll probably read the rest of the answers tomorrow and see what works
Not sure if it works 100%, i would go like:
Sort input
for each element going from right to left in array (bigger to smaller)
based on value n of element at index i decrease n left elements by 1
return fail if cant decrease because you reached end of list or value 0
return success.
This logic (if correct) can lead whit some modifications to O(N*log(N)) solution, but I currently think that that would be just too much for novice programmer.
EDIT:
This does not work correct on input
2 2 1 1
All steps are then (whitout sorting):
while any element in list L not 0:
find largest element N in list L
decrease N other values in list L by 1 if value >= 1 (do not decrease this largest element)
return fail if failure at this step
set this element N on 0
return OK
Here's a hint. Answer these questions
Given N athletes, what is the maximum number of matches?
Given athlete X, what is the maximum number of matches he could do?
Is this sufficient to check just these? If you're not sure, try writing a program to generate every possible matching of players and check if at least one satisfies the input. This will only work for small #s of atheletes, but it's a good exercise. Or just do it by hand
Another way of asking this question, can we create a symmetric matrix of 1s and 0s whose rows are equal the values. This would be the table of 'who played who'. Think of this like an N by N grid where grid[i][j] = grid[j][i] (if you play someone they play you) and grid[i][i] = 0 (no one plays themselves)
For example
Input: 4 3 3 3 3 Output: 1
Looks like
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0
We can't do this with this one, though:
Input: 3 2 2 0 Output: 0
EDIT
This is equivalent to this (from Degree (graph theory))
Hakimi (1962) proved that (d1, d2, ..., dn) is a degree sequence of a
simple graph if and only if (d2 − 1, d3 − 1, ..., dd1+1 − 1, dd1+2,
dd1+3, ..., dn) is. This fact leads to a simple algorithm for finding
a simple graph that has a given realizable degree sequence:
Begin with a graph with no edges.
Maintain a list of vertices whose degree requirement has not yet been met in non-increasing order of residual degree requirement.
Connect the first vertex to the next d1 vertices in this list, and then remove it from the list. Re-sort the list and repeat until all
degree requirements are met.
The problem of finding or estimating the number of graphs with a given
degree sequence is a problem from the field of graph enumeration.
Maybe you can take the array of athletes' match qties, and determine the largest number in there.
Then see if you can split that number into 1's and subtract those 1's from a few other members of the array.
Zero out that largest number array member, and remove it from the array, and update the other members with reduced values.
Now, repeat the process - determine the new largest number, and subtract it from other members of the array.
If at any point there are not enough array members to subtract the 1's from, then have the app return 0. otherwise continue doing it until there are no more members in the array, at which point you can have the app return 1.
Also, remember to remove array members that were reduced down to zero.
Your examples can all trivially be solved by counting the matches and looking whether they divide by 2.
A problem not covered by your examples would be a player, who has more games than the sum of the other players:
Input: 4 5 1 1 1 Output: 0
This can be complicated if we add more players:
Input: 6 5 5 5 1 1 1 Output: 0
How to solve this question? Well, remove one game pairwise from the maximum and the minimum player, and see what happens:
Input: 6 5 5 5 1 1 1
Input: 5 5 5 4 1 1 -
Input: 4 5 4 4 1 - -
Input: 3 4 4 4 - - -
It violates the rule:
An athlete can't play more than one match with another athlete.
If 3 players are left, they can't have had more than 2 games each.
Edit: Below solution passes some invalid inputs as valid. It's a fast way to check for definite negatives, but it allows false positives.
Here's what a mathematician would suggest:
The sum of the number of matches must be even. 3 3 4 2 1 sums to 13, which would imply someone played a match against themselves.
For n players, if every match eliminates one player at least n-1 distinct matches must be played. (A knockout tournament.) To see this, draw a tree of matches for 2, 4, 8, 16, 32... players, requiring 1, 3, 7, 31... matches to decide a winner.
For n players, the maximum number of matches if everyone plays everyone once, assuming no repeat matches, is n choose 2, or (n!)/(2!)(n-2)! (Round robin tournament). n! is the factorial function, n! = n * n-1 * n-2 * ... * 3 * 2 * 1..
So the criteria are:
Sum of the number of matches must be even.
Sum of the number of matches must be at least 2n-2. (Note the multiplication by 2 - each match results in both players increasing their count by one.)
Sum of the number of matches must be at most 2 * n choose 2.
[Edit] Each player must participate in at least one match.
If your tournament is a cross between a knockout tournament and a round robin tournament, you could have somewhere between n-1 and n choose 2 matches.
Edit:
If any player plays more than n-1 matches, they played someone at least twice.
If your tournament is a knockout tournament ordered so that each player participates in as few matches as possible, then each player can participate in at most log_2(n) matches or so (Take log base 2 and round up.) In a tournament with 16 players, at most 4 matches. In a tournament of 1024 players, at most 10 matches.