Get current time (milliseconds) without a call to a System method - java

I am trying to challenge myself; my goal is to create and print a random number without a Math or System method.
I already have a method of printing to the console without using System.out.println() but I have hit a roadblock in finding a way to get the time (System.currentTimeMillis()) without a System call.
I understand that I need the current time to use as a seed for my random number generation.
I'd like to not use any math or time-related imports
Edit: Probably shouldn't have asked this... it was just an idea I had haha

Using java.time.Instant:
long now = Instant.now().toEpochMillis();
This of course only works if by "System call" you really mean "no call to a method of the class System" as opposed to "no method of the Java system".

Well, you’ve got to get your seed from somewhere. Would a hard-coded random constant be OK? No, I thought not. Otherwise you would have been set.
So you need to read that seed from somewhere outside the program. You can get it from a server, from the file system, from user input, there are many options, it doesn’t have to be the system clock. I once wrote a program that generated random numbers by shuffling some bits from recent database transactions around and hashing the result. I didn’t even use a pseudo-random number generator. But you need to make some call to outside your program.

Related

Java Math Equation Alarm Snooze

I'm currently coding a clock app in java for android, and I want to implement a snooze function where when the alarm goes off, a random math problem would appear on the screen. The user would have to successfully answer the math problem before the alarm would snooze/turn off. I'm completely lost on how I would implement this feature. Any guidance on how i'd implement this would be greatly appreciated. Thanks.
First, I'd like to say that what ever I'm about to tell you is the way I would do it, since you did not specify any way specifically you would like to do it. I am no Java expert, but you could probably generate two random integers from a certain range (maybe something like 2 to 11) using Math.random. Try looking at this question for info on how to do that: How do I generate random integers within a specific range in Java? or Math.random() explained Then maybe generate a random number from 1 to 4 where 1 is addition, 2 is subtraction, 3 is multiplication, and 4 is addition. Then you could have an if statement for subtraction and division that checks if the first number is greater than the second number. Also, you could have another if statement for division checking if the division statement ends up with a whole number. Then you could have a final if statement checking if the user typed in the right answer. If you want you could make little alerts for if they got it wrong or right. As for the snooze function, you could just make a property that adds a certain amount of minutes to your method for the alarm. Also, I'd like to say that I like your idea for the math problems!

Can you change a line after you've outputted it with System.out.println?

I have been coding for a while now and as far as I'm aware, once you've outputted a line to System.out.println in Java; you cannot change it.
The reason I ask this question is because of some very strange results from my program. The program records the time of the bubble sort and merge sort algorithms in sorting different kinds of int arrays and prints the average of these times at different sizes of n, where n is the size of the array.
Now I've had a litany of problems with this program thus far, but I do not understand how the following is possible:
...
At 200000, randomly-sorted takes:
NaN //Expected output, since I did not activate the random arrays.
...
However, at the same line, and in an unpredictable manner, the program occasionally does this:
...
At 200000, randomly-sorted takes:
75683.45
...
And then swaps back again after a while!
So the program is somehow managing to replace the outputted line, which I have never experienced before.
Any help or clarification very much appreciated! If you need the code, I am more than happy to share.
EDIT: To clarify, this is on a Macbook Air running Java SE 6. As for the code, please refer to my Github account with the entire project at the following link - https://github.com/danielsoutar/complexityPractical.
Side-note: One other thing. For bubble sort, the randomly-generated arrays apparently take longer to sort than a reverse-sorted array, which is clearly nonsense. Not sure if that matters to this problem but it is something to note.
the question was kinda unclear to me, but as far as I understand you could take a look at RegEx for filtering out on a String or clear the Console and put your output back in.
Clear console:
Runtime.getRuntime().exec("cls");
RegEx example:
yourString.replaceAll("[yourCharactersToReplace]","");
System.out refers to a PrintStream instance. In the abstract, a PrintStream object represents a place where you can send text. Period. Once the text is sent, that's the end of the story.
But in reality the text actually goes somewhere. If you are invoking your Java program from a command line, then it's very likely that the place where the text goes is a terminal emulator window or a console window; and it's also very likely that the console recognizes certain codes that your program can embed in the text that tell it to do things.
Things like, change the color of the text, move the cursor around in the window, and over-write text that already was there.
There have been literally hundreds of different coding systems to let a computer program do those things on a terminal screen/window, but one is supported by almost all consoles and terminal emulators. Google for "ANSI escape codes" to learn more about it.
If you want your program to purposefully move the cursor around, change the text color, etc. Then you might want to use a 3rd party library like jcurses (google for that too) to handle the possibility of a console that does not accept (or is not configured to accept) ANSI escape codes.

Android: Random Generation in a Networked Situation (Multiplayer)

I wrote a class that, given a seed and difficulty, will return a playing field to my game. The generation is consistent (no matter what, the same seed & difficulty level will always result in the same play field). As far as I know all android devices use Java 1.6 so here goes my question(s):
Is it safe to send only the seed and difficulty to other devices in a multiplayer environment?
Do I need to worry about when Google updates Java version level form 1.6? or will they likely update all android devices to that version level (I am assuming the Random class will have been changed)? And if not what would be a good way to detect if Random class is different?
Rephrased, what precautionary measures should be in place to ensure that the class java.util.Random, which my field generation class uses heavily, will result in the same play field for every device? Or, alternatively, would it be more wise to consider sending all play field data to the non-hosting device(s)?
I could probably accomplish the latter with a reliable message with size of:
byte[ROWS * COLUMNS]
In advance, I appreciate any guidance/suggestions in this matter. This is a difficult issue to search for so some links for future views may be appropriate.
There are a few options here, but I guess I was hoping for some magic JVM property defining the java.util.Random class revision version.
First option is to check the java version and compare it against the other device's version. If they are the same it is safe (as far as I know) to assume that the Random class is the same and thus the seed and difficulty can be sent. If, however, they are different you either send all the data or check the documentation/version release notes yourself to see when the Random class was changed and then determine if all the data should be sent based on previously acquired java version identifier.
The second option is to simply always send all the data. Which is what I will personally be doing.
If you're not as lucky as I and your data exceeds the value of Multiplayer.MAX_RELIABLE_MESSAGE_LEN (in bytes) you may have to break the data into multiple messages which could get ugly but is entirely doable.

Programmatically finding periodicity of a given function

I am working on a project in Android for my Signal Processing course. My aim is to find signal properties, such as periodicity, even/odd, causality etc, given a user-input function. Right now, I am stuck at trying to figure out how to programmatically calculate the periodicity of a given function. I know the basics behind periodicity: f(t+T) = f(t)
The only idea I have right now is to extensively calculate values for the function, and then check for repetition of values. I know the method is quite stupid, given the fact I don't know how many such values I need to calculate to determine if it is periodic or not.
I know this can be done easily in Matlab, but again very difficult to port Matlab to Java. Is there something I am missing? I have been searching a lot, but haven't found anything useful.
Thanks for any help, in advance!
If the function f is given as a symbolic expression, then the equation you stated can in some cases be solved symbolically. The amount of work required for this will depend on how your functions are described, what kinds of functions you allow, what libraries you use and so on.
If your only interaction with the function is evaluating it, i.e. if you treat the function description as a black box or obtain its values from some sensor, then your best bet would be a Fourier transformation of the data, to convert it from the time domain into frequency domain. In particularly, you probably want to choose your number of of samples to analyze as a power of two, and then use FFT to quickly obtain intensities for various frequencies.

What is a cross platform way to select a random seed in Java?

After reading this answer:
best way to pick a random subset from a collection?
It got me wondering, how does one pick a random seed in Java?
And don't say use System.currentTimeMillis() or System.nanoTime(). Read the article to see why not.
That's a hard question, but let me make it harder. Let's say you need to generate a random seed without connecting to the internet, without using user input (IE, there's no gui), and it has to be cross platform (therefore no JNI to access hardware).
Is there some JVM variables we can monitor as a source of our randomness?
Can this be done? Or is it impossible?
Take a look at Uncommons Maths (full disclosure: I wrote it). It should solve most of the problems you'll ever have with random numbers in Java.
Even, if you don't use it you should be able to get some ideas from the various SeedGenerator implementations it provides. Basically, it defaults to using /dev/random. If that doesn't exist (e.g. Windows) it either tries to download data from random.org or it uses SecureRandom.generateSeed.
I think SecureRandom.generateSeed is the best that you can do without relying on anything platform specific or on the Internet.
Combine System.currentTimeMillis() with a global counter that you increment every time you generate the seed. Use AtomicLong for the counter so you can increment with efficiency and thread safety.
"Combine" doesn't mean "add" or "xor" because it's too easy to get duplicates. Instead, hash. You could get complicated and stuff the long and the counter into e.g. 16 bytes and MD5 it, but I would probably use a 64-bit version of the Adler CRC or some other 64-bit CRC.
Um, that article says that 32-bit seeds are bad, but 64-bit seeds are good. System.currentTimeMillis() is a 64-bit seed.

Categories