Math.random() function in Java
My computer doesn't gives enough good random numbers with this function. Does it need any improvement?
Define "enough good random numbers"
Similar Messages
-
HELP!!! math.random() problem
Hello,
I was wondering if anyone can help me with a problem I'm
running into using the math.random(). I'm using Flash CS3 and
created a very simple script to select random frames in a simple
movie. It works as expected in the CS3 environment and in Safari
but it doesn't work correctly in Firefox or in the DotNetNuke
module I am using. Here is the code:
i = Math.ceil(Math.random() * 3);
gotoAndPlay("Image"+i);
I would appreciate any help you can provide.Remember that Math.random() function returns a positive double value between 0.0 and 1.0. For a better definition you can refer to the Math class in the API.
Since this is an assignment, I am not going to give you the code but I'll just tell you how you should be going about solving this.
Now you have two limits right? What you can do is, multiply the smaller of the two numbers (I guess in your case its going to be the top) with the random number generated by the Math.random() function. Just add a check to see if this result is lesser than the maximum limit. If yes, then go ahead and add that number to the array. If not, just repeat the same thing.
I hope you got the idea. If you still have problems, please let me know.
Plutaurian -
Help with math.random!
I'm trying to replace all even numbers in a string with odd numbers that are produced from a random generator. I have somewhat of an idea of how to do it as far as creating an array of 5 characters(1,3,5,7,9) and then implement the math.random to take random numbers from that array. i just dont know how to execute that. for example:
"adam123456789" -->should be "adam153157739"
whereas, the underlined(5,1,7,3) should be random numbers(i just picked these for an instance). is it possible to do any form of :
Methods...
char [ ] ary = {1,3,5,7,9};
String line = "adam123456789";
line = line.replaceAll("[0,2,4,6,8]", Math.round(Math.random()*[ary]));
return line;**i'm a beginner, so i dont really know what im talking about. just seeking help. thanks!ok. this is the class with all of my methods in there. just excuse the rest of it..
import java.util.Random;
public class NoVowelNoEven {
private String str = "";
NoVowelNoEven() {
str = "hello";
NoVowelNoEven(String newString) {
str = newString;
String getOriginal() {
return str;
static String getValid(String newString) {
char[] arr = newString.toCharArray();
String str2 = "";
for (int i = 0; i < arr.length; i++) {
if (isValid(arr)) {
str2 += arr[i];
return str2;
static int countValidChar(String newString) {
String validString = getValid(newString);
return validString.length();
static String replaceWithYAndOdd(String newString) {
char [] ary = {1,3,5,7,9};
String str3 = newString;
str3 = str3.replaceAll("[a,e,i,o,u]","y");
str3 = str3.replaceAll("[A,E,I,O,U]","Y");
//str3 = str3.replaceAll("[0,2,4,6,8]", );
return str3;
static boolean isValid(char char2) {
switch (Character.toLowerCase(char2)) {
case 'a':
return false;
case 'e':
return false;
case 'i':
return false;
case 'o':
return false;
case 'u':
return false;
case '0':
return false;
case '2':
return false;
case '4':
return false;
case '6':
return false;
case '8':
return false;
default:
return true; -
Is there a way to create a math.random that doesn't overlap movieclips?
Hi,
Actually I have two questions. I am creating a memory sequence game and I was wondering:
1. Is there a way to random position movieclips on the stage without having them overlap each other?
2. Is there a way to have flash draw a vector line from one clip to another in sequence and then have the user retrace what flash did? I have 6 movieclips on the stage, each with their own instance (ex. obj1_mc, obj2_mc, etc.). Is there a way to tell flash to always draw a line between movieclips in sequence even though the movieclips are randomly placed on the stage?
Thanks,
OJsure.
1. the easiest way to position objects without over-lapping, IF you can assume it will always be possible, is to use something like:
var mcA:Array=[your movieclips]
var index:uint=0;
positionF();
function positionF(){
// assuming top-left reg points of your movieclips
mcA[index].x=Math.random()*(stage.stageWidth-mcA[index].width);
mcA[index].y=Math.random()*(stage.stageHeight-mcA[index].height);
var hitBool:Boolean=false;
for(var i:int=0;i<index-1;i++){
if(mcA[index].hitTestObject(mcA[i])){
hitBool=true;
break;
if(hitBool){
positionF();
} else {
index++;
if(index<mcA.length){
positionF();
} else {
// positioning complete. do whatever
2. you can use the graphics class to draw dynamic lines. -
Any Mod function in JAVA?
I did not find 'MOD' function in the Math class. Is there any 'MOD' function in Java?
Thanks!What is your MOD function?
Does the %-operator do what you need or do you want a strict mathematical modulus that returns only positive values? -
How to change double i = Math.random(); value to (int) value
I am trying to find out how to convert a given double value to integer, which is, to conver double myNumber = Math.random() to (int) value. Here is the sample program look like this.
Thank you for the help.
import javax.swing.JOptionPane;
public class numbers
public static void main(String[] args)
int upperLimit = Integer.parseInt(JOptionPane.showInputDialog
(null, "Enter the upper range integer."));
double myNumber = Math.random();
//Test of Random numbers.
System.out.println("The Upper random number limit is: " +
myNumber * upperLimit);
} //End of main.
} // End of class.Not sure exactly what you want and why you want to change the double to an int. I'm assuming by this you want to generate random integers, from 1 to the upper limit the user enters? If so, this is how I would do it:import java.util.*;
import javax.swing.*;
public class Numbers
public static void main(String[] args)
int upperLimit = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the upper range integer."));
Random r = new Random();
int myNumber = r.nextInt(upperLimit) + 1;
System.out.println(myNumber);
} -
Generating unique no.'s using random function
Hi,
I'm trying to generate unique values for row and column say from 0-3
and I read some where that if we use random.nextInt() we will get unique values but I'm getting repeated values.I'll appreciate if anyone can help me in this matter.Here's the code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class random{
public static void main(String args[])
int b[]=new int[4];
int c[]=new int[4];
int i;
Date date;
Random random;
date=new Date();
random = new Random(date.getTime());
for(i=0;i<4;i++)
digit = random.nextInt(4);
b=digit;
for(i=0;i<4;i++)
digit = random.nextInt(4);
c[i] = digit;
for(i=0;i<4;i++)
System.out.println("column array is" + c[i]);
for(i=0;i<4;i++)
System.out.println("row array is" + b[i]);
}//end main
}//end class
Thanks
Suneetha.here is my code for generating a random number but not a unique number. with a big enough number the possibility getting a unique is high so you may modify it to suit you need:
private void initial_node()
float Qxyd = -1, Qyzd = -1, Cxyd = -1, Cyzd = -1;
long seed;
Q_table = new float[row][col];
seed = (long)( Math.random() * System.currentTimeMillis() * 100000000 );
Random rand1 = new Random( seed );
seed = (long)( Math.random() * System.currentTimeMillis() * 100000000 );
Random rand2 = new Random( seed );
seed = (long)( Math.random() * System.currentTimeMillis() * 100000000 );
Random rand3 = new Random( seed );
seed = (long)( Math.random() * System.currentTimeMillis() * 100000000 );
Random rand4 = new Random( seed );
for( int i = 0; i < row; i++ )
do
Qxyd = (float)( rand1.nextFloat() + (float)rand1.nextFloat() / 3 );
while( Qxyd < 0.35 || Qxyd == -1 );
Q_table[5] = Math.abs( Qxyd );
do
Qyzd = (float)( rand2.nextFloat() + (float)rand2.nextFloat() / 7 );
while( Qyzd < 0.45 || Qyzd == -1 );
Q_table[i][3] = Math.abs( Qyzd );
do
Cxyd = (float)( rand3.nextFloat() + (float)rand3.nextFloat() / 9 );
while( Cxyd > 0.15 || Cxyd == -1 );
Q_table[i][8] = Math.abs( Cxyd );
do
Cyzd = (float)( rand4.nextFloat() + (float)rand4.nextFloat() / 11 );
while( Cyzd > 0.10 || Cyzd == -1 );
Q_table[i][9] = Math.abs( Cyzd ); -
Hello,
I made a memory game with a tutorial. My knowledge of AS3 is not that good so I have to following question.
There is a function like Math.Random to random generate number and put them on stage. I made a memory game and the cards are on the same place every time I play the "movie".
I want them to shuffle every time I restart the game. How can I write a good random function in AS3?
Thank you.
Joep van DongenSo you still cant open my files?
I can post code:
Fla file = Memory.fla
DocumentClass = MemoryGame
This is MemoryGame.as :
package
import flash.display.MovieClip;
import flash.events.MouseEvent;
import Card;
import Computer;
import Muis;
import Radio;
import Iphone;
import Beamer;
import Platenspeler;
public class MemoryGame extends MovieClip
private var _card:Card;
private var _computer:Computer;
private var _muis:Muis;
private var _radio:Radio;
private var _iphone:Iphone;
private var _beamer:Beamer;
private var _platenspeler:Platenspeler;
private var _cardX:Number;
private var _cardY:Number;
private var _firstCard:*;
private var _totalMatches:Number;
private var _currentMatches:Number;
public function MemoryGame()
_totalMatches = 6;
_currentMatches = 0;
createCards();
private function createCards():void
_cardX = 45;
_cardY = 31;
for(var i:Number = 0; i < 2; i++)
_card = new Card();
addChild(_card);
_computer = new Computer();
_card.setType(_computer);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
for(var j:Number = 0; j < 2; j++)
_card = new Card();
addChild(_card);
_muis = new Muis();
_card.setType(_muis);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cardX = 45;
_cardY += _card.height + 50;
for(var k:Number = 0; k < 2; k++)
_card = new Card();
addChild(_card);
_radio = new Radio();
_card.setType(_radio);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
for(var l:Number = 0; l < 2; l++)
_card = new Card();
addChild(_card);
_iphone = new Iphone();
_card.setType(_iphone);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cardX = 45;
_cardY += _card.height + 50;
for(var m:Number = 0; m < 2; m++)
_card = new Card();
addChild(_card);
_beamer = new Beamer();
_card.setType(_beamer);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
for(var n:Number = 0; n < 2; n++)
_card = new Card();
addChild(_card);
_platenspeler = new Platenspeler();
_card.setType(_platenspeler);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
private function checkCards(event:MouseEvent):void
event.currentTarget.removeEventListener(MouseEvent.CLICK, checkCards);
if(_firstCard == undefined)
_firstCard = event.currentTarget;
else if(String(_firstCard._type) == String(event.currentTarget._type))
_firstCard = undefined;
_currentMatches ++;
if(_currentMatches >= _totalMatches)
else
_firstCard.gotoAndPlay("flipBack");
event.currentTarget.gotoAndPlay("flipBack");
_firstCard.addEventListener(MouseEvent.CLICK, checkCards);
event.currentTarget.addEventListener(MouseEvent.CLICK, checkCards);
_firstCard = undefined;
This is the Card.as:
package
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class Card extends MovieClip
public var _type:*;
public function Card()
this.buttonMode = true;
this.addEventListener(MouseEvent.CLICK, onClick);
private function onClick(event:MouseEvent):void
if(this.currentFrame == 1)
this.play();
public function setType(type:*):void
_type = type;
loader_mc.addChild(_type);
This is the how its put on screen:
So you can see its quiet easy to do this memory game ;-)
I'm really desperate right now because I was really happy how far I got with this game:-)
But now I know my AS3 isnt that good at all. -
[FLA] Math.random
Amigos, tengo otra pregunta:
Intento hacer algo parecido a un dado. He creado un MC dado
con 6 fotogramas y he creado un MC que me sirva de botón.
He escrito el código de abajo. Y el dado obedece por el
return de la primera función, antes de hacer clic en el
botón, y deja el botón inutilizado.
¿Qué es lo que me falla, por favor? Mil
graciasPerdón, el código es:
function randRange(min:Number, max:Number):Number {
var randomNum:Number = Math.floor(Math.random() * (max - min
+ 1)) + min;
return randomNum;
this.boton.onRelease = function()
for (var i = 0; i<1; i++) {
var n:Number = randRange(1, 6)
izquierda.gotoAndStop(n);
Pero sólo me funciona el dado la primera vez.
¿Qué puede ser? -
Upper/lower limits of Math.random
Hi,
I currently have applied a random range to my Mouse Cursor. So it fluctuates on the Y axis.
However it obviously takes any value between 0 and 10.
I would like it to either take 0 or 10. I know you can use math.round / ceil, but does anyone know how I could achieve this?
Thanks.
var mouseposy = mouseY;
var mouseposx = mouseX;
const DURATION:Number = 1;
const VERTICAL_RANGE:Number = 10;
var timer:Timer = new Timer( 50, DURATION * 20 );
timer.addEventListener( TimerEvent.TIMER, onTimer );
timer.addEventListener( TimerEvent.TIMER_COMPLETE, onTimerComplete );
timer.start();
function onTimer( $event:TimerEvent ):void
myCursor.y = mouseposy - (VERTICAL_RANGE * ( Math.random() * 5 ));
myCursor.x = mouseposx
stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
myCursor.visible = true;
function onTimerComplete( $event:TimerEvent ):void
x = y = 0;
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);try replacing with these lines
const VERTICAL_RANGE:Number = 1
myCursor.y = mouseposy - ((VERTICAL_RANGE * Math.ceil( Math.random() * 2 ))* 10); -
Avoid Math.random() from looping the same number twice?
I'm trying to play a random gallary image by making it stops at different frame every few seconds, and the actions is completely random.
The problem is, since there are only 5 different images(5 frames) I'm displaying, there is a high probability that it stays at the same frame, how do I avoid that? Like avoid staying at the same page twice, if not run the function again....?
setInterval(createItems,throwItems);
var RandomImg:randomImg =new randomImg();
RandomImg.y=100;
RandomImg.x=180;
RandomImg.gotoAndStop(Math.floor(Math.random()*(1+5-1))+1);//generate random value between 1-5
addChild(RandomImg);
ThanksHow do I keep track of the random value, like what value should I put within the if to compare?
I try modify it a little, and wrap it within an if(), and use preValue to track down the previous frame, am I doing it right?
setInterval(createItems,throwItems);
var preValue:Number;
function createItems():void
var RandomImg:randomImg =new randomImg();
var randomFrame= Math.floor(Math.random()*(1+5-1))+1; //generate random value between 1-5
RandomImg.y=100;
RandomImg.x=180;
RandomImg.gotoAndStop(randomFrame);
if(preValue == randomFrame)
RandomImg.gotoAndStop(Math.floor(Math.random()*(1+5-1))+1);
addChild(RandomImg);
preValue = randomFrame;
}else
addChild(RandomImg);
preValue = randomFrame; -
Randomization without Math.random()
Hi,
I need to write a function that returns successive values from a list randomly without using Math.random. I can paste a constant list of pseudo-random values into the function and use it. This should work the same as Math.random with a constant for the initial random seed. Any idea how can I do this???Have you ever had tamarind candy? I haven't actually. That was my first reaction when I read that :)
It's addictive. The
ingredients are
tamarind, sugar, chilies and salt. (You can get them
without chilies,
but that's the gringo version.) It's a typical Thai
recipe in that it seeks to
balance sour, sweet, hot and salty -- a snack for
Buddhists. If they're fresh,
they are nice and chewy, too. They may not be candy,
but I'm an open-minded
snacker.If I don't act xenophobic and closed-minded they'll take away my American card :)
That doesn't actually sound gross at all. Would you find them at an Asian market? There are a few around where that I could look for them. If not, what about an Indian market? There are hell of Indians in this area, so there's probably a store nearby. -
User defined function in java for message mapping
I wrote the following user defined function in java for message mapping and mapped vendor with this. The aim of this function is to write a error file at defined path when i send empty Vendor value from File to RFC-Function module BAPI_PO_CREATE. The "err.txt" error file is not written when i execute in TEST but the value "ERROR" is returned to destination Vendor Field.
public String validation(String a, Container container) {
//write your code here
if (a.equals("")) {
try {
String source = "Vendor cannot be empty";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);
for (int i = 0; i < buffer.length; i +=2)
f0.write(buffer<i>);
f0.close();
FileWriter f1 = new FileWriter("/10.10.0.55/sapmnt/trans/edixiin/err.txt");
f1.write(buffer);
f1.close();
catch (IOException e) {}
return "ERROR";Hi Senthil,
Check these things :
1) Whether you have permission to create a file in that directory.
2) try giving this
10.10.0.55
sapmnt
trans
edixiin
err.txt
3) Also check for permissions.
Hope this will help you.
Regards
Suraj -
Writing message mapping function in Java in integration repository
Hi XI Pundits,
I am new to XI. I was working on Message mapping in intergration repository.
To map the source messages to target messages, we do graphical kind of mapping like drag and drop.
There are some functions aavilable at the bottom like concatehate, trim and etc. which we use if we need to modify the source message and map to target.
But in case we face a situation when we don't find the function which suits our requirement, I guess we need to write a new function. We can write these new function using Java only.
Can someone throw some light on this ?
<b>What do we do to invoke java editor in integartion reposity to write mapping function in java ?
Can someone give an example of snippet of code ?</b>
Thanks.Hi Tushar,
Go thro this help link. You will get all info about User defined function.
http://help.sap.com/saphelp_nw04/helpdata/en/22/e127f28b572243b4324879c6bf05a0/frameset.htm
To get more understanding on mapping go thro this link(PDF File)
https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/9202d890-0201-0010-1588-adb5e89a6638
Hope this helps.
regards,
P.Venkat
Message was edited by: Venkataramanan -
Can we call java function in java script????
hello
please tell me can i call a java function through java script function in jsp???of course not. JavaScript is interpreted by the client (web browser) while the Java code in a JSP resides on the server. don't confuse the web application's architecture.
robert
Maybe you are looking for
-
I have an iPad 2 with most recent update 8.1.3. I have been experiencing connection problems, wifi dropping all the time. I get the prompts to enter passwords for iCloud and i Tunes all the time. I finally synched my Apple ID with my iTunes ID but th
-
Can\t install Adobe Flash 10.2 - tell me to close M. Firefox. How?
How do I close M. Firefox in order to install Adobe Flash 10.2? Thx, Isabel PS Explain with simple sentences. I am easily confused. For example, a box below says "Installed plug-ins". My answer is "What? Pardon me? ".
-
Recovery_mode managed vs managed real time apply
Hello All, I am using Oracle 11.2.0.3 My primary database is an Oracle RAC 2 nodes database with ASM and my standby database is a single instance physical standby database on file systems. My protection mode is MAXIMUM PERFORMANCE What is the differe
-
Table vertical alignment problem
Hi, I wonder if someone can take a look at this page www.fitnessworld.ca/corplist.html and tell me what needs to be fixed to make the first column of words start at the top, aligned with the column next to it. If you have a solution, could you provid
-
How do I get to the connection doctor
My email is not being forwarded to 'Mail' so how do I get to the connection doctor?