Hello everyone,


I want to print out the string "Hello World!" to console at a random interval, and the average length of the random interval is 1 minute when the string is printed out hundreds of times. Anyone know how to accomplish this?


Thanks in advance,
George

Recommended Answers

All 20 Replies

I tried this out and here's the method I came up with... enjoy!

public class Rand
{
	public static void main(String[] args)
	{
		String[] sa = {"HelloWorld", " "}; // holds Hello World or just a blank string
		for (int i=0; i<60000; i++) // i think this loop takes aboout a minute
		{							// but im not sure
			int num = (int) (Math.random() * 2); // chooses a random number (0 or 1)
			System.out.println(sa[num]); // and then prints out the corresponding String
											// from above
		}
	}
}

Nick Nisi

it isnot very useful, since the loop can vary from CPU to CPU. Faster CPUs process the loop quicker...
another approch can be with creating a thread(timertask) and a timer class, check out API docs for more....

Thanks tonakai,

it isnot very useful, since the loop can vary from CPU to CPU. Faster CPUs process the loop quicker...
another approch can be with creating a thread(timertask) and a timer class, check out API docs for more....

Your reply is very helpful. Can you describe your idea of "another approch can be with creating a thread(timertask) and a timer class" in more details?


regards,
George

Thanks stupidenator,

I tried this out and here's the method I came up with... enjoy!

public class Rand
{
	public static void main(String[] args)
	{
		String[] sa = {"HelloWorld", " "}; // holds Hello World or just a blank string
		for (int i=0; i<60000; i++) // i think this loop takes aboout a minute
		{							// but im not sure
			int num = (int) (Math.random() * 2); // chooses a random number (0 or 1)
			System.out.println(sa[num]); // and then prints out the corresponding String
											// from above
		}
	}
}

Nick Nisi

How can you draw the conclusion that the loop in your sample will takes about a minute?


regards,
George

Here an example,
myTimer.java

import java.util.*;

public class myTimertask extends TimerTask {
  public void run() {
    System.out.println("Hello World!");
  }
}

myTimertaskUser.java

import java.util.*;
public class myTimerUser {
  public static void main(String[] args) {
    myTimertask testTimertask = new myTimertask();
    Timer testTimer = new Timer();
    testTimer.schedule(testTimertask,1000,1000);
  }
}

well after i write this, i see that it is not possible to change its display time directly, so you need to figure out some other way, like after displaying text, cancel the timer, then generate a new random number, then start again.... i can give you another example but, i am a bit lazy.... ;)

for (int i=0; i<60000; i++) // i think this loop takes aboout a minute

It won't :) On my machine at work (which is extremely slow because of lack of memory, it often spends 5 minutes swapping data when I switch applications) it took 2 minutes almost to the second.

Anyway, it won't print out strings with an average interval of one minute.
For that you need to use a Thread which sleeps for a random interval.
Of course you can't possibly create an unknown number of random intervals yet have those have an average time of a minute.
At best you can create a random number between 2 limits and use that as the interval where the average between those numbers is one minute (in milliseconds which is the measure of time used by Thread.sleep()).

I'm not really sure why I thought that loop would last for a minute. Sorry about that...

Nick Nisi

to average one minute, I would use java.util.Random and do the following...

import java.util.Random;

class OneMinute
{
	public static void main(String[] args) 
	{
		double numSeconds, numSecondsTotal;
		Random random = new Random();

		numSecondsTotal = 0;
		for (int i=0; i<100; i++)
		{
			numSeconds = (random.nextFloat()+0.5)*60;
			numSecondsTotal += numSeconds;
			System.out.println(numSeconds);
		}
		System.out.println("The average number of seconds is: "+ numSecondsTotal/100);

	}
}

I tried usign nextGaussian() but there is no way to change the standard distrubution to something else, but anyways this should work, i tried it out and it always averaged between 58 - 61 seconds, but has a range of 30-90 seconds (aka 0.5 - 1.5 minutes). You can tweak with it a bit to get a bigger range (or smaller) if need be. Use this in conjuction with tonakai's post to get what u need.
http://java.brangle.com/tutorials/java/util/Random.php

Ok so I got bored and decided to do the gaussian method, of course I kinda forced it to do what i wanted with the if statement in there, but either way this has a much much bigger range of 0 - 120 seconds

import java.util.Random;

class OneMinute
{
	public static void main(String[] args) 
	{
		double numSecondsTotal;
		double i=0, numSeconds =0;
		Random random = new Random();

		numSecondsTotal = 0;

		do
		{
			numSeconds = (random.nextGaussian()+1)*60.0;
			if (numSeconds >= 0.0 && numSeconds <= 120.0)
			{
				i++;
				numSecondsTotal += numSeconds;
				System.out.println(numSeconds);
			}
		}
		while (i < 100);
		System.out.println("The average number of seconds is: "+ numSecondsTotal/100);

	}
}

http://java.brangle.com/tutorials/java/util/Random.php

You are welcome stupidenator!

I'm not really sure why I thought that loop would last for a minute. Sorry about that...

Nick Nisi

Thanks all the same,
George

Thanks jwenting,

It won't :) On my machine at work (which is extremely slow because of lack of memory, it often spends 5 minutes swapping data when I switch applications) it took 2 minutes almost to the second.

Anyway, it won't print out strings with an average interval of one minute.
For that you need to use a Thread which sleeps for a random interval.
Of course you can't possibly create an unknown number of random intervals yet have those have an average time of a minute.
At best you can create a random number between 2 limits and use that as the interval where the average between those numbers is one minute (in milliseconds which is the measure of time used by Thread.sleep()).

Your method is quite good! And your machine is too slow. :-)


regards,
George

Thanks tonakai,

Here an example,
myTimer.java

import java.util.*;

public class myTimertask extends TimerTask {
  public void run() {
    System.out.println("Hello World!");
  }
}

myTimertaskUser.java

import java.util.*;
public class myTimerUser {
  public static void main(String[] args) {
    myTimertask testTimertask = new myTimertask();
    Timer testTimer = new Timer();
    testTimer.schedule(testTimertask,1000,1000);
  }
}

well after i write this, i see that it is not possible to change its display time directly, so you need to figure out some other way, like after displaying text, cancel the timer, then generate a new random number, then start again.... i can give you another example but, i am a bit lazy.... ;)

Your sample is very helpful! I am a new user to Timer class and I have studied the API document of this class. I have an issue about this class, will the timer run forever? If not, when will it terminate?


regards,
George

Thanks paradox814,

to average one minute, I would use java.util.Random and do the following...

import java.util.Random;

class OneMinute
{
	public static void main(String[] args) 
	{
		double numSeconds, numSecondsTotal;
		Random random = new Random();

		numSecondsTotal = 0;
		for (int i=0; i<100; i++)
		{
			numSeconds = (random.nextFloat()+0.5)*60;
			numSecondsTotal += numSeconds;
			System.out.println(numSeconds);
		}
		System.out.println("The average number of seconds is: "+ numSecondsTotal/100);

	}
}

I tried usign nextGaussian() but there is no way to change the standard distrubution to something else, but anyways this should work, i tried it out and it always averaged between 58 - 61 seconds, but has a range of 30-90 seconds (aka 0.5 - 1.5 minutes). You can tweak with it a bit to get a bigger range (or smaller) if need be. Use this in conjuction with tonakai's post to get what u need.
http://java.brangle.com/tutorials/java/util/Random.php

Your reply is very helpful. You are an expert of this field and I am a newbie of nextGaussian method. I have two more issues about your reply.

- What means "there is no way to change the standard distrubution to something else" in your reply? What are the something else?

- How can I "tweak with it a bit to get a bigger range (or smaller)"?


regards,
George

Thanks paradox814,

Ok so I got bored and decided to do the gaussian method, of course I kinda forced it to do what i wanted with the if statement in there, but either way this has a much much bigger range of 0 - 120 seconds

import java.util.Random;

class OneMinute
{
	public static void main(String[] args) 
	{
		double numSecondsTotal;
		double i=0, numSeconds =0;
		Random random = new Random();

		numSecondsTotal = 0;

		do
		{
			numSeconds = (random.nextGaussian()+1)*60.0;
			if (numSeconds >= 0.0 && numSeconds <= 120.0)
			{
				i++;
				numSecondsTotal += numSeconds;
				System.out.println(numSeconds);
			}
		}
		while (i < 100);
		System.out.println("The average number of seconds is: "+ numSecondsTotal/100);

	}
}

http://java.brangle.com/tutorials/java/util/Random.php

Your reply is very helpful. Why you say "this has a much much bigger range of 0 - 120 seconds"? From your previous reply, you mentioned the range is 30-90 seconds.


regards,
George

well if you call it with a "period" it will run forever, you can cancel it with,
timertask.cancel() method.....

What are the something else?

Given the API documentation from Sun there is no way to do the following random.setStandardDeviation(someNumber); it is stuck at 1 because it's standard :sad:

What means "there is no way to change the standard distrubution to something else" in your reply?

Tweaking to get a bigger or smaller range could more simplistically be done using my next post where I use a do-while loop and an if statment

One stadard distrubtion means that you will enclose 68.2% of the area under the curve (view link for picture)
2 std will enclose 95.45% of the area under the curve

so if we could modify the standard distrubtion to have it be that the second standard distrubution is 2 minutes then over 95.45% of our random numbers will be between 0 and 2 minutes, which will help optimize the code for faster speed.

And as you guessed it 3 standard deviations would be better but it only covers 99.73% of the curve

For a picture view this:
http://mathworld.wolfram.com/StandardNormalDistribution.html

if you want to avoid a headache don't read this:
Scroll down (on the link given above) to where it says (3), (4), (5), and (6) those are all properties of a standard normal distrubtion. This all has to do with statistics, the picture of a gaussian method is given in P(x). D(x) is the PDF (probabolity density function) which is just the sum of P(x). But anyways onto your question what is a standard deviation is a the square root of variance line (4). I know you are probably getting a headache right now because I hate statistics, and I'm sure after reading this you will to.

How can I "tweak with it a bit to get a bigger range (or smaller)"?

see my second post in this thread with the do-while loop

Your reply is very helpful. Why you say "this has a much much bigger range of 0 - 120 seconds"? From your previous reply, you mentioned the range is 30-90 seconds.
George

Yes the first chunk of code had a range from 30-90, that is it would output numbers from 30 seconds to 90 seconds that averaged on minute. The second block of code had a bigger range of 30 seconds on each end, that is it could vary from 0-120 seconds, and still average one minute. Since the second one allows for more numbers it has a bigger range.

Thanks tonakai,

well if you call it with a "period" it will run forever, you can cancel it with,
timertask.cancel() method.....

Your reply is very helpful.


regards,
George

Thanks paradox814,

Given the API documentation from Sun there is no way to do the following random.setStandardDeviation(someNumber); it is stuck at 1 because it's standard :sad:


Tweaking to get a bigger or smaller range could more simplistically be done using my next post where I use a do-while loop and an if statment

One stadard distrubtion means that you will enclose 68.2% of the area under the curve (view link for picture)
2 std will enclose 95.45% of the area under the curve

so if we could modify the standard distrubtion to have it be that the second standard distrubution is 2 minutes then over 95.45% of our random numbers will be between 0 and 2 minutes, which will help optimize the code for faster speed.

And as you guessed it 3 standard deviations would be better but it only covers 99.73% of the curve

For a picture view this:
http://mathworld.wolfram.com/StandardNormalDistribution.html

if you want to avoid a headache don't read this:
Scroll down (on the link given above) to where it says (3), (4), (5), and (6) those are all properties of a standard normal distrubtion. This all has to do with statistics, the picture of a gaussian method is given in P(x). D(x) is the PDF (probabolity density function) which is just the sum of P(x). But anyways onto your question what is a standard deviation is a the square root of variance line (4). I know you are probably getting a headache right now because I hate statistics, and I'm sure after reading this you will to.


see my second post in this thread with the do-while loop

All I could say is that you are an expert and I am headache about statistics.


regards,
George

Thanks paradox814,

Yes the first chunk of code had a range from 30-90, that is it would output numbers from 30 seconds to 90 seconds that averaged on minute. The second block of code had a bigger range of 30 seconds on each end, that is it could vary from 0-120 seconds, and still average one minute. Since the second one allows for more numbers it has a bigger range.

I am wondering whether there will be only 68.2% of all generated random values in these ranges.


regards,
George

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.