Testing a random number generator - java

I am having trouble printing out the first two columns of the results in a table but as I am new to programming I am having issues and wondering where the issue is in my code. The brief states I must create:
A parameterless static int method, randInt(), that will return a random integer in the range 0..9 inclusive. This method will include a call to Math.random().
A static void method named randTest that takes a single integer argument, n. This should perform the following actions:
Declare an int array of 10 elements named counts. This will be used to record how often each possible value is returned by randInt.
Call randInt n times, each time incrementing the count of the element of counts corresponding to the value returned.
Print the results to the console in a clear tabular form. The output should look like the following:
This is my code:
import java.util.Arrays;
public class RandNumGenerator {
public static int RandInt(){
double n = Math.random()*10;
return (int) n;
}
public static void randTest(int n){
int [] counts = new int [10];
for(int i=0;i<n;i++){
counts[i] = RandInt();
System.out.println(counts[i]);
}
}
public static void main(String[] args) {
int sampleSize = 1000;
System.out.println ("Sample Size: " + sampleSize);
String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
System.out.println(Arrays.toString(intArray));
randTest(10);
}
}

public static void randTest(int n){
Question for you to think about: What is the parameter here? Hint: It's not 10... What do you actually want to DO n times?
counts[i] = RandInt();
You really want to create 10 random numbers and store them into the array? Nope. You want to create "sampleSize" numbers and increase the array on the correct position. What would the correct position be?
counts[ correctPosition ] = counts[ correctPosition ] + 1;
...would be more correct, if you can figure out the correctPosition.
Also I would move the output from the main method to randTest() where you have everything together.

Related

Adding plus 1 towards an array containing full of number via main class and another class

public class Main
{
public static void main(String[] args)
{
int[] num = {1,2,3,4};
System.out.println(Counter.add(num));
}
}
Class
public class Counter
{
public static int add(int[] numb)
{
for(int i=0;i<numb.length;i++){
numb[i]++;
System.out.println(numb[i]);
int result = result + numb[i];
}
return result;
}
}
I am trying to output the total number in the array list, but with a twist, having +1 to each number in the array list, so 1,2,3,4 would give me 14, as 1+2+3+4 = 10 + 4 (+1 to each number), do I have to use .split to give me the total amount of variable in the array to add onto the total addition?
Do I have to use .split to give me the total amount of variable in the array to add onto the total addition?
No. You can simply return the sum, plus the length of the Array. Also you declare result within the for loop, so it is only in scope within the loop. Move it outside of the loop
public static int add(int[] numb)
{
int result = 0;
for(int i=0;i<numb.length;i++){
System.out.println(numb[i]);
result += numb[i];
}
return result + numb.length;
}
Which, when called with the Array int[] num = {1,2,3,4}; outputs 14.

How can I fix this error (Java Method + Array)?

I want to make a program which, after filling an array in main(), through a method, returns the arithmetic mean of the elements contained in that array.
When I call the method to execute the process (the line where I use the System.out.print) it gives me an error, saying that the method is not applicable for the arguments in it. But it should lead to an array of ints.
Code
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
System.out.println(meanArray (2, 6, 9, 19, 1));
}
static int meanArray (int [] a) {
Scanner inputLine = new Scanner(System.in);
int numbers;
int start;
int sum = 0;
int mean;
numbers = inputLine.nextInt();
for (start = 0; start < numbers; start++) {
a[start] = inputLine.nextInt();
sum = sum + a[start];
}
mean = sum/numbers;
return mean;
}
}
When you call
System.out.println (meanArray (2, 6, 9, 19, 1));
it expected a method with a signature like
public static Something meanArray(int a, int b, int c, int d, int e) {
Most likely what you intended was
public static Something meanArray(int... a) {
which accepts a variable number of arguments.
The problem in this code is you create a method that take an integer array as parameter and you send different integer values but not an integer array when calling the method. Instead calling;
meanArray(1,2,4,3)
you should declare integer array and pass the variable to the method.
It will be better to declare array variable first and pass it to the function like:
int a[]={1,2,3,4};
meanArray(a);
And you donot need to declare another numbers variable ( lenth is inbuilt function to return size of an array)inside the method for summing elements of array, try as follows inside the meanArray();
for(start=0;start<a.length;start++){
sum+=a[start];
}
If you want to test the numbers in your code, declare and initialize the array with:
int[] array ={2,6,9,19,1}; and then call meanArray(array);
If you want to test an arbitrary set of numbers from console, you need to declare the array differently with:
int[] array = new int[5]; //*5 states how many numbers you will input from console *
and then you need to change the loop interval to: start < array.length;

How to find all possible numbers with a Recursion method

i want to write a Recursion method that prints all possible arrangements for these
numbers , the integers 1 to 9
arranged randomly in a grid of three rows and three column.for example :
6 2 1
5 4 7
3 9 8
sorry i don't have any code , because it's very hard to me.
public class Test {
public static void main (String[] args){
String x = "123456789";
System.out.println(test(x,0));
}
public static String test(String x , int y){
if(x.length()==1)return "";
return x.charAt(y)+test(x.substring(y),y);
}
There are many ways to implement something like this, this is one example. I will use int[] instead of String for convenience sake:
public static void main(String[] args) {
nextPermutation(new int[9], 0, new boolean[9]);
}
public static void nextPermutation(int[] perm, int index, boolean[] alreadyUsed) {
if(index == perm.length) {
//the permutation is complete
//you can store it or print it
} else {
for(int i = 0 ; i < alreadyUsed.length ; i++) {
if(alreadyUsed[i]) continue;
perm[index] = i+1;
boolean[] newAlreadyUsed = Arrays.copyOf(alreadyUsed, alreadyUsed.length);
newAlreadyUsed[i] = true;
nextPermutation(Arrays.copyOf(perm, perm.length), index+1, Arrays.copyOf(newAlreadyUsed, newAlreadyUsed.length));
}
}
}
This will generate all possible combinations of 1-9. The idea of the algorithm is that you keep track of which digits you already used, run through a loop and select all available digits.
Note that it's important to pass copies of perm and alreadyUsed, otherwise you will just pass the same array and overwrite previous permutations.
pass values ​​to an array, randomize and create a loop to generate the matrix.
loop: make a generic loop starting to generate matrix with i0 , j0 like position i1 , j1 of matrixand add the values of array
int j = 0;
for( int i = 0; i <= YOURARRAY.length(); i++)
{
System.out.println( i POSITIONOFARRAY );
j+1
}

Random Numbers Test (Histogram)

I'm brand new to Java coding i'm trying to create a histogram with the following methods that were given to me. The comments are the instruction to each of our method that we will later use to create a main method and print a histogram. I have got up to method 3 and was able to compile everything fine but i'm not sure if i'm doing them right, I just know that they are compiling correctly up to method 4. I just don't know what to do for method 5.
/*
Method 1:
Find the maximun value in an array
*/
public static int max(int[]arr){
int maxValue = arr[0];
for ( int i=1; i < arr.length; i++ ){
if (arr[i] > maxValue){
maxValue = arr[i];
}
}
return maxValue;
}
/*
Method 2:
Compute a random integer in the range [a..b)
*/
public static int randomInteger(int a, int b){;
int randomNum;
randomNum = a+(int)(Math.random() * ((b-a)+1));
return randomNum;
}
/*
Method 3:
Draw a Simple histogram of the array arr.
*/
public static void drawHistogram(int[] arr){
for ( int i=0; i<arr.length; i++ ){
System.out.print((i*10+1)+"-"+(i*10+10)+":"+"\t");
for (int j=0; j<arr[i]; j++)
System.out.print("*");
System.out.println();
}
}
/*
Method 4:
Compute num random integers in the range [0..range) and put the frequency in arr[]
*/
public static void doSingleTest(int[] arr, int num, int range){
for (int i=1; i<=num; i++){
int random = randomInteger(0,range);
arr[random]++;
}
}
/*
Method 5:
Compute num pairs of random integers in the range [0..range) and put the frequency in arr[]
*/
public static void doPairsTesting(int[] arr, int num, int range){
}
public static void main(String[] args) {
int test[] = new int[]{1,2,3,4,6,11,7};
System.out.println("method1 = "+ max(test));
System.out.println("method2 = "+randomInteger(1,20));
drawHistogram(test);
doSingleTest(test,1,5);
System.out.println("method4 = "+Arrays.toString(test));
}
It's fault design int random = int randomInteger(range); I think you need to read docs abot java basics.
I fixed method4 in next way:
public static void doSingleTest(int[] arr, int num, int range){
for (int i=1; i<=num; i++){
int random = randomInteger(0,range);
arr[random]++;
}
}
For testing your methods, use next main method, it prints results to console or you can use Debugger in your IDE:
public static void main(String[] args) {
int test[] = new int[]{1,2,3,4,6,11,7};
System.out.println("mathod1 = "+ max(test));
System.out.println("mathod2 = "+randomInteger(1,20));
drawHistogram(test);
doSingleTest(test,1,5);
System.out.println("mathod4 = "+Arrays.toString(test));
}
And at last your method 5 must to return value of needed type or be void:
public static void doPairsTest(int[] arr, int num, int range){
}
For computing random integers, you might want to consider using the Random class. Here is some documentation: http://docs.oracle.com/javase/6/docs/api/java/util/Random.html
You can do this by declaring a Random object inside your class like this:
static Random randomGenerator = new Random();
And then within each of your methods, you can use randomGenerator.nextInt(n), where n will be the end of the range you want random numbers to be included. (exclusive of n, starting with 0).
For method 4, you probably want to set the return type to be an array. And then you can either leverage this randomGenerator, or given your current code, you'd have to pass in two parameters to your randomInteger method.
For method 5, you can simply use your doSingleTest method and then divide the entries of your array by 2 before returning the array. This works because if you find two 3s, your doSingleTest would have a frequency of 2 at the appropriate position. And dividing this by 2 would give you the number of pairs. Also you don't have to worry about odd numbers because the int type in Java simply drops remainders.
I also just noticed that you did not set a return type for method 5, so go ahead and set that to be int[]
And use a public static void main(String[] args) method to test your methods.
For method 5, are you referring to the dopairtest? In case so here is how I solved that:
static void doPairsTest(int[] arr3, int num2, int range3){
for (int i = 0 ; i < num2 ; i++) {
int rand2 = randomInteger(0, range3);
int rand3 = randomInteger(0, range3);
int randomPair = (rand2 * 10) + rand3 ;
System.out.println(randomPair);
arr3[randomPair] ++ ;
}
}
As you can see I just declared and assigned randomly generated values from my previous method into rand2 and rand 3 and then I added the two of them so they add up to a double digit.
Did you find out how to do the histogram? I am very confused on how to plot it based on the numbers and frequencies we generated.
public static void drawHistogram(int[] arr){
int n=0;
for (int i=1;i<=99;i++)
if (arr[i]>n)
n=arr[i];
for (;n>0;n--)
{
String r=" ";
for (int i=0;i<=99;i++)
if (n<=arr[i])
{
System.out.print(r+"*");
r=" ";
}
else
r+=" ";
System.out.println();
}
}

Count how many times an element occurs in an array - Java

I recently made a very simple practice program in Python, that takes user input and rolls dice. The code is:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(actually this is part of a larger program, so I had to cut'n'paste bits, and I might have missed something out).
And so I decided to translate that to Java. Notice the algorithm here: get random number, print it, append it to an array, then count the amount of each number in the array at the end, and print out that value. Problem is, I don't know how to do the equivalent of someArray.count(someIndex) in Java syntax. So my Java program looks like this so far:
import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
So can someone help me with the array counting code? I understand that this might not be a defined method, since Python is higher level after all, so I could make my own array counting method, but I was wondering if Java, like Python, has a predefined one.
EDIT: I managed something like this:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
EDIT: Just out of interest, assuming I use Command prompt to run my Java program and Python.exe (command prompt console for Python), which one will be faster (in other words, for the same code, which language has better performance?)?
You could use a HashMap to store the result.
If the new number is not in your map you add it with "1" as initial value.
If it exists your put "+1" to the current map value.
To display the values you just have to iterate on you entries in a for each loop.
The solution is to transform your array to a List and then use the Collections.frequency method:
List<Integer> resultList = Arrays.asList(results);
int freq = Collections.frequency(resultList, 4);
Also you could use ArrayList from the very beginning saving you the transformation:
List<Integer> result = new ArrayList<Integer>();
// add results
int freq = Collections.frequency(result, 4);
See the Collections documentation here
EDIT: If performance is an issue (as suggested in the comments) then maybe you want to use each index of the array as a counter, as follows:
Random flip = new Random(SIDES);
int[] counters = new int[SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
counters[result] = counters[result]+1;
}
Notice that you no longer need to count at the end since you've already got all the counters in the array and there is no overhead of calculating the hash.
There are a couple libraries that will do this for you:
Google Guava's MultiSet
Apache Common's Bag
But for something so simple, you may consider an extra library a bit excessive.
You can also do this yourself with an int[]. Assuming your dice is using whole numbers, have the number rolled refer to the index into the array, and then increment the value at that index. When you need to retrieve the value for a given number, look up its value by the index.
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
There's a frequency method in collections
int occurrences = Collections.frequency(listObject, searchItem);
Java doc for collections
As far as I am aware, there is no defined method to return the frequency of a particular element in an array. If you were to write a custom method, it would simply be a matter of iterating through the array, checking each value, and if the value matches the element you're after, incrementing a counter.
So something like:
// in this example, we assume myArray is an array of ints
private int count( int[] myArray, int targetValue) {
int counter = 0;
for (int i = 0 ; i < myArray.length; i++ ) {
if (myArray[i] == targetValue) {
counter++;
}
}
return counter;
}
Of course, if you want to find the frequency of all the unique values in your array, this has the potential of being extremely inefficient.
Also, why are you using a 7-sided die? The Random nextInt() will return a number from 0 up to but not including the max. So your die will return values from 0 through 6. For a six-sided die, you'd want a new Random(6); and then increment your roll by one to get a value from one through six: flip.nextInt() +1;.
class FindOccurrence {
public static void main (String[]args) {
int myArray[] = {5, 8, 5, 12, 19, 5, 6, 7, 100, 5, 45, 6, 5, 5, 5};
int numToFind = 5;
int numberOfOccurrence = 0;
for (int i=0; i < myArray.length; i++) {
if (numToFind == myArray[i]) {
numberOfOccurrence++;
}
}
System.out.println("Our number: " + numToFind);
System.out.println("Number of times it appears: " + numberOfOccurrence);
}
}

Categories