Shuffling an ArrayList - java

I'm trying to create a method to randomly shuffle a array of primitives using a Arraylist. I was wondering if the .get(); method was the proper method to use on my Arraylist where on a normal array in a for loop it would just be array[j]; where j is the value in the for loop. Also, I'm not too familiar with Math.random(); and needed some help implementing it in this situation.
public static void selectionShuffle(int[] values) {
ArrayList<Integer> temp=new ArrayList<Integer>(52);
int rando=(int)Math.random()*52+1;
for(int counter=0;counter<temp.size();counter++){
temp.set(rando,(Integer)counter);
}
for(int counter=0;counter<values.length;counter++){
values[counter]=temp.get(counter);
}
}

Collections.shuffle(temp); is what you need
http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle%28java.util.List%29
What you may want to do is after creating the ArrayList, run a for-loop to add 52 values:
for(int i = 0; i < 52; i++){
temp.add(i);
}
Then do this:
Collections.shuffle(temp);
Print out the result to confirm

Your implementation should ensure that every index is set at least once. Your temp.set(rando,(Integer)counter) sets a random index to the value of counter. Also, you must change the value of rando with every iteration of the loop.
Math.random()
returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0.
as per Oracle, so when you multiply by 52.0 you get a value between 0 and 51.9 inclusive. When cast to an integer it is truncated to the floor of its value, giving you a range of 0 - 51 inclusive, or the size of your array.

Related

How to optimize nested for loop

Suppose for Array A of length L and skip value = k
I have to find highest possible sum in an array for a given start point.
sum should be in such a way that the initial point taken in array should be added then the next point after initial point+k skip and so on
so what is the highest possible sum?
for example array a=[1,9,2] k=2
then highest possible sum would be 9
i used two for loops
for(int i=0;i<a.length;i++){
for(int j=i;j<a.length){
sum+=a[j];
j+=k;
}
if(sum>max)
max=sum;
sum=0;
}
Though this works its complexity would be O(n^2);
how can reduce it?

ArrayList <Double> Understanding

I am doing a project on ArrayLists and mathematic methods such as sum, standard deviation and variance etc and I have come across this ArrayList<Double>.
public static double Sum(ArrayList<Double> list) {
double sum = 0;
for (int i = 0; i < list.size(); i++) {
sum = sum + list.get(i);
}
return sum;
}
I understand how ArrayList works but I am not exactly sure what is going on in this method, can anyone help me understand it a little better?
These are called Generics. Oracle has a great tutorial on it
Long story short, if you write List list = new ArrayList it would mean anything can be put in that list: toys, food, books. Kinda chaotic, huh? I bet what you'd rather have are boxes that contain only certain types of objects: a box for toys, another one for food and one more for books. That's generally what generics allow you to do. By writing List<Book> list = new ArrayList<>(), you're saying that this list can contain only books. If you try to put something else in there, you will get an error.
To sum up, in your case, method sum takes ArrayList<Double> - a list that can contain only Double objects. You can be sure that all of the elements are of that type, so you needn't check.
Look at this: ArrayList<Double> list = new ArrayList<Double>(); it creates a list that can only contain double values. A double is a variable type that can contain whole numbers and decimal numbers. So creating a list like this only allows the program to add numbers to the list: list.add(4.3);
When you call this method, you must pass an ArrayList<Double> object to it: Sum(List); Then it takes the list and adds every element of that list together into a variable called sum. After it has done that, it will return that sum. return sum;.
Here's how it does that:
for (int i = 0; i < list.size(); i++) {
sum = sum + list.get(i);
}
Its basic syntax is for(initialization; condition; iteration). When first called it will execute the initialization, then it will continue to repeat as long as the condition is true, and every time it repeats it will execute the iteration.
This specific one creates a variable called i and assigns it the value 0 for its initialization. Then for its condition it does i < list.size(), meaning that it will repeat as long as the integer value contained in i is less then the number of elements in the ArrayList. Finally, for its iteration it does i++, which will make the integer contained in i one value larger every time the thread loops.
So our i will get one value larger every time the loop iterates. Inside the loop we have sum = sum + list.get(i);. This takes the double (decimal) variable sum and adds to its current value whatever value is contained in the i (remember i has a number value) element of the ArrayList.
Click this link to learn more about for loops: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
So if the ArrayList contained the values {2, 4, 1, 5} and i contained the value 1, then calling sum = sum + list.get(i); would add the value 4 to the the value contained in sum. If i equaled 0 and we called sum = sum + list.get(i), than sum's value would be increased by 2, and it goes on like that.
These are called indexes. Indexes are numbers used to access objects in arrays or array lists. If I had an array that looked like this: int array[] = {4, 2, 5, 3}; then 4's index would be 0, 2's index would be 1, 5's index would be 2, and 3's index would be 3.
This image can give you a better understanding of indexes:

Error finding largest randomly generated double in ArrayList Java

I'm trying to get a program to work where I generate 1,000,000 random numbers between 0 and 1 and then find and print the largest number.
I've got the generator to work and managed to insert each double generated into an ArrayList but I cannot seem to figure out how to find the largest number in the list. At the moment the current code throws the error "java.lang.IndexOutOfBoundsException".
This is all probably due to me being new to the ArrayList and not being fluent with its commands and how it works but I would really appreciate some help on what I'm doing wrong here as I've been stuck for a while.
import java.util.ArrayList;
import java.util.Random;
public class milran {
public static void main(String[] args) {
Random r = new Random();
ArrayList<Double> myList = new ArrayList<Double>();
for (int i = 1; i<=1000000; i++){
double randomValue = 0.0+(1.0-0.0)*r.nextDouble();
myList.add(randomValue);
}
double max = myList.get(1);
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
if (test>max){
max = test;
}
}
System.out.println(max);
}
}
First of all take a look at the docs for java.util.Collections and java.util.ArrayList.
Secondly, the ArrayIndexOutOfBoundsException is being triggered by this...
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
...
}
This is because array indexing starts at 0, therefore the last element is myList.size() - 1. In other words, when z = myList.size(), it is out of bounds.
Also, in your first for loop, you are using i = 1; 1 <= 1000000. It makes much more sense to use i = 0; i < 1000000 as you can use i to touch each element in an array (or list).
for( i = 0; i < 1000000; i++ )
{
// do something with myArray[i]
}
Here's what I would do after the values have been inserted...
Sort the array: Collections.sort(myList);
Retrieve the last element: System.out.println( myList.get( myList.size() - 1 ) );
...and that's it.
If you need to implement the actual sort yourself then i'd consider using a primitive double array (double[]) rather than a Collection.
Otherwise, if you are using a collection, you can use a foreach loop.
for( Double d : myList ) // for each Double 'd' in myList
{
// do something with d
}
N.B. Another potential issue with this line in the second loop
double test = myList.get(z);
This automatic conversion from Double (object) to double (primitive) is called unboxing. There will be a performance cost, especially when repeated a million times. In the first loop you are converting the other way (autoboxing) – also a million times.
ArrayList start count its elements from 0. You need to replace myList.get(1) to myList.get(0), int z=2 to int z=1 and z<=myList.size() to z<myList.size().
This line: for (int z=2; z<=myList.size(); z++) { is wrong. It should be for (int z=1; z<myList.size(); z++) {.
This is because arrays and lists are 0 based, so a list of size 2 has 2 elements - index 0 and index 1. Currently you try to index into the element number equal to the size, which does not exist.
Along the same line, myList.get(1); should be myList.get(0);.
This is unrelated to your problem, but this line 0.0+(1.0-0.0)*r.nextDouble(); can be much more easily written as r.nextDouble();. I'm not sure what you were trying to do by doing 0 + 1 - 0.
As others have already pointed out, you have an error in your for-loop condition that causes the index to go out-of-bounds.
One way that you can avoid this in the future is by using Java's for-each loop syntax instead of trying to manage the index yourself.
for (Double test : myList) {
if (test>max){
max = test;
}
}
This syntax makes your intent much clearer than the traditional indexed for syntax and removes a point of potential error (managing the index and the bounds of the list) from your hands.

Integer variable not following while loop conditions

I've been having an issue with my code concerning arrays and int variables. In the section that I have issues with, I'm trying to check if an array (in which the user inputs their own integers) is in an increasing order, and if it is in an increasing order, the array is printed; if not, an error message is displayed. I am trying to do this using int two variables, one called c1 and another called orderCheck1 (both initialized to 0).
int[ ] list1 = new int [10000];
int a1 =0;
int b1 =0;
int c1 =0;
int value1;
int orderCheck1 =0;
while (a1 ==0){
if (b1 < list1.length){
value1 = scan.nextInt();
//checks to see if value entered is positive
if (value1 >=0){
list1[b1] = value1;
b1++;
}
else{
a1 =1;
}
}
}
while (c1 <(list1.length-1)){
if (list1[c1] >list1[(c1+1)]){
orderCheck1 =1;
}
c1++;
}
if (orderCheck1 ==0){
for (int i =0; i < b1; i++){
System.out.print (list1[i] + " ");
}
}
else{
System.out.println ("ERROR: One or both arrays are not in an increasing order.);
}
Basically, if a number in the array is larger than the number following it, orderCheck will become 1. Later in the code, it checks if orderCheck1 is either zero or one. If orderCheck1 is zero, then the ints in the array are printed; if it is one, then the error message is displayed.
The issue is, no matter what I enter, orderCheck1 always becomes a one, so the error message is always printed. What is wrong with my code?
Note: When the user enters values into the array, they are supposed to enter a negative number to stop entering values.
The main problem, I believe, is that you've allocated a list of 10000 elements, and you don't use them all. Java initializes the elements to 0. (Note that in some other languages, a construct like this could initialize the elements to random garbage values.)
You then write a loop that inputs numbers until the user enters a negative number. This will set the first n elements of the loop for some number n. But the remaining elements do not get chopped off the array. They are still there, and they are still 0.
This causes a problem for this loop:
while (c1 <(list1.length-1)){
if (list1[c1] >list1[(c1+1)]){
orderCheck1 =1;
}
c1++;
}
Note that list1.length is still 10000, even though the user didn't enter 10000 values. Once an array is created with new int[10000] or something like that, that fixes the .length of the array. This length cannot be changed. That means c1 will go up to 9999, regardless of how many values were entered.
Therefore, at some point, you will hit a point where you start comparing to the 0 values that got put in the array when you created it. Since all the values the user entered are positive, that means list1[c1] > list1[c1+1] will be true when list[c1] is the last value entered, because list1[c1+1] will still be 0.
The solution is that instead of letting c1 go up to list1.length-1, you have to stop it when it gets to, I think, one less than the number of user entries. It looks like you already have a b1 that counts the number of entries, so the while needs to be changed to while (c1 <some-expression-that-uses-b1). I'll let you work on getting that upper limit right.
One more thing: When you have an array like this whose size isn't really known, it's better to use an ArrayList. Unlike an int[], an ArrayList<Integer> will grow as you add elements to it, and the size() method will return the actual number of elements added.
I would suggest a method:
static boolean isAscending(int[] nums) {
for (int i = 1; i < nums.length; i++)
if (nums[i - 1] > nums[i])
return false;
return true;
}
Note that this handles the edge case of arrays of size zero or one correctly.

Explain Array[Counter]

This relates to lines 15 and 16 of Fig. 7.2 in Java How to Program, Ninth Edition by Paul Deitel.
I'm just beginning to learn Java. Can someone explain why the array[counter] output is zero for the Value column? I understand that the default value for each element in array is zero but I don't quite understand what array[counter] is doing. Is the element's default value of zero being multiplied by the counter value 0-9 through each iteration of the loop, which results in zero? Thanks.
public class InitArray
{
public static void main(String[] args)
{
int[] array; // declare array named array
array = new int[10]; // create the array object
System.out.printf("%s%8s\n", "Index", "Value"); //column headings
// output each array element's value
for(int counter = 0; counter <array.length; counter++)
System.out.printf("%5d%8d\n", counter, array[counter]);
}
}
}
I am disappointed with the down votes and harsh comments on this simple question, can't we just simply try and make the concept clear to the user
This is a simple for loop the index of the first element in the array is 0. So when the counter = 0 i.e first element, counter less than the length of the array i.e
counter<array.length , print "%5d%8d\n",
counter, array[counter] then increment counter i.e counter ++ so the value of counter is increasing which also moves the index of the array.
Hope this Helps.
This give you the element at position "Counter" in the array. If Counter is Zero you get the first result, because an array in java is Zero based. That meens that the first element in an array has the index zero.

Categories