I'm trying to create an Integer[] that is increased by a multiple of 10 for each loop. Once the Integer[] size is set I'd like it to fill up the array with random ints. I'm able to get the size of the array to increase, but the values stored within it are null.
To me this means the array is resizing correctly, but they elements aren't being assigned to anything. I'm trying a double for-loop, with the inner loop assigning the random values. If there is a better way to do this(which I'm sure there is b/c mine isn't running!) could you please help?
this is my creation of the Int[]
public class TimeComplexity {
Integer[] data;
public TimeComplexity()
{
Random random = new Random();
for (int N = 1000; N <= 1000000; N *= 10)
{
N = random.nextInt(N);
data = new Integer[N];
//checking to see if the random numbers were added.
//array size is okay but locations aren't taking a
//random number
System.out.println(Arrays.toString(data));
}
}
In case you're interested in the output for it my main class. (this isn't part of the question but if you have suggestions I'd love them!)
public class TimeComplexityApp {
private static int MAXSIZE = 1000000;
private static int STARTSIZE = 1000;
public TimeComplexityApp()
{
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
TimeComplexity time = new TimeComplexity();
System.out.println(time);
System.out.printf("%-6s %13s %13s\n\n\n","ARRAY","int","INTEGER");
for (int N = STARTSIZE; N <= MAXSIZE; N *= 10)
{
double d = 1.0;
System.out.printf("\n%-6d %15.2f %15.2f\n", N, d, d);
}
}
}
In the first source code that shows lack initialize the elements of array of integers.
data = new Integer [N]; only creates the array of integers of size N, lack include the elements in each cell of the array.
So, just need a loop to complete each element or cell array:
for (int i = 0; i <N; i ++)
data [i] = random.nextInt (N);
Now this array is complete and will not return NULL on each item.
On every iteration of your loop, you are creating a new array of random (int size) length. But you are never putting anything into it. The right way to do this is:
int[] vals = ...;
for (int i = 0; i < end - start; i++) {
if (vals.length < i; i++) {
//1. create new larger int[]
//2. copy the old array into the new array
//3. vals = yourNewArray
}
vals[i] = random.nextInt();
}
Related
I am pretty new in this world, and I must say sometimes things that looks easy are pretty harsh.
I am stuck with a task that entails dealing with an array and for-loops.
I should iterate over the array and for every iteration step print a different random string. My current code is not working correctly, the only thing I'm getting a random item and the same index printed multiple times.
My output right now:
relax
2
2
2
2
How can I fix that and get a correct randomized output?
My code:
public static void main(String[] args) {
int i;
String Cofee[] = {"pick it","drink it","relax","put it in a cup",};
java.util.Random randomGenerator = new java.util.Random();
int x = Cofee.length;
int y = randomGenerator.nextInt(x);
String frase = Cofee[y] ;
System.out.println(frase);
for(i = 0; i < Cofee.length; i++)
System.out.println(y);
}
You assign a value to y once, and you print y repeatedly. The value of y doesn't change. To do that, you would need to call randomGenerator.nextInt(x) for each iteration of the loop!
However, if you want to randomize and print the array, use:
public static void main(String[] args)
{
String[] coffee = {"pick it","drink it","relax","put it in a cup",};
// this wraps the array,
// so modifications to the list are also applied to the array
List<String> coffeeList = Arrays.asList(coffee);
Collections.shuffle(coffeeList);
for(String value : coffee)
System.out.println(value);
}
As an aside, don't use String coffee[], but use String[] coffee. Although Java allows putting the array type after the variable name, it is considered bad form.
Or use a list directly:
public static void main(String[] args)
{
List<String> coffeeList = Arrays.asList("pick it","drink it","relax","put it in a cup");
Collections.shuffle(coffeeList);
for(String value : coffeeList)
System.out.println(value);
}
For that, you can implement a shuffling algorithm.
It's not so scaring as it might sound at first. One of the famous classic shuffling algorithms, Fisher–Yates shuffle is relatively easy to grasp.
The core idea: iterate over the given array from 0 to the very last index, and for each index swap the element that corresponds to the randomly generated index between 0 and the current index (i) with the element under the current index.
Also, I would advise creating a separate array representing indices and shuffle it in order to preserve the array of string its initial state (you can omit this part and change the code accordingly if you don't need this).
That's how it might be implemented:
public static final Random RANDOM = new Random(); // we need an instance for random to generate indices
A Fisher–Yates shuffle implementation:
public static void shuffle(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = RANDOM.nextInt(i + 1); // generating index in range [0, i]
swap(arr, i, j); // swapping elements `i` and `j`
}
}
Helper-method for swapping elements:
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Usage-example:
String[] coffee = {"pick it","drink it","relax","put it in a cup"};
int[] indices = new int[coffee.length];
for (int i = 0; i < indices.length; i++) indices[i] = i; // or Arrays.setAll(indices, i -> i); if you're compfortable with lambda expressions
shuffle(indices);
for (int i = 0; i < coffee.length; i++) {
String next = coffee[indices[i]];
System.out.println(next);
}
Output:
drink it
pick it
put it in a cup
relax
So this is a coding question from school I have, I don't want to say "hey guys do my homework for me!", I actually want to understand what's going on here. We just started on arrays and they kind of confuse me so I'm looking for some help.
Here's the complete question:
Write a program in which the main method creates an array with
10 slots of type int. Assign to each slot a randomly-generated
integer. Call a function, passing it the array. The called
function should RETURN the largest integer in the array to
your main method. Your main method should display the number
returned. Use a Random object to generate integers. Create it
with
Random r = new Random(7);
Generate a random integer with
x = r.nextInt();
So, here's what I have so far:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
int x = r.nextInt();
for (int i = 0; i < count.length; i++)
{
count[i] = x;
}
}
I created that array with 10 ints, then used a for loop to assign each slot that randomly generated integer.
I'm having a hard time for what to do next, though. I'm not sure what kind of method / function to create and then how to go from there to get the largest int and return it.
Any help is really appreciated because I really want to understand what's going on here. Thank you!
Here is how to generate Random ints
public static void main(String[] args) {
int []count = new int[10];
Random r = new Random(7);
int x=0;
for (int i = 0; i < count.length; i++)
{
x = r.nextInt();
count[i] = x;
}
System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number
Here is how to make method and get max number from list.
static int maxNumber(int[] mArray){//Passing int array as parameter
int max=mArray[0];
for(int i=0;i<mArray.length;i++){
if(max<mArray[i]){//Calculating max Number
max=mArray[i];
}
}
return max;//Return Max Number.
}
Ask if anything is not clear.
This is how we make method which return int.
You can do it by using a simple for loop for the Array.
First you have to create a seperate int variable (eg: int a) and assign value zero (0) and at each of the iterations of your loop you have to compare the array item with the variable a. Just like this
a < count[i]
and if it's true you have to assign the count[i] value to the variable a . And this loop will continue until the Array's last index and you will have your largest number in the a variabe. so simply SYSOUT the a variable
Important: I didn't post the code here because I want you to understand the concept because If you understand it then you can solve any of these problems in future by your self .
Hope this helps
What you have got so far is almost correct, but you currently are using the same random number in each iteration of your for-loop. Even though you need to get a new random number for each iteration of your for-loop. This is due to how the Random object is defined. You can achieve this by changing your code the following way:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
for (int i = 0; i < count.length; i++)
{
int x = r.nextInt(); // You need to generate a new random variable each time
count[i] = x;
}
}
Note that this code is not optimal but it is the smallest change from the code you already have.
To get the largest number from the array, you will need to write another for-loop and then compare each value in the array to the largest value so far. You could do this the following way:
int largest = 0; // Assuming all values in the array are positive.
for (int i = 0; i < count.length; i++)
{
if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
largest = count[i]; // The current value is larger than any value we have seen so far,
// we therefore set our largest variable to the largest value in the array (that we currently know of)
}
}
Of course this is also not optimal and both things could be done in the same for-loop. But this should be easier to understand.
Your code should be something like this. read the comments to understand it
public class Assignment {
public static int findMax(int[] arr) { // Defiine a function to find the largest integer in the array
int max = arr[0]; // Assume first element is the largest element in the array
for (int counter = 1; counter < arr.length; counter++) // Iterate through the array
{
if (arr[counter] > max) // if element is larger than my previous found max
{
max = arr[counter]; // then save the element as max
}
}
return max; // return the maximum value at the end of the array
}
public static void main(String[] args) {
int numberofslots =10;
int[] myIntArray = new int[numberofslots]; // creates an array with 10 slots of type int
Random r = new Random(7);
for (int i = 0; i < myIntArray.length; i++) // Iterate through the array 10 times
{
int x = r.nextInt();
myIntArray[i] = x; // Generate random number and add it as the i th element of the array.
}
int result = findMax(myIntArray); // calling the function for finding the largest value
System.out.println(result); // display the largest value
}
}
Hope you could understand the code by reading comments..
This can be done in one simple for loop no need to have 2 loops
public static void main(String[] args) {
Integer[] randomArray = new Integer[10];
randomArray[0] = (int)(Math.random()*100);
int largestNum = randomArray[0];
for(int i=1; i<10 ;i++){
randomArray[i] = (int)(Math.random()*100);
if(randomArray[i]>largestNum){
largestNum = randomArray[i];
}
}
System.out.println(Arrays.asList(randomArray));
System.out.println("Largest Number :: "+largestNum);
}
Initialize max value as array's first value. Then iterate array using a for loop and check array current value with max value.
OR you can sort the array and return. Good luck!
Here's a basic method that does the same task you wish to accomplish. Left it out of the main method so there was still some challenge left :)
public int largestValue(){
int largestNum;
int[] nums = new int[10];
for (int n = 0; n < nums.length; n++){
int x = (int) (Math.random() * 7);
nums[n] = x;
largestNum = nums[0];
if (largestNum < nums[n]){
largestNum = nums[n];
}
}
return largestNum;
}
I wrote a small program.
Сondition: "Given an array of size n. Insert an element with a zero value after each negative element of the array." I solved this task using 2 ArrayList arrays. I'm wondering if it's possible to get a solution using only 1 array?
Code of the program:
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> ArrIntNum = new ArrayList<>(sizeArr); // Declare array
Random rnd = new Random();
int val;
// Filling array random elements from -20 to 20
for(int i = 0; i < sizeArr; i++){
val = -20 + rnd.nextInt(41);
ArrIntNum.add(i, val);
}
// Output array on the screen
System.out.println(ArrIntNum.toString());
ArrayList<Integer> ArrWithZeroAftNegVal = new ArrayList<>(); // Declare once more array
// Adding zero after every negative number in array ArrIntNum and write in array ArrWithZeroAftNegVal
for(int i = 0; i < sizeArr; i ++){
if(ArrIntNum.get(i) < 0) {
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
ArrWithZeroAftNegVal.add(0);
}
else
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
}
// Output edited array on the screen
System.out.println(ArrWithZeroAftNegVal.toString());
}
}
A ListIterator works quite naturally, allow addition of elements on the same array:
ListIterator<Integer> i = ArrIntNum.listIterator();
while (i.hasNext()) {
Integer value = i.next();
if (value < 0) i.add(0);
}
Like this:
import java.util.ArrayList;
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> arrIntNum = new ArrayList<Integer>(sizeArr); // Declare array
Random rnd = new Random();
// Filling array random elements from -20 to 20
for(int i = 0; i < arrIntNum.size(); i++)
arrIntNum.add(-20 + rnd.nextInt(41));
// Output array on the screen
System.out.println(arrIntNum);
// Adding zero after every negative number in array ArrIntNum
for(int i = 0; i < sizeArr; i++) {
if(arrIntNum.get(i) < 0)
arrIntNum.add(i + 1, 0);
}
// Output edited array on the screen
System.out.println(arrIntNum);
}
}
I also simplified your code for you.
I'm trying to write code that stores 50 randomly generated floating point numbers in an ArrayList. Use a regular for-loop to cycle through the values and remove any that are less than 0.5. Then use a for-each loop to print out the values that remain.
this is my code so far and I don't know where to go from here...
import java.util.ArrayList;
public class fiftyFloats {
public static void main (String [] args) {
//create a reference for the array list
ArrayList <Float> vals;
//reserve space for it in memeory
vals = new ArrayList <Float> (50);
for (int i = 0; i<vals.size(); i++){
i = new Float
}
for (Integer atPos: vals) {
System.out.println(vals.toString());
}
}
}
There are a few ways to do this depending on how you want to generate a "random" number.
java.util.Random has some functions that can be used, including "nextFloat" which returns a random values between 0 and 1 of the float type.
so
ArrayList <Float> vals = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < 50; i++) {
vals.add(rand.nextFloat());
}
Then it should be easy enough to loop through the list again and remove any number that doesn't meet your criterion. You don't need to reserve 50 spots up front in an ArrayList, that's one of the benefits of using it, that you can dynamically add to it.
Your loop as is won't work. You already defined "i" as an integer in your loop code, now you're trying to create a float with the same name. You can use "i" inside your loop, but it is going to be the "i" that you specified at "int i = 0;"
Overall it seems like you're very new and don't understand some core things about java, like how variables work. Consulting a tutor/teacher/basic text would probably helpy ou a lot.
To generate a random number you need to use the Random class.
NOTE - random.nextFloat() will only generate a number between 0.0 and 1 if you want to include larger numbers you will need to multiply it
The integer you are using to control the for loop cannot be reassigned to a float within the loop
You don't need to put arrayList.toString() in a loop
import java.util.ArrayList;
import java.util.Random;
public class fiftyFloats {
public static void main(String[] args) {
ArrayList<Float> vals = new ArrayList<Float>();
Float randomNum;
Random rand = new Random();
for (int i = 0; i < 50; i++) {
randomNum = rand.nextFloat();
if (randomNum > 0.5) {
vals.add(randomNum);
}
}
System.out.println(vals.toString());
}}
I think this is what you are trying to do here:
//create a reference for the array list
ArrayList<Float> vals;
//reserve space for it in memeory
vals = new ArrayList<Float>(50);
Random rand = new Random();
for (int i = 0; i < 50; i++) {
vals.add(rand.nextFloat());
}
for (Float val : vals) {
System.out.println(val.toString());
}
Some things to point out in your original code:
Float fl = new Float(2.2);
//create a reference for the array list
ArrayList<Float> vals;
// Here, you've set the _Capacity_, not the size.
vals = new ArrayList<Float>(50); // vals.size() => 0
// Based on above, you are essentially saying "never do these things"
// -> for (int i = 0; i < 0; i++)
for (int i = 0; i < vals.size(); i++) {
// this, if a valid expression, would have an incompatible type
// since i is of type int.
// if you were to use this, you would need to use a constructor such as
// new Float(1.2).
i = new Float
}
// In this enhanced loop, you are assigning a value from ArrayList vals
// to atPos, not the position. Since ArrayList is of type Float,
// atPos is a Float.
for (Integer atPos : vals) {
System.out.println(vals.toString());
}
Since the float values you need are not quoted between min and max then you can use nano time
Example:
List <Float> vals = new ArrayList <Float> (50);
for (int i = 0; i<vals.size(); i++){
vals.add (System.current/100.0f);
}**
I need to make a typical integer filled array with 10 random non repeating numbers from 0 to 20. Also, I need to be able to modify this so I can exclude some random numbers from 0 to 20.
How can I do this?
You can do this in three easy steps:
Build a list with all the candidate numbers you want
Use Collections.shuffle to shuffle that list
Use the n first elements of that shuffled list.
First build a list of size 20 with values 0,...,19
Then shuffle() it
And last - take the sublist containing first 10 elements.
This Method will work for you. It generate 10 unique random numbers from 0 to 20.
public static int[] getRandomArray(){
int randomCount =10;
int maxRandomNumber = 21;
if(randomCount >maxRandomNumber ){
/* if randomCount is greater than maxRandomNumber
* it will not be possible to generate randomCount
* unique numbers
**/
return null;
}
HashMap<Integer, Integer> duplicateChecker = new HashMap<Integer, Integer>();
int[] arr = new int[randomCount ];
int i = 0;
while(i<randomCount ){
// Generate random between 0-20, higher limit 21 is excluded
int random = new Random().nextInt(maxRandomNumber );
if(duplicateChecker.containsKey(random)==false){
duplicateChecker.put(random, random);
arr[i]=random;
i++;
}
}
return arr;
}
* Edited: To make the method deterministic. And Avoid the chance of infinite loop
public static int[] getRandomArray(){
int randomCount =10;
int maxRandomNumber = 21;
if(randomCount >maxRandomNumber ){
/* if randomCount is greater than maxRandomNumber
* it will not be possible to generate randomCount
* unique numbers
**/
return null;
}
ArrayList<Integer> arrayList = new ArrayList<Integer>();
// Generate an arrayList of all Integers
for(int i=0;i<maxRandomNumber;i++){
arrayList.add(i);
}
int[] arr = new int[randomCount ];
for(int i=0;i<randomCount;i++){
// Generate random between 0-20, higher limit 21 is excluded
int random = new Random().nextInt(arrayList.size());
// Remove integer from location 'random' and assign it to arr[i]
arr[i]=arrayList.remove(random);
}
return arr;
}
What about making an arraylist of numbers upto 20, and after each random number call you remove the number from the list and into the array.
example
Random r = new Random();
int[] myArray = new int[10];
ArrayList<Integer> numsToChoose = new ArrayList<Integer>();
int counter = 0;
for(int i = 0; i < 21; i++)
{
numsToChoose.add(i);
}
while(numsToChoose.size() > 11)
{
myArray[counter] = numsToChoose.remove(r.nextInt(numsToChoose.size()));
counter++;
}
That way it should only loop 10 times, I may be wrong though.
Hope it helps
EDIT: And in order to modify this to exclude certain numbers, you would just need a method that takes an array that contains said numbers as a parameter, and loop through it removing each number from the arraylist before you generate your random numbers.
Most of the other responses offer the Collections.shuffle method as a solution. Another way, which is theoretically faster is the following:
First lets build the list:
public class RandomWithoutReplacement {
private int [] allowableNumbers;
private int totalRemaining;
/**
* #param upperbound the numbers will be in the range from 0 to upperbound (exclusive).
*/
public RandomWithoutReplacement ( int upperbound ) {
allowableNumbers = new int[ upperbound ];
for (int i = 0; i < upperbound; i++) {
allowableNumbers[i] = i;
}
totalRemaining = upperbound;
}
}
Next lets consider what we need to do when we need to get the next number.
1) When we request another number, it must be chosen from any one of the available, uniformly.
2) Once it is chosen, it must not repeat again.
Here is what we can do:
First, choose a number at random from the allowableNumbers array.
Then, remove it from the array.
Then remove the number at the end of the array, and place it in the position of the number we are to return.
This ensures all of the 2 conditions we have placed.
public int nextRandom () {
//Get a random index
int nextIndex = (int) ( Math.random() * totalRemaining );
//Get the value at that index
int toReturn = allowableNumbers [ nextIndex ];
//Find the last value
int lastValue = allowableNumbers [ totalRemaining - 1 ];
//Replace the one at the random index with the last one
allowableNumbers[ nextIndex ] = lastValue;
//Forget about the last one
totalRemaining -- ;
return toReturn;
}
With that, your function is almost complete.
I would add a couple more things just in case:
public boolean hasNext () {
return totalRemaining > 0;
}
And at the beginning of the actual function:
public int nextRandom () {
if (! hasNext() )
throw new IllegalArgumentException();
// same as before...
}
That should be it!
Well, I could't help it not to post my solution which is storing a sequance of numbers into twice as many random locations first. Then compacts it into the resultting array.
int[] myRandomSet = generateNumbers(20, 10);
...
public int[] generateNumbers(int range, int arrayLenght){
int tempArray[];
int resultArray[];
int doubleLocations;
Random generator = new Random();
doubleLocations = range * 2;
tempArray = new int[doubleLocations];
resultArray = new int[arrayLenght];
for (int i=1; i<=range; i++){
if (i != 5 && i != 13){ //exclude some numbers
do{
r = generator.nextInt(doubleLocations);
}while(tempArray[r]!=0);
tempArray[r] = i; //enter the next number from the range into a random position
}
}
int k = 0;
for (int i=0; i<(doubleLocations); i++){
if(tempArray[i] != 0){
resultArray[k] = tempArray[i]; //compact temp array
k++;
if (k == arrayLenght) break;
}
}
return resultArray;
}