Home > Archive > Java Help > March 2008 > Math.random()
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
|
| hi,
am trying to find out how to use random() method.. what is construction
if, say, I want to generate a random no. betw. 1 and 100..
here, http://java.sun.com/j2se/1.4.2/docs...ath.html#random()
it does not show how this method is used exactly (i.e., what
construction is exactly... these detailed method-sections should show
exact constructions/examples of how method is used..)
this method apparently takes no arguments, so how do you tell it in what
range (betw what nos.) you want the random no. generated?
int randomNo = 0;
randomNo = Math.random(a no. betw. 1 and 100...) // how do you do
this????
AND: if I want to look up java tutorial on this, how do you search for
class, method, etc.. you want here?
http://java.sun.com/docs/books/tutorial/
(a few years ago I had a pg bookmarked in java.sun that was a huge index
to all aspects of Java language, so all you had to do was search for
term you wanted by doing ctrl-find on the browser (or scrolling down..)
(also, this tutorial is for Java 6, do they still have tutorial for
1.5??)
thank you...
| |
| Stanimir Stamenkov 2008-02-25, 7:23 pm |
| Mon, 25 Feb 2008 16:39:42 -0500, /maya/:
> am trying to find out how to use random() method.. what is construction
> if, say, I want to generate a random no. betw. 1 and 100..
>
> this method apparently takes no arguments, so how do you tell it in what
> range (betw what nos.) you want the random no. generated?
>
> int randomNo = 0;
> randomNo = Math.random(a no. betw. 1 and 100...) // how do you do
> this????
randomNo = Math.random() * 100 + 1;
As Math.random() returns a value greater than or equal to 0.0 and
less than 1.0, multiplying it by 100 (or whatever upper bound) will
return value greater than or equal to 0.0 and less than 100.0 (or
the other upper bound chosen). Casting the result to an int will
strip the fraction part so if you want a result of 0 to 100
inclusive you may simply multiply the Math.random() result by 101.
> AND: if I want to look up java tutorial on this, how do you search for
> class, method, etc.. you want here?
> http://java.sun.com/docs/books/tutorial/
At least you may try Google:
http://www.google.com/search?q=math...s%2Ftutorial%2F
(using a "site:java.sun.com/docs/books/tutorial/" (w/o the quotes)
token in the query).
--
Stanimir
| |
|
| maya wrote:
> hi,
>
> am trying to find out how to use random() method.. what is construction
> if, say, I want to generate a random no. betw. 1 and 100..
>
> here, http://java.sun.com/j2se/1.4.2/docs...ath.html#random()
> it does not show how this method is used exactly (i.e., what
> construction is exactly... these detailed method-sections should show
> exact constructions/examples of how method is used..)
>
> this method apparently takes no arguments, so how do you tell it in what
> range (betw what nos.) you want the random no. generated?
>
>
> int randomNo = 0;
> randomNo = Math.random(a no. betw. 1 and 100...) // how do you do
> this????
>
>
> AND: if I want to look up java tutorial on this, how do you search for
> class, method, etc.. you want here?
> http://java.sun.com/docs/books/tutorial/
> (a few years ago I had a pg bookmarked in java.sun that was a huge index
> to all aspects of Java language, so all you had to do was search for
> term you wanted by doing ctrl-find on the browser (or scrolling down..)
> (also, this tutorial is for Java 6, do they still have tutorial for
> 1.5??)
>
> thank you...
what I actually want is to generate a LIST of nos, between 1 and a
variable.. I found this way:
for (int i=1; i <= iPhotosL; i++) {
out.println((int)(Math.random()*iPhotosL) + " -- random
no.<br>");
}
however, I would like to tell it to NOT REPEAT a no. in the list, i.e.,
what I want is a list betw. 1 and a given no., but that no number
appears more than once in the list.. is this possible??
(I want to have option of displaying photos in a random order instead of
in order of img-names (1.jpg, 2.jpg, 3.jpg, etc..))
thank you very much..
| |
| Hal Rosser 2008-02-25, 7:23 pm |
|
"maya" <maya778899@yahoo.com> wrote in message news:fpvdus$8de$1@aioe.org...
> maya wrote:
>
> what I actually want is to generate a LIST of nos, between 1 and a
> variable.. I found this way:
>
> for (int i=1; i <= iPhotosL; i++) {
> out.println((int)(Math.random()*iPhotosL) + " -- random
> no.<br>");
> }
>
> however, I would like to tell it to NOT REPEAT a no. in the list, i.e.,
> what I want is a list betw. 1 and a given no., but that no number appears
> more than once in the list.. is this possible??
>
> (I want to have option of displaying photos in a random order instead of
> in order of img-names (1.jpg, 2.jpg, 3.jpg, etc..))
>
> thank you very much..
Create a boolean array 0 to <your max value> and Each time you select a
number - set the the array element that has that index to true but keep
another variable for the count of how many you want - but only increment the
count if the array element was false before you set it to true.
Do the loop until the count equals the number you of picks you wanted.
You're welcome
| |
|
| Hal Rosser wrote:
> "maya" <maya778899@yahoo.com> wrote in message news:fpvdus$8de$1@aioe.org...
>
> Create a boolean array 0 to <your max value> and Each time you select a
> number - set the the array element that has that index to true but keep
> another variable for the count of how many you want - but only increment the
> count if the array element was false before you set it to true.
> Do the loop until the count equals the number you of picks you wanted.
> You're welcome
>
>
oh brother... I think get gist of what you're saying.. will try
it....;) thank you very much.. (boolean array.... hmmm.. not sure if
I've ever even seen code for a boolean array...;)
| |
| Jeff Higgins 2008-02-25, 7:23 pm |
|
maya wrote
> hi,
>
> am trying to find out how to use random() method.. what is construction
> if, say, I want to generate a random no. betw. 1 and 100..
>
If you're not constrained to Math.random(), see this.
<http://mindprod.com/jgloss/pseudorandom.html#LOWHIGH>
| |
| Patricia Shanahan 2008-02-25, 7:23 pm |
| maya wrote:
.....
> however, I would like to tell it to NOT REPEAT a no. in the list, i.e.,
> what I want is a list betw. 1 and a given no., but that no number
> appears more than once in the list.. is this possible??
.....
I would load up an ArrayList, with the Integer numbers from 1 to N, and
run Collections.shuffle on it.
Patricia
| |
| Patricia Shanahan 2008-02-25, 7:23 pm |
| Hal Rosser wrote:
> "maya" <maya778899@yahoo.com> wrote in message news:fpvdus$8de$1@aioe.org...
>
> Create a boolean array 0 to <your max value> and Each time you select a
> number - set the the array element that has that index to true but keep
> another variable for the count of how many you want - but only increment the
> count if the array element was false before you set it to true.
> Do the loop until the count equals the number you of picks you wanted.
> You're welcome
>
>
OK if you only want the first few results, but can get very inefficient
if you need all or most of the numbers.
Patricia
| |
| Daniel Pitts 2008-02-25, 7:23 pm |
| maya wrote:
> maya wrote:
>
> what I actually want is to generate a LIST of nos, between 1 and a
> variable.. I found this way:
>
> for (int i=1; i <= iPhotosL; i++) {
> out.println((int)(Math.random()*iPhotosL) + " -- random
> no.<br>");
> }
>
> however, I would like to tell it to NOT REPEAT a no. in the list, i.e.,
> what I want is a list betw. 1 and a given no., but that no number
> appears more than once in the list.. is this possible??
>
> (I want to have option of displaying photos in a random order instead of
> in order of img-names (1.jpg, 2.jpg, 3.jpg, etc..))
>
> thank you very much..
>
>
>
Try putting the photos into a List object, and then calling
Collections.shuffle() with that list object as the parameter.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
| |
| Jeff Higgins 2008-02-25, 7:23 pm |
|
maya wrote:
> maya wrote:
> what I actually want is to generate a LIST of nos, between 1 and a
> variable.. I found this way:
>
>
> however, I would like to tell it to NOT REPEAT a no. in the list, i.e.,
> what I want is a list betw. 1 and a given no., but that no number appears
> more than once in the list.. is this possible??
>
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class Test {
public static void main(String[] args) {
List<Integer> randomIntegers =
new ArrayList<Integer>
(NoDuplicateListOfRandomIntegers.
getRandomList(100, 1, 999));
for(int i = 0; i < randomIntegers.size(); i++) {
System.out.println(i + " " + randomIntegers.get(i));
}
}
public static class NoDuplicateListOfRandomIntegers {
private static Random rand = new Random();
public static List<Integer> getRandomList(int size, int low, int high) {
if(high <= size) {
throw new IllegalArgumentException();
}
Set<Integer> integers = new HashSet<Integer>();
while(integers.size() < size) {
integers.add(rand.nextInt(high - low + 1 ) + low);
}
List<Integer> ret = new ArrayList<Integer>();
ret.addAll(integers);
return ret;
}
}
}
| |
| RedGrittyBrick 2008-02-25, 7:23 pm |
| Hal Rosser wrote:
> "maya" <maya778899@yahoo.com> wrote in message news:fpvdus$8de$1@aioe.org...
>
> Create a boolean array 0 to <your max value> and Each time you select a
> number - set the the array element that has that index to true but keep
> another variable for the count of how many you want - but only increment the
> count if the array element was false before you set it to true.
> Do the loop until the count equals the number you of picks you wanted.
> You're welcome
>
>
If you want integers 1-n in random order, I believe the usual procedure
is to create an ordered array of n integers 1..n, then iterate through
positions 1-n of the array and for each position generate a random
number between the current position and n, swap the number at the
current position with the number at the random position.
The above is far more efficient than repeatedly picking a random number
and ignoring duplicates, because towards the end you are mostly picking
duplicates. For small n I imagine this doesn't matter, other than
aesthetically.
| |
| Jeff Higgins 2008-02-25, 7:23 pm |
|
Daniel Pitts wrote:
> maya wrote:
> Try putting the photos into a List object, and then calling
> Collections.shuffle() with that list object as the parameter.
>
A clear winner. :-))
| |
| Jeff Higgins 2008-02-25, 7:23 pm |
|
Jeff Higgins wrote:
>
>
Oops! having just read RedGrittyBrick's & Patricia's comments;
with a size argument of 1,000,000 I get +14 million iterations.
Scratch this one. :(
Thanks.
> public static class NoDuplicateListOfRandomIntegers {
>
> private static Random rand = new Random();
>
> public static List<Integer> getRandomList(int size, int low, int high)
> {
> if(high <= size) {
> throw new IllegalArgumentException();
> }
> Set<Integer> integers = new HashSet<Integer>();
> while(integers.size() < size) {
> integers.add(rand.nextInt(high - low + 1 ) + low);
> }
> List<Integer> ret = new ArrayList<Integer>();
> ret.addAll(integers);
> return ret;
> }
> }
> }
>
>
| |
|
| maya wrote:
> oh brother... I think get gist of what you're saying.. will try
> it....;) thank you very much.. (boolean array.... hmmm.. not sure if
> I've ever even seen code for a boolean array...;)
package testit;
import java.util.Random;
import java.util.Set;
import java.util.HashSet;
public class Scrambler
{
private final Random rand = new Random();
public Set <Integer> scrambleEggs( int upper, int count )
{
Set <Integer> chosen = new HashSet <Integer> ( count * 4 / 3 + 1 );
boolean [] selected = new boolean [ upper ];
while ( count > 0 )
{
int indx = rand.nextInt( upper );
if ( ! selected [ indx ] )
{
if ( chosen.add( indx ))
{
--count;
}
selected [ indx ] = true;
}
}
return chosen;
}
}
Untried, untested. (Pseudo-)Non-deterministic run time.
The bizarre reference to chosen.add()'s return value is a hint that one
doesn't really need the boolean array if one is using a Set, in that Set
guarantees uniqueness of its values with respect to equals(), and add() tells
you if the item was not already in the Set. This could really help if 'upper'
has a large value.
Things get trickier if you want multi-threaded use or a deterministic number
of times through the loop.
--
Lew
| |
|
| RedGrittyBrick wrote:
> If you want integers 1-n in random order, I believe the usual procedure
> is to create an ordered array of n integers 1..n, then iterate through
> positions 1-n of the array and for each position generate a random
> number between the current position and n, swap the number at the
> current position with the number at the random position.
It sounds like the OP is asking for something different: A collection of n
unique numbers drawn from the range 0 to u (or equivalently, 1 to u + 1), u >=
n-1. Order doesn't seem to matter.
But the OP also said:
> (I want to have option of displaying photos in a random order
> instead of in order of img-names (1.jpg, 2.jpg, 3.jpg, etc..))
That means the OP can recast the *goal* to what RedGrittyBrick said. Present
the n unique image names in a RandomAccess like ArrayList, or in an array.
Now the OP's goal reduces to randomly ordering the n indexes into the
RandomAccess, taken over the range 0 to n, not 1 to n + 1. Present the images
from the RandomAccess in the random order generated by RedGrittyBrick's algorithm.
A classic case of recasting the tactic - picking random integers with no
duplicates - to the goal - presenting a known list of images in random order -
in order to find a better tactic - using the 0 to n (un)sorting algorithm.
--
Lew
| |
| Patricia Shanahan 2008-02-25, 10:19 pm |
| Lew wrote:
> maya wrote:
>
> package testit;
> import java.util.Random;
> import java.util.Set;
> import java.util.HashSet;
>
> public class Scrambler
> {
> private final Random rand = new Random();
>
> public Set <Integer> scrambleEggs( int upper, int count )
> {
> Set <Integer> chosen = new HashSet <Integer> ( count * 4 / 3 + 1 );
> boolean [] selected = new boolean [ upper ];
>
> while ( count > 0 )
> {
> int indx = rand.nextInt( upper );
> if ( ! selected [ indx ] )
> {
> if ( chosen.add( indx ))
> {
> --count;
> }
> selected [ indx ] = true;
> }
> }
> return chosen;
> }
> }
>
> Untried, untested. (Pseudo-)Non-deterministic run time.
>
> The bizarre reference to chosen.add()'s return value is a hint that one
> doesn't really need the boolean array if one is using a Set, in that Set
> guarantees uniqueness of its values with respect to equals(), and add()
> tells you if the item was not already in the Set. This could really
> help if 'upper' has a large value.
>
> Things get trickier if you want multi-threaded use or a deterministic
> number of times through the loop.
>
Why have the boolean array at all? The technique only makes sense if
upper is very large compared with count, so that the collision risk is
very low, and in that case it is bad to have to create an array with
upper elements. Here's a simplified, though still untested, version.
package testit;
import java.util.Random;
import java.util.Set;
import java.util.HashSet;
public class Scrambler
{
private final Random rand = new Random();
public Set <Integer> scrambleEggs( int upper, int count )
{
Set <Integer> chosen = new HashSet <Integer> ( count * 4 / 3 + 1 );
while ( chosen.size() < count )
{
chosen.add(Integer.valueOf(rand.nextInt( upper ));
}
return chosen;
}
}
Testing chosen.size(), rather than counting add attempts, automatically
deals with duplicates, because adding a duplicate does not increase the
size of the Set.
Patricia
| |
| rossum 2008-02-26, 8:41 am |
| On Mon, 25 Feb 2008 16:39:42 -0500, maya <maya778899@yahoo.com> wrote:
Others have dealt with your Math.random() question.
>AND: if I want to look up java tutorial on this, how do you search for
>class, method, etc.. you want here?
>http://java.sun.com/docs/books/tutorial/
>(a few years ago I had a pg bookmarked in java.sun that was a huge index
>to all aspects of Java language, so all you had to do was search for
>term you wanted by doing ctrl-find on the browser (or scrolling down..)
> (also, this tutorial is for Java 6, do they still have tutorial for
>1.5??)
>
>
>thank you...
I suspect that you are talking about the Sun Java reference site:
http://java.sun.com/javase/reference/index.jsp
or possibly just the API documentation:
http://java.sun.com/javase/6/docs/api/ (v6) or
http://java.sun.com/j2se/1.5.0/docs/api/ (v5).
The API documentation is available as download from Sun's site.
rossum
| |
| Roedy Green 2008-02-27, 5:22 am |
| On Mon, 25 Feb 2008 16:39:42 -0500, maya <maya778899@yahoo.com> wrote,
quoted or indirectly quoted someone who said :
>am trying to find out how to use random() method.. what is construction
>if, say, I want to generate a random no. betw. 1 and 100
see http://mindprod.com/jgloss/pseudorandom.html
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
| |
| Roedy Green 2008-02-27, 5:22 am |
| On Mon, 25 Feb 2008 23:54:49 +0200, Stanimir Stamenkov
<s7an10@netscape.net> wrote, quoted or indirectly quoted someone who
said :
>
>As Math.random() returns a value greater than or equal to 0.0 and
>less than 1.0, multiplying it by 100 (or whatever upper bound) will
>return value greater than or equal to 0.0 and less than 100.0 (or
>the other upper bound chosen). Casting the result to an int will
>strip the fraction part so if you want a result of 0 to 100
>inclusive you may simply multiply the Math.random() result by 101.
That is not a good thing to do. See
http://mindprod.com/jgloss/pseudorandom.html for why. Use
random.nextInt( n ) instead.
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
| |
|
| thank you all very much for yr responses.. actually I decided that
instead of displaying the images at random in server (which means every
time user comes back photos would be displayed in a different order, I'm
not sure I want that) I want do do the following:
when photos first come in from memory card they are named thus:
DSC_0001.JPG, DSC_0002.JPG, DSC_0003.JPG, etc...
so instead of dislaying images at random in actual site I want to use
random function when RENAMING images (locally, w/stand-alone class)
before uploading them.. now I have written a class for this, thus:
import java.io.*;
public class Rename {
public static void main(String[] args) {
int posDot;
String _temp = "";
String no = "";
// if no arg passed start naming of imgs @ "1"
// else start at whatever no. is passed to class...
if (null == args || args.length < 1) {
no = "1";
} else {
no = args[0];
}
int iNo = Integer.parseInt(no);
File directory = new File(System.getProperty("user.dir"));
String[] textFileNames = directory.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".JPG");
}
});
for (int j=0; j < textFileNames.length+1; j++) {
// System.out.print(textFileNames[j] + "\n");
}
for (int i = 0; i < textFileNames.length; ++i) {
File oldFile = new File(textFileNames[i]);
posDot = textFileNames[i].indexOf(".");
_temp = textFileNames[i].substring(0,posDot);
// System.out.print(_temp + "\n");
File newFile = new File(i+iNo + ".jpg");
oldFile.renameTo(newFile);
}
}
}
(adapted from example I found here:
http://www.zanthan.com/itymbi/archives/000805.html)
I would like to use random function to rename imgs at random (i.e., so
instead of 1.jpg, 2.jpg, etc, in same order as orig's ones, I would like
to do, say, name first img a number, 2nd image another number, but at
random.. )
(reason sometimes I'll need to start renaming at @ no. diff from "1" is
that in each dir I have imgs from one mem. card, and thus can have one
img named DSC_0002.JPG in two diff folders b/c they came from diff
cards, so can't just put all imgs from all cards in one folder.. so,
after renaming, will have in 1st folder 1.jpg, etc.. thru, say, 15.jpg,
then in second folder need to start at 16.jpg.. etc.. and if I want to
shuffle among all imgs (not just imgs in one folder) I need to do this..
I hope this makes sense..)
thank you very much..
Lew wrote:
> maya wrote:
>
> package testit;
> import java.util.Random;
> import java.util.Set;
> import java.util.HashSet;
>
> public class Scrambler
> {
> private final Random rand = new Random();
>
> public Set <Integer> scrambleEggs( int upper, int count )
> {
> Set <Integer> chosen = new HashSet <Integer> ( count * 4 / 3 + 1 );
> boolean [] selected = new boolean [ upper ];
>
> while ( count > 0 )
> {
> int indx = rand.nextInt( upper );
> if ( ! selected [ indx ] )
> {
> if ( chosen.add( indx ))
> {
> --count;
> }
> selected [ indx ] = true;
> }
> }
> return chosen;
> }
> }
>
> Untried, untested. (Pseudo-)Non-deterministic run time.
>
> The bizarre reference to chosen.add()'s return value is a hint that one
> doesn't really need the boolean array if one is using a Set, in that Set
> guarantees uniqueness of its values with respect to equals(), and add()
> tells you if the item was not already in the Set. This could really
> help if 'upper' has a large value.
>
> Things get trickier if you want multi-threaded use or a deterministic
> number of times through the loop.
>
| |
|
| Jeff Higgins wrote:
> Daniel Pitts wrote:
> A clear winner. :-))
>
>
ok, am trying to do this now.. acc to docs it's like a vector except
"synchronized" (not sure what this means..) only thing in Vector you add
elements thus:
vPhotos.addElement(imgsList[i]);
but am having problems here:
ArrayList photos = new ArrayList();
File directory = new File(System.getProperty("user.dir"));
String[] textFileNames = directory.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".jpg") || name.endsWith( ".JPG");
}
});
for (int i=0; i < textFileNames.length+1; i++) {
photos.add(i); // error here...
}
how do I convert this "i" to an object (since this method takes only obj
as argument..)
and then how do I apply Collections.shuffle() to it??
photos.Collections.shuffle() ?? I dont think so....;)
I really need this today, for some photos I'm putting together for a
friend overseas, sending with a friend who travels today....
thank you very much..
| |
|
| maya wrote:
> Jeff Higgins wrote:
>
> ok, am trying to do this now.. acc to docs it's like a vector except
> "synchronized" (not sure what this means..) only thing in Vector you add
> elements thus:
>
> vPhotos.addElement(imgsList[i]);
>
> but am having problems here:
>
> ArrayList photos = new ArrayList();
>
> File directory = new File(System.getProperty("user.dir"));
> String[] textFileNames = directory.list(new FilenameFilter() {
> public boolean accept(File dir, String name) {
> return name.endsWith(".jpg") || name.endsWith( ".JPG");
> }
> });
>
> for (int i=0; i < textFileNames.length+1; i++) {
> photos.add(i); // error here...
> }
>
>
> how do I convert this "i" to an object (since this method takes only obj
> as argument..)
>
> and then how do I apply Collections.shuffle() to it??
>
> photos.Collections.shuffle() ?? I dont think so....;)
>
> I really need this today, for some photos I'm putting together for a
> friend overseas, sending with a friend who travels today....
>
> thank you very much..
>
>
>
ok, I think got Collections.shuffle() part..
Collections.shuffle(photos, new Random());
only problem now is how to add all nos. to ArrayList (this has to be 1.4
construction, not 1.5..)
and then how to go from Collections.shuffle to this:
for (int i = 0; i < textFileNames.length; ++i) {
File oldFile = new File(textFileNames[i]);
posDot = textFileNames[i].indexOf(".");
_temp = textFileNames[i].substring(0,posDot);
File newFile = new File(i+1 + ".jpg");
oldFile.renameTo(newFile);
}
so imgs are named with nos. at random (i.e., so imgs, after renamed, are
in diff order from orig ones..)
thank you....
| |
| Jeff Higgins 2008-03-07, 7:23 pm |
|
maya wrote:
> maya wrote:
photos.add(new File(i));
[color=darkred]
> ok, I think got Collections.shuffle() part..
>
> Collections.shuffle(photos, new Random());
>
> only problem now is how to add all nos. to ArrayList (this has to be 1.4
> construction, not 1.5..)
>
> and then how to go from Collections.shuffle to this:
>
> for (int i = 0; i < textFileNames.length; ++i) {
> File oldFile = new File(textFileNames[i]);
> posDot = textFileNames[i].indexOf(".");
> _temp = textFileNames[i].substring(0,posDot);
> File newFile = new File(i+1 + ".jpg");
> oldFile.renameTo(newFile);
> }
>
> so imgs are named with nos. at random (i.e., so imgs, after renamed, are
> in diff order from orig ones..)
>
>
> thank you....
>
| |
| Jeff Higgins 2008-03-07, 7:23 pm |
|
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
public class ShuffleImages {
public static void main(String[] args) {
ArrayList photos = new ArrayList();
File directory = new File(System.getProperty("user.dir"));
String[] textFileNames = directory.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".jpg") || name.endsWith(".JPG");
}
});
for (int i = 0; i < textFileNames.length; i++) {
photos.add(new File(textFileNames[i]));
}
Collections.shuffle(photos);
}
}
| |
|
| Jeff Higgins wrote:
> import java.io.File;
> import java.io.FilenameFilter;
> import java.util.ArrayList;
> import java.util.Collections;
>
> public class ShuffleImages {
>
> public static void main(String[] args) {
>
> ArrayList photos = new ArrayList();
> File directory = new File(System.getProperty("user.dir"));
>
> String[] textFileNames = directory.list(new FilenameFilter() {
> public boolean accept(File dir, String name) {
> return name.endsWith(".jpg") || name.endsWith(".JPG");
> }
> });
>
> for (int i = 0; i < textFileNames.length; i++) {
>
> photos.add(new File(textFileNames[i]));
>
> }
>
> Collections.shuffle(photos);
>
> }
> }
>
>
thank you very much.. I have incorporated this code into my class to
rename files, it now looks thus, and get no compile or runtime errors,
but it's still not doing it at random, i.e., what I want:
if I have: DSC_0184.JPG, DSC_0185.JPG, DSC_0186.JPG, DSC_0187.JPG,
DSC_0188.JPG, DSC_0189.JPG, DSC_0190.JPG, DSC_0191.JPG, DSC_0192.JPG,
I want, for example: 8th img in this list to be called 1.jpg, 4nd img to
be called 3.jpg, sixth image to be called 10.jpg, etc.. so once they
are renamed they are ordered at random vis-a-vis orig order.. what I
have now after incorporating yr code:
---------------
public class renameRandom {
public static void main(String[] args) {
int posDot;
String _temp = "";
String no = "";
File directory = new File(System.getProperty("user.dir"));
String[] textFileNames = directory.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".jpg") || name.endsWith( ".JPG");
}
});
ArrayList photos = new ArrayList();
for (int i=0; i < textFileNames.length; i++) {
photos.add(new File(textFileNames[i]));
}
Collections.shuffle(photos, new Random());
for (int i = 0; i < textFileNames.length; ++i) {
File oldFile = new File(textFileNames[i]);
posDot = textFileNames[i].indexOf(".");
_temp = textFileNames[i].substring(0,posDot);
File newFile = new File(i+1 + ".jpg");
oldFile.renameTo(newFile);
}
}
}
still trying to incorporate random "feature" into this renaming class..
maybe I need to modify this line?
File newFile = new File(i+1 + ".jpg");
so it when renaming imgs it goes thru the imgs at random instead of how
they are ordered originally??
thank you very much..
| |
|
| maya wrote:
> Jeff Higgins wrote:
>
> thank you very much.. I have incorporated this code into my class to
> rename files, it now looks thus, and get no compile or runtime errors,
> but it's still not doing it at random, i.e., what I want:
>
> if I have: DSC_0184.JPG, DSC_0185.JPG, DSC_0186.JPG, DSC_0187.JPG,
> DSC_0188.JPG, DSC_0189.JPG, DSC_0190.JPG, DSC_0191.JPG, DSC_0192.JPG,
>
> I want, for example: 8th img in this list to be called 1.jpg, 4nd img to
> be called 3.jpg, sixth image to be called 10.jpg, etc.. so once they
> are renamed they are ordered at random vis-a-vis orig order.. what I
> have now after incorporating yr code:
>
> ---------------
>
> public class renameRandom {
>
> public static void main(String[] args) {
>
> int posDot;
> String _temp = "";
> String no = "";
>
> File directory = new File(System.getProperty("user.dir"));
> String[] textFileNames = directory.list(new FilenameFilter() {
> public boolean accept(File dir, String name) {
> return name.endsWith(".jpg") || name.endsWith( ".JPG");
> }
> });
>
> ArrayList photos = new ArrayList();
> for (int i=0; i < textFileNames.length; i++) {
> photos.add(new File(textFileNames[i]));
> }
> Collections.shuffle(photos, new Random());
>
> for (int i = 0; i < textFileNames.length; ++i) {
> File oldFile = new File(textFileNames[i]);
> posDot = textFileNames[i].indexOf(".");
> _temp = textFileNames[i].substring(0,posDot);
> File newFile = new File(i+1 + ".jpg");
> oldFile.renameTo(newFile);
> }
>
> }
>
> }
>
> still trying to incorporate random "feature" into this renaming class..
>
> maybe I need to modify this line?
>
> File newFile = new File(i+1 + ".jpg");
>
> so it when renaming imgs it goes thru the imgs at random instead of how
> they are ordered originally??
>
> thank you very much..
so I figured after shuffling them I need to put them in an array.. yes??
so I now have:
ArrayList photos = new ArrayList();
for (int i=0; i < textFileNames.length; i++) {
photos.add(new File(textFileNames[i]));
}
Collections.shuffle(photos, new Random());
String[] photosArr = new String[photos.size()];
photos.toArray(photosArr); // runtime error on this line..
for (int i = 0; i < photosArr.length; ++i) {
File oldFile = new File(photosArr[i]);
posDot = photosArr[i].indexOf(".");
_temp = photosArr[i].substring(0,posDot);
File newFile = new File(i+1 + ".jpg");
oldFile.renameTo(newFile);
}
it compiles fine, but get a runtime error, thus:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method
at java.util.ArrayList.toArray(Unknown Sour
at renameRandom.main(renameRandom.java:40)
line 40 is: photos.toArray(photosArr);
( I looked up ArrayList in docs, it looks like it can be converted to an
array in same way as Vector can, and I have done it w/Vector before..)
thank you..
| |
| Jeff Higgins 2008-03-07, 7:23 pm |
|
maya wrote:
> Jeff Higgins wrote:
>
> thank you very much.. I have incorporated this code into my class to
> rename files, it now looks thus, and get no compile or runtime errors, but
> it's still not doing it at random, i.e., what I want:
>
> if I have: DSC_0184.JPG, DSC_0185.JPG, DSC_0186.JPG, DSC_0187.JPG,
> DSC_0188.JPG, DSC_0189.JPG, DSC_0190.JPG, DSC_0191.JPG, DSC_0192.JPG,
>
> I want, for example: 8th img in this list to be called 1.jpg, 4nd img to
> be called 3.jpg, sixth image to be called 10.jpg, etc.. so once they are
> renamed they are ordered at random vis-a-vis orig order.. what I have now
> after incorporating yr code:
>
> ---------------
>
> public class renameRandom {
>
> public static void main(String[] args) {
>
> File directory = new File(System.getProperty("user.dir"));
> String[] textFileNames = directory.list(new FilenameFilter() {
> public boolean accept(File dir, String name) {
> return name.endsWith(".jpg") || name.endsWith( ".JPG");
> }
> });
for (int i = 0; i < textFileNames.length; ++i) {
textFileNames[i] = i + ".jpg";
}
> ArrayList photos = new ArrayList();
> for (int i=0; i < textFileNames.length; i++) {
> photos.add(new File(textFileNames[i]));
> }
> Collections.shuffle(photos, new Random());
>
>
> }
>
> }
>
> still trying to incorporate random "feature" into this renaming class..
>
> maybe I need to modify this line?
>
> File newFile = new File(i+1 + ".jpg");
>
> so it when renaming imgs it goes thru the imgs at random instead of how
> they are ordered originally??
>
> thank you very much..
| |
| Jeff Higgins 2008-03-07, 7:23 pm |
| Oops!
> for (int i = 0; i < textFileNames.length; ++i) {
> textFileNames[i] = i + ".jpg";
> }
for (int i = 0; i < textFileNames.length; ++i) {
textFileNames[i] = i + ".jpg";
new File(textFileNames[i]).renameTo(new File(i + ".jpg"));
}
| |
| Jeff Higgins 2008-03-07, 7:23 pm |
|
> Oops!
>
> for (int i = 0; i < textFileNames.length; ++i) {
> textFileNames[i] = i + ".jpg";
> new File(textFileNames[i]).renameTo(new File(i + ".jpg"));
> }
>
>
Let me try this again.
for (int i = 0; i < textFileNames.length; ++i) {
String current = directory.getAbsolutePath() +
File.separator + i + ".jpg";
String temp = directory.getAbsolutePath() +
File.separator + textFileNames[i];
new File(temp).renameTo(new File(current));
textFileNames[i] = current;
}
| |
|
| <http://java.sun.com/javase/6/docs/a....html#listFiles(java.io.FileFilter)>
You can retrieve the list as Files directly, so you needn't create a copy of
each one.
Jeff Higgins wrote:
> import java.io.File;
import java.io.FileFilter;
> import java.util.ArrayList;
import java.util.Arrays;
> import java.util.Collections;
>
> public class ShuffleImages {
>
> public static void main(String[] args) {
File [] shuffledFiles = getImagesShuffled();
// do something with them
}
public static File [] getImagesShuffled()
{
> File directory = new File(System.getProperty("user.dir"));
File [] files = directory.listFiles( new FileFilter()
{
public boolean accept( File file )
{
return file.getName().toLowerCase().endsWith(".jpg");
}
} );
Collections.shuffle( Arrays.asList( files ) );
return files;
> }
> }
--
Lew
| |
|
| maya wrote:
> so I now have:
>
> ArrayList photos = new ArrayList();
If you used generics you'd see that this is a List <File>, not a List <String>.
> for (int i=0; i < textFileNames.length; i++) {
> photos.add(new File(textFileNames[i]));
> }
>
> Collections.shuffle(photos, new Random());
You don't really need a new Random().
> String[] photosArr = new String[photos.size()];
> photos.toArray(photosArr); // runtime error on this line..
Because you're trying to jam a bunch of Files into an array of String.
> it compiles fine,
Because you don't use generics. With generics you'd have had an error and
you'd know why it didn't work.
> but get a runtime error, thus:
> Exception in thread "main" java.lang.ArrayStoreException
> line 40 is: photos.toArray(photosArr);
And now you know.
--
Lew
| |
|
| Lew wrote:
> maya wrote:
>
> If you used generics you'd see that this is a List <File>, not a List
> <String>.
>
>
> You don't really need a new Random().
>
>
> Because you're trying to jam a bunch of Files into an array of String.
>
>
> Because you don't use generics. With generics you'd have had an error
> and you'd know why it didn't work.
>
>
> And now you know.
>
thank you very much to all for your help.. I finally managed, thus:
public class renameRandom {
public static void main(String[] args) {
int posDot;
String _temp = "";
String no = "";
File oldFile;
int __indx;
int _indx;
int indx;
File directory = new File(System.getProperty("user.dir"));
// if no arg passed start naming of imgs @ "1"
// else start at whatever no. is passed...
if (null == args || args.length < 1) {
no = "1";
} else {
no = args[0];
}
__indx = Integer.parseInt(no);
_indx = __indx - 1;
String[] textFileNames = directory.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".jpg") || name.endsWith( ".JPG");
}
});
ArrayList photos = new ArrayList();
for (int i=0; i < textFileNames.length; i++) {
System.out.println(textFileNames[i] + " -- " + i);
photos.add(new File(textFileNames[i]));
}
System.out.println("");
Collections.shuffle(photos);
Object _photosArr[] = photos.toArray();
String photosArr = "";
File newFile;
for (int i = 1; i < _photosArr.length+1; ++i) {
photosArr = _photosArr[i-1].toString();
posDot = photosArr.indexOf(".");
_temp = photosArr.substring(0,posDot);
oldFile = new File(_temp + ".jpg");
indx = i + _indx;
newFile = new File(indx + ".jpg");
oldFile.renameTo(newFile);
System.out.println(_photosArr[i-1] + " -- " + newFile);
System.out.println(photosArr + " ** " + newFile + "\n");
// above line u see it prints out correct new names....
}
}
}
however, a problem remains:
1) if, after renaming, I have, say, imgs 1.jpg thru 15.jpg, then remove,
for ex, 8.jpg and 9.jpg, and run class again, it still skips these two
numbers and last img is still 15.jpg.. (but if you run the class and
look @ printouts in console it shows correct names for newFile var...
in general I find class does not work well if when run the class files
have already been renamed once to 1.jpg, etc.. as opposed to if files
still have orig names (DSC_0004.jpg, etc..)
once again thank you all very much... this is the hardest thing I have
tried to do in java...
| |
|
| maya wrote:
> String[] textFileNames = directory.list(new FilenameFilter() {
> public boolean accept(File dir, String name) {
> return name.endsWith(".jpg") || name.endsWith( ".JPG");
> }
> });
>
> ArrayList photos = new ArrayList();
>
> for (int i=0; i < textFileNames.length; i++) {
> System.out.println(textFileNames[i] + " -- " + i);
> photos.add(new File(textFileNames[i]));
> }
>
> System.out.println("");
>
> Collections.shuffle(photos);
> Object _photosArr[] = photos.toArray();
The trouble with this idiom is that you create an array, *copy* it into a
List, then *copy* it back into an array. That's very wasteful. If you use
Arrays.asList() as I suggested elsethread, then you skip both the repeated
add() step and the toArray() step.
Reiterating the code fragment:
public static File [] getImagesShuffled()
{
File directory = new File(System.getProperty("user.dir"));
File [] files = directory.listFiles( new FileFilter()
{
public boolean accept( File file )
{
return file.getName().toLowerCase().endsWith(".jpg");
}
} );
Collections.shuffle( Arrays.asList( files ) );
return files;
}
This will save both memory and execution time, a rare case when there isn't a
tradeoff between them.
You should also genericize your Collections classes when you do use them, and
make the widest appropriate type for the variable even if the object type is
narrower:
List <File> photos = new ArrayList <File> ();
--
Lew
| |
| Roedy Green 2008-03-10, 10:30 pm |
| On Mon, 25 Feb 2008 16:39:42 -0500, maya <maya778899@yahoo.com> wrote,
quoted or indirectly quoted someone who said :
>this method apparently takes no arguments, so how do you tell it in what
>range (betw what nos.) you want the random no. generated?
see
http://mindprod.com/jgloss/pseudorandom.html
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
| |
|
| Lew wrote:
> maya wrote:
>
> The trouble with this idiom is that you create an array, *copy* it into
> a List, then *copy* it back into an array. That's very wasteful. If
> you use Arrays.asList() as I suggested elsethread, then you skip both
> the repeated add() step and the toArray() step.
>
> Reiterating the code fragment:
> public static File [] getImagesShuffled()
> {
> File directory = new File(System.getProperty("user.dir"));
>
> File [] files = directory.listFiles( new FileFilter()
> {
> public boolean accept( File file )
> {
> return file.getName().toLowerCase().endsWith(".jpg");
> }
> } );
> Collections.shuffle( Arrays.asList( files ) );
> return files;
> }
>
> This will save both memory and execution time, a rare case when there
> isn't a tradeoff between them.
>
> You should also genericize your Collections classes when you do use
> them, and make the widest appropriate type for the variable even if the
> object type is narrower:
>
> List <File> photos = new ArrayList <File> ();
>
Lew, thanks for your response.. it's not that I dont pay attention to
responses.. but sometimes responders post just a snippet of code that I
don't know where to put it in the class and dont know how to make it
work and such.. I new if I could convert that ArrayList back to a
regular array it would work.. so I just figured out how to do that and
it worked...;)
(well, sort of, as I mentioned yesterday I'm still having some problems..)
the code you post today,
public static File[] getImagesShuffled()
what is this? doesn't look like a method.. is it a class? I put this
class inside my class and call it from my class? it's an inner class,
right? sorry, this is why I get sometimes, how do I call this
class from inside my class?? not sure exactly what part of my code to
replace w/this code...
thank you...
| |
|
| maya wrote:
> the code you post today,
>
> public static File[] getImagesShuffled()
>
> what is this? doesn't look like a method.. is it a class? I put this
> class inside my class and call it from my class? it's an inner class,
> right? sorry, this is why I get sometimes, how do I call this
> class from inside my class?? not sure exactly what part of my code to
> replace w/this code...
This is a method, lifted from my earlier post, that you put inside the class.
The parentheses are a clue. As is the 'return' statement before the closing
brace.
It is shown as a 'static' method, but could be implemented as an instance
method instead.
You call it from another method, such as main() in the same class, by an
invocation:
File [] shuffledImages = getImagesShuffled();
This was shown in my earlier post.
Defining methods:
<http://java.sun.com/docs/books/jls/...lasses.html#8.4>
<http://java.sun.com/docs/books/tuto...OO/methods.html>
Invoking methods:
<http://java.sun.com/docs/books/jls/...ions.html#15.12>
<http://java.sun.com/docs/books/tuto...eturnvalue.html>
--
Lew
| |
|
| Lew wrote:
> maya wrote:
>
> This is a method, lifted from my earlier post, that you put inside the
> class. The parentheses are a clue. As is the 'return' statement before
> the closing brace.
>
> It is shown as a 'static' method, but could be implemented as an
> instance method instead.
>
> You call it from another method, such as main() in the same class, by an
> invocation:
>
> File [] shuffledImages = getImagesShuffled();
>
> This was shown in my earlier post.
>
> Defining methods:
> <http://java.sun.com/docs/books/jls/...lasses.html#8.4>
> <http://java.sun.com/docs/books/tuto...OO/methods.html>
>
> Invoking methods:
> <http://java.sun.com/docs/books/jls/...ions.html#15.12>
>
> <http://java.sun.com/docs/books/tuto...eturnvalue.html>
>
ok, I found your earlier post, Lew, with the method and the call to it
(yes, it did look like a method to me, but I had never seen a method
declared like an array, so I was a bit ..)
so now have done thus:
public class renameRandom {
public static void main(String[] args) {
int _indx;
int indx;
int iRenTo = 0;
File newFile;
// if no arg passed start naming of files @ "1"
// else start at whatever no. is passed...
if (null == args || args.length < 1 || args[0].equals("0")) {
indx = Integer.parseInt("0");
} else {
_indx = Integer.parseInt(args[0]);
indx = _indx - 1;
}
File [] shuffledFiles = getImagesShuffled();
for (int i = 0; i < shuffledFiles.length; ++i) {
iRenTo = ++indx;
newFile = new File(iRenTo + ".jpg");
System.out.println( shuffledFiles[i] + " -- of ::: " + newFile +
" -- nf" );
shuffledFiles[i].renameTo(newFile);
}
}
public static File[] getImagesShuffled() {
File directory = new File(System.getProperty("user.dir"));
File[] files = directory.listFiles( new FileFilter() {
public boolean accept( File file ) {
return file.getName().toLowerCase().endsWith(".jpg");
}
} );
Collections.shuffle( Arrays.asList( files ) );
return files;
}
}
and this works fine except I would like the option of running the class
again to shuffle the images again, but, just like before, once the files
are named 1.jpg, 2.jpg, etc.. (as opposed to orig names like
DSC_0004.JPG, DSC_0023.JPG, etc..) the renameTo() stmt gets IGNORED..
the images ARE being shuffled every time I run the class (as can be seen
by what the printout-stmt returns...), but they only get renamed the
first time I run the class (before imgs are named "1.jpg", etc..)
I have been working on this for about two hours now, still don't know why..
thank you..
|
|
|
|
|