I need to complete this task. But I am not entirely sure how to get the range into the array. I think I am supposed to use a loop somehow but I do not get it to work.
This is what I have so far:
import java.util.*;
public class A2_1
{
static Scanner x = new Scanner(System.in);
public static void main(String[] args)
{
int [] myArray = new int [1000000];
int x;
for ( x = 0; x <= 100; x++)
{
myArray [x] = x+1;
}
System.out.println(myArray);
}
}
This is the task:
"Create a program that generates 1,000,000 integer random values in the range of [1,..,100] and for any given x (between 1 and 100) taken from the user input computes "(๐๐๐ก๐๐ ๐๐ข๐๐๐๐ ๐๐ ๐๐๐๐๐๐๐ก๐ ๐๐๐ ๐ ๐กโ๐๐ ๐๐ ๐๐๐ข๐๐ ๐ก๐ ๐ฅ)/1,000,000".
This value must be comparable to the CDF of a uniform distribution U[1,100] at point x."
Im not going to give you the answer since this sounds like homework but I will help you break it down into manageable chunks.
First, generate 1000000 random numbers between 1 and 100. You were on the right track and combine it with Dawnkeepers hint. int[] randoms = new int[1000000]; is an int array with a size of 1000000. Now iterate over each index and assign it a random number(see above). Now you have an array with a million random numbers. Generating a million randoms can be a lengthy procedure depending on you machine, so yea.
Next, use the Scanner class to get the users input.(pro tip: dont use the same variable name for your scanner as your variable in the for loop lol). Now do an if check to make sure they enter a number between 1 and 100. if(val > 0 && val <= 100). If this passes, move on, else quit or prompt for user to give a new input. Using the scanner is pretty trivial so I wont go into this.
Finally, iterate through your list of randoms and keep a counter of how many numbers less then or equal to x.
int counter = 0;
for(int i = 0; i < randoms.length; i++) {
//if randoms[i] is less then or equal x, counter++
}
Take that counter and do your math, int final_answer = counter/randoms.length;
That's all that is to it. There are more efficient ways of doing this but I tried to make it simple to follow. If I misread the question, sorry.
Related
this is my first time using this site so sorry if I do something wrong,
Here's an example output of the program I'm working on, basically what's supposed to happening
1-10 |**
11-20 |****
21-30 |***
31-40 |
41-50 |******
It goes on like that till the range of 91-100. This is my code so far, I've had a couple of different ideas so the code is incomplete in some parts but I really don't know which direction to go.
import java.util.Scanner;
public class HowMany
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
int range1 = 0;
int range2 = 0;
int range3 = 0;
int range4 = 0;
int range5 = 0;
int range6 = 0;
int range7 = 0;
int range8 = 0;
int range9 = 0;
int range10 = 0;
System.out.println("Enter integers between 1 and 100 (inclusive).");
System.out.println("Enter an integer out of the range to stop.");
//Assigning the user input a variable
int userNum = input.nextInt();
while(userNum >= 1 || userNum <= 100)
{
for (int i = 0; i < value; i++)
System.out.print("*");
if(userNum >= 1 && userNum <= 10)
}
}
}
Any help will be appreciated and if I haven't mentioned anything that I should specify let me know
Thanks
I don't think it would be beneficial for you if I just write you the program because this looks like exercise or homework, so let's work this out together. The program should run like this:
USER INPUT
If: 1..100 => PUT in the correct range and do 1)
Quit
The first observation is that
int userNum = input.nextInt();
needs to happen inside a loop, called the event loop. The structure is one big loop, that does the steps as stated above.
Now there is a better way to keep track of the ranges. Whenever you see yourself writing variables like var1, var2... you are better off with an array of values. The best would be to use an array of integers, where each index represents one range, something like this:
[0] 1-10
[1] 11-20
[2] 21-30 ...
and then you can just increment the correct index.
For instance, the user types in 34, you work out with the modulo operator where it goes and insert it.
Then I am sure you can find a smart way to print the final string. The best would be to create a separate print function for the array, something like:
printCounts(int[] count) { ... }
Hope those help, feel free to ask follow-up questions :)
trying to make a Sudoku game, but stuck at checking (and fixing) duplicates in rows and columns
if (buttons.getSource().equals(newGame)) {
String diffic = JOptionPane.showInputDialog("Choose difficulty, ranging from 1-3 where 1 is easy");
int difficulty = Integer.parseInt(diffic);
ArrayList<Integer> allnumbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
if (difficulty == 1) {
for (int i = 0; i < 81; i++) {
fields.get(i).setEditable(true);
fields.get(i).setText("");
double d = Math.random();
if (d < 0.6) {
random = new Random();
Integer randomInt = allnumbers.get(random.nextInt(allnumbers.size()));
fields.get(i).setText(randomInt + "");
fields.get(i).setEditable(false);
}
}
}
As of now, it prints and stuff works, but it prints duplicated numbers.
My pseudo-way right now:
1. Find a way to print the arraylist in random order for each row. The random part is done, but it still prints duplicated numbers (im thinking to print numbers 1-9 in random order 9 times, 1 time for each row)
2. Find a way to check columns afterwards. No clue how yet, taking one problem at a time
Anyone here been around the same problems, got some tips?
Thank you :)
Create an ArrayList with the nine number.
Use Collections.shuffle(...) to shuffle the numbers in random order.
I don't really understand what's happening, if someone could explain this to me that would be great.
So, here's my code:
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
for(int i =0; i != 90; i++){
System.out.println(generate());
}
}
public static int generate(){
Random random = new Random();
int rand = random.nextInt(89)+1;
while(numbers.contains(rand)){ //<---Here seems to be my problem
rand = random.nextInt(89)+1;
System.out.println("Number: " + rand + " already exists!");
}
numbers.add(rand);
return rand;
}
I am writing a program that generates a random number from 0-90, each of which are different to the last. Unfortunately, it seems that the while loop only returns true.
You're picking from 89 random numbers (1-89 inclusive) and trying to find a unique number each time... but you're calling that 90 times. What do you expect the last iteration to do? (To put it another way - you're trying to squeeze 90 numbers into 89 slots. That's not going to work.) On the last iteration, all the possible values will already be in the list, so the condition of your while loop will always be met, whatever value is randomly chosen on each iteration.
If you wanted the numbers to be between 1 and 90 inclusive, you should be using random.nextInt(90) + 1. The argument to nextInt is the maximum number exclusive to generate - so if you call random.nextInt(3) for example, it will generate 0, 1 or 2.
(There are better ways of doing this, by the way - such as populating the list and then using Collections.shuffle - but I've concentrated on explaining the behaviour of your current code.)
You can do it easily by using collections shuffle
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i =1; i <= 90; i++){
number.add(i)
}
Collections.shuffle(numbers); // at this point the number are shuffled.
Read about shuffle.
I'm a newbie in java. I was going through some tutorials and came across this code I was not able to understand the code. Please explain what it means.
class Randoms
{
public static void main(String[] args)
{
Random rand = new Random();
int freq[] = new int[7];
for(int roll = 1; roll < 10; roll++)
{
(++freq[1 + rand.nextInt(6)]);
}
...
Line by line:
Random rand = new Random(); create new instance of the Random object, this is responsible for the creation of random numbers.
int[] freq = new int[7]; create a new int array that can store 7 elements, with indices from 0...6. It is worth noting that in Java, the ints stored in the array are initialized to 0. (This is not true for all languages, an example being C, as in C the int arrays initially store memory junk data, and must be explicitly initialized to zero).
for(int roll = 1; roll < 10; roll++) this rolls 9 times (because 1...9, but it's better practice to go from 0)
(++freq[1 + rand.nextInt(6)]); this line is something that you shouldn't ever do in this sort of fashion, because it's a monstrosity as you can see.
Do something like this:
for(int roll = 0; roll < 9; roll++)
{
int randomNumber = rand.nextInt(6); //number between 0...5
int index = 1 + randomNumber; //number between 1...6
freq[index]++; //increment the number specified by the index by 1
//nearly equivalent to freq[index] += 1;
}
So basically it randomizes the number of 9 dice throws, and stores the dice throw count (or so it calls it, frequency) in the array.
Thus, it's simulating 9 dice throws (numbers from 1...6), and each time it "rolls" a particular number, it increases the number stored in the array at that specific location.
So in the end, if you say:
for(int i = 1; i <= 6; i++)
{
System.out.println("Thrown " + freq[i] + " times of number " + i);
}
Then it will be clearly visible what's happened.
(++freq[1 + rand.nextInt(6)]); // this line of code.
The above line of code is pre-incrementing the value of freq[] array at the specified position,i.e., 1+rand.nextInt(6) --- referred value is ++freq[some-position to be evaluated] which we will evaluate below.
This rand.nextInt(6) will generate an integer number lesser than 6 and greater than 0,as it is a pre-defined method of Random Class ,randomly.We can't predict it.
And,then say number generated is 4. SO, 1+rand.nextInt(6)=5.
Hence,your code would simplify to (++freq[1 + rand.nextInt(6)]) OR `(++freq[5]).
So,simplification of this code will be equivalent to a number which equals 1 more than 6th element of array freq[].
// as freq[5] is the 6th element of the array freq[].
Also,there are some other points which SIR David Wallace suggested me to include which I would like to explain a bit more.It goes below :-
++a here ++ is called pre-increment operator and it increases the value of a by 1. There also exists an altered reverse version of it.
a++ here this ++ is called post-increment operator and it also increases the value of a by 1.But,WAIT,you might have thought that there aren't differences,but there are.
For the differences potion,I'd like to suggest to have a reading of What is the difference between pre-increment and post-increment in the cycle (for/while)?, though it is questioned in sense of C++,the same is in Java too!
// Create a new Random Object, this helps you generate random numbers
Random rand = new Random();
// create a integer array with 7 integers
int freq[] = new int[7];
// loop 9 times
for(int roll = 1; roll < 10; roll++)
{
// rand.nextInt(6) generates a number between 0 and 5 (<6). add one to it
// ++ adds one to the integer in the array that is at the index of 1-6.
(++freq[1 + rand.nextInt(6)]);
}
Some strange things about this code:
Roll loop starts at 1 then goes to 10 so at first glance it would seem to loop 10 times but actually runs 9 times.
The ++ inside the loop would generally be located on the right and could lead to some confusion among newer programmers.
freq[1 + rand.nextInt(6)] causes freq[0] to never be used.
At first a new object of the Random-Class and an array with 7 elements are created. Each element of the Array has the value 0. Inside the for-loop you randomly pick element 2 to 7 of the Array and increase its current value by 1. This is done 9 times.
Your code will never pick the first element of the Array which has the index 0.
I would rewrite the code to make it more clear:
Random rand = new Random();
int freq[] = new int[6];
int randomIndex = 0;
for(int roll = 0; roll < 9; ++roll)
{
randomIndex = rand.nextInt(6);
freq[randomIndex] = freq[randomIndex] + 1;
}
This code has not been tested, but it should basicly do the same.
I been trying to write a program that can display the fibonacci sequence. However any number I input will output 0. I suspect that it has either to do with scope of the variable or something wrong with my return. could someone look at my code and figure out if it is really those problems? I'm sorta new to java, so even the basic is difficult for me.
public static void main(String args [])
{
Scanner in = new Scanner(System.in);
int number = 0;
do{
System.out.print("Which Fibonacci Number would you like? ");
fib = in.nextInt();
}while(number < 0 || number > 71);
System.out.print("Fibonacci #"+number+" is "+fibcalc(fib)+"\n");
}
public static double fibcalc(double number)
{
double prevNumber1 = 0;
double prevNumber2 = 1;
double fib = 0;
for(int i =0; i < number; i++){
fib = prevNumber1;
prevNumber1 = prevNumber2;
prevNumber2 = fib + prevNumber2;
}
return fib;
}
made some revisions, down to one error.
error: cannot find symbol
System.out.print("Fibonacci #"+number+" is "+fibcalc(fib)+"\n");
symbol: variable fib
I got a qucik question.
can one method call upon another method for a variable? the variable is inside of the curly braces. kind of what I have in my code.it seems like most of my errors were similar to this one.
It's nothing to do with scope. Look at this code:
while(i < fib){
fib = prevNumber1;
...
}
You're using the fib variable as both "the number of iterations to execute" and "the current result". Those are two separate concepts, and should be stored in separate variables.
In particular, on the first iteration, fib will be set to 0 and i will be incremented to 1... so your loop will then terminate, returning 0.
I'd also suggest changing your parameter type to int and using long or BigInteger for the Fibonacci number variables (depending on what range you want to support). There's no part of this problem which needs non-integer values, so you shouldn't be using double at all.
Finally, I'd suggest using a for loop instead of a while loop - you want to perform a given number of iterations, and the idiomatic way of writing that in Java is:
for (int i = 0; i < count; i++) {
// whatever
}