Arrayelements as counters - java

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++ ) ).

Related

I want to generate four Different Random Numbers in android But Their total should not be Greater Than the Specified range like 0 to 69

This my Button OnClick() Method on Click of the button All Four random numbers will be Displayed on the Logcat
public void onClick(View v) {
/* the Code for Four Random Numbers*/
final Random random = new Random();
final Set<Integer> mySet = new HashSet<>();
while (mySet.size() < 4) {
mySet.add(random.nextInt(69) + 1);
}
// Now Adding it to the ArrayList
ArrayList<Integer> Elements = new ArrayList<>(mySet);
Log.i("Elements","A:" + Elements.get(0));
Log.i("Elements","B:" + Elements.get(1));
Log.i("Elements","C:" + Elements.get(2));
Log.i("Elements","D:" + Elements.get(3));
}
});
The Output Will be Look Like this (I just give an Example of one case It is Different in every case Whenever I run a App)
A : 11
B : 28
C : 57
D : 1
Now the Problem is :
The sum of all the numbers is greater than the specified range which is 0 to 69
When We Add A,B,C,D values which is equals to 97
Which is greater than the Specified Range 0 to 69
So I Want the Random Numbers in such a way that :
when we Add A,B,C,D the their Sum Should no Exceed the Range that is 69
So My Question is How can i Do That ?
Please Help!! I am Stuck in that part of the Code
and I find no Solution
In addition to what other people have suggested, you might want to read this: find all subsets that sum to a particular value
First, note that this bears some resemblance to the subset sum problem. Given the set of all numbers between 1 and 69, you're looking for a subset of 4 of them that adds up to 69. For any natural number, there are only a finite number of such sets (although it obviously eventually gets computationally infeasible to enumerate all of them). Either way, your answer is guaranteed to be one of these sets regardless of what algorithm you use.
The linked question shows code to find all of the subsets that add up to a particular value. Once you have this, just filter on all the subsets that have length 4 and randomly pick one of them.
There are two ways, depending on how you want to do it:
Rereoll the random numbers until a valid sum is achieved. This will be truly random.
Change the max value for the 2nd, 3rd, 4th, etc random number so that it can't be too big. However this will change it from every number being equally likely to smaller numbers being more likely.
This is a tricky question. These is no mention of a sample space, so one can assume it has to be valid integer of sorts. Generate any number of a number signed 32 bit integer. This would be –2147483648 and 2147483647 until you have four unique ones which sum is between 0 and 69.
Best of luck!
you can use this code :
final Random random = new Random();
final Set<Integer> mySet = new HashSet<>();
int thesum = 0 ;
while (mySet.size() < 4 && thesum< 69) {
int nmbr = random.nextInt(69) + 1 ;
thesum = thesum + nmbr ;
mySet.add(nmbr) ;
}
if( mySet.size() == 3)
{ArrayList<Integer> Elements = new ArrayList<>(mySet);
Log.i("Elements","A:" + Elements.get(0));
Log.i("Elements","B:" + Elements.get(1));
Log.i("Elements","C:" + Elements.get(2));
Log.i("Elements","D:" + Elements.get(3));}

What am I doing wrong with this factorial program? It just keeps on returning back the original value

public static void main (String args[]){
int num=5;
int i=num-1;
int factorial=0;
while(i>0){
factorial=num*i;
i--;
}
System.out.println(""+factorial);
}
It just keeps on returning me 5. Sorry,if it sounds like a kiddish question, I am new to programming world.
Replace
factorial=num*i;
with
num=num*i;
And
System.out.println(""+factorial);
with
System.out.println(""+num);
Reason
You are running your while loop correctly. In each iteration, you are multiplying two successive numbers. But you are storing the result in factorial which gets overwritten with every iteration. So in the end, you end up getting the original number. So do as directed above, get rid of factorial varialble.
I will not give you solution, but it is normal that it's storing 5, because your last execution is:
factorial = 5 * 1;
Now think twice what you HAVE to do.
You Are Doing Something Wrong because it will execute as
num is 5 and i is 4 // result will be 20
then num is 5 and i is 3 // result will be 15
then num is 5 and i is 2 // result will be 10
then num is 5 and i is 1 // result will be 5
while loop break
you need to store your previous result so use this
int num=5;
int factorial=1;
while(num>0){
factorial=num*factorial; // previous result will be store in factorial
num--;
}
System.out.println(""+factorial);
Now how this program is working
num is 5 and fact is 1 // fact will be 5
then num is 4 and fact is 5 // fact will be 20
then num is 3 and fact is 20 // fact will be 60
then num is 2 and fact is 60 // fact will be 120
then num is 1 and fact is 120 // fact will be 120
while loop break
In each loop, you are multiplying the number by i, so in the end you will just get num*1. You can initialize the result variable factorial with the value of num and in each loop, assign it its value multiplied by i, that will result the multiplication of all numbers from 1 to num (factorial):
public static void main (String args[]){
int num=5;
int i=num-1;
int factorial=num;
while(i>0){
factorial=factorial*i;
i--;
}
System.out.println(""+factorial);
}

Why does the output for my program always start with two consecutive zeros even though I wrote a code that doesn't produce zeros or repeated numbers?

I am trying to create a method that produces lottery numbers with a random number generator. There are two groups of numbers. Group one is supposed to have five different numbers that appear in sorted order, with a range of 1-56. Group two consists of a single number with a range of 1-46. When I run the program, group one always begins two consecutive zeros even though I tried to write the code in a way that doesn't allow group one to have zeros or repeating numbers. At first I thought that the problem must have something to do with the random number generator, so I tried debugging the project in NetBeans. As I stepped through the lines of code, I could see the values assigned to n, which is the variable that holds the numbers produced by the random generator. The values of n were 54, 50, 11, 49, and 28. In the program, the values of n are put into a sorted array. So the output for group one should have been 11, 28, 49, 50, 54, but instead it was 0, 0, 11, 28, 49.
Here is my code:
public static void MakeTickets(){
int [] Group1= new int [5];
int Group2;
int n;
Random rand= new Random ();
for (int j=0 ; j<5; j++){
//Here, I try to make sure that the range for n is 1-56
n= rand.nextInt(55)+1;
//Here, I try to make sure that a number isn't put into the group one
//array more than once
while (Arrays.binarySearch(Group1, n)>=0){
n= rand.nextInt(55)+1;
}
Group1[j]=n;
Arrays.sort(Group1);
}
Random r= new Random();
int num= r.nextInt(45)+1;
Group2=num;
System.out.print("Here is your ticket: Group One= ");
for(int number: Group1){
if (number==Group1[4]){
System.out.print(number);
} else {
System.out.print(number+", ");
}
}
System.out.println(" Group Two= "+Group2);
}
Here is the output:
Here is your ticket: Group One= 0, 0, 33, 45, 50 Group Two= 40
I've tried using ThreadLocalRandom instead, but I still had the same problem. Does anyone know what I am doing wrong? Any and all advice is much appreciated.
The Arrays.sort(Group1); is causing the problem.
I believe the Arrays.sort(Group1); should be placed after the first for loop (after generating the Group1 values).
Currently the values are sorted after adding every value.
Initially the values in the array are 0 0 0 0 0
1st Iteration
After generating the first number
n= rand.nextInt(55)+1; //lets assume the generated value is 43
the, array becomes 43 0 0 0 0
After calling the sort ,
Arrays.sort(Group1);
the array becomes 0 0 0 0 43
2nd Iteration.
After generating the second number
n= rand.nextInt(55)+1; //lets assume the generated value is 22
the, array becomes 0 22 0 0 43
After calling the sort ,
Arrays.sort(Group1);
the array becomes 0 0 0 22 43
3rd Iteration
After generating the third number
n= rand.nextInt(55)+1; //lets assume the generated value is 31
the, array becomes 0 0 31 22 43
After calling the sort ,
Arrays.sort(Group1);
the array becomes 0 0 22 31 43
The 4th and 5th iteration do not change the first two values in the array. This way the first 2 number get stuck as 0s, which explains your result.
You can't use Arrays.binarySearch on an unsorted array. In such case result of this operation is unpredictable.
Sort moves all zeros to the beginning of the array. But you are not rewriting them (cause j is being incremented).
Hello there,As far as I know, there are zero-digit situation, the general is the default allocation of zero is the compiler, that you did not initialize this variable.
I believe the problem is that the int array is being sorted every time. The int array is initialized with values of 0. By sorting the array every time you are changing where the new random number needs to be inserted. So sometimes you are accidentally overwriting one of the randomly generated numbers instead of the 0's.
Perhaps instead of using BinarySearch which requires the sorting just used contains and get rid of the sorting until all of the random numbers are generated. I don't know the exact syntax since I haven't coded in Java for 3 years, but you could do something like Arrays.asList(Group1).contains(n). So...
for (int j = 0; j < 5; j++) {
//Here, I try to make sure that the range for n is 1-56
n= rand.nextInt(55)+1;
while (Arrays.asList(Group1).contains(n)) {
n = rand.nextInt(55)+1;
}
Group1[j] = n;
}
Arrays.sort(Group1);

divide and conquer: computing the time elapsed

I have to do a little assignment at my university:
I have a server that runs 'n' independent services. All these services started at the same time in the past. And every service 'i' writes 'b[i]' lines to a log file on the server after a certain period of time 's[i]' in seconds. The input consist of 'l' the number of lines of the log file and 'n' the number of services. Then we have in the next 'n' lines for every service i: 's[i]' the period as mentioned and 'b[i]' the number of lines the services writes to the log file.
I have to compute from the number of lines in the log file, how long ago, in seconds, the programs all started running. Example:
input:
19 3
7 1
8 1
10 2
Output:
42
I have to use divide and conquer, but I can't even figure out how to split this in subproblems. Also I have to use this function, where ss is the array of the periods of the services and bs the number of lines which each services writes to the log file:
long linesAt(int t, int[] ss, int[] bs) {
long out = 0;
for (int i = 0; i < ss.length; i++) {
// floor operation
out += bs[i] * (long)(t/ss[i]);
}
return out;
ss and bs are basically arrays of the input, if we take the example they will look like this, where the row above is the index of the array:
ss:
0 1 2
7 8 10
bs:
0 1 2
1 1 2
It is easily seen that 42 should be the output
linesAt(42) = floor(42/7)*1+floor(42/8)*1+floor(42/10)*2 = 19
Now I have to write a function
int solve(long l, int[] ss, int[] bs)
I already wrote some pseudocode in brute force, but I can't figure out how to solve this with the divide and conquer paradigm, my pseudocode looks like this:
Solve(l, ss, bs)
out = 0
t = 0
while (out != l)
out = linesAt(t, ss, bs)
t++
end while
return t
I think I have to split l in some way, so to calculate the time for smaller lengths. But I don't really see how, because when you look at this it doesn't seem to be possible:
t out
0..6 0
7 1
8 2
9 2
10 4
11..13 4
14 5
15 5
16 6
17..19 6
20 8
...
40 18
42 19
Chantal.
Sounds like a classic binary search would fit the bill, with a prior step to obtain a suitable maximum. You start with some estimate of time 't' (say 100) and call linesAt to obtain the lines for that t. If the value returned is too small (i.e. smaller than l), you double 't' and try again, until the number of lines is too large.
At this point, your maximum is t and your minimum is t/2. You then repeatedly:
pick t as the point halfway between maximum and minimum
call linesAt(t,...) to obtain the number of lines
if you've found the target, stop.
if you have too many lines, adjust the maximum: maximum = t
if you have too few lines adjust the minimum: minimum = t
The above algorithm is a binary search - it splits the search space in half each iteration. Thus, it is an example of divide-and-conquer.
You are trying to solve an integer equation:
floor(n/7)*1+floor(n/8)*1+floor(n/10)*2 = 19
You can remove the floor function and solve for n and get a lower bound and upper bound, then search between these two bounds.
Solving the following equation:
(n/7)*1+(n/8)*1+(n/10)*2 = 19
n=19/(1/7+1/8+2/10)
Having found n, which range of value m0 will be such that floor (m0 / 7) = floor (n/7)?
floor (n/7) * 7 <= m0 <= (ceiling (n/7) * 7) - 1
In the same manner, calculate m1 and m2.
Take max (mi) as upperbound and min(mi) as lowerbound for i between 1 and 3 .
A binary search at this point will probably be an overkill.

identifying .length in two dimensional array

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.

Categories