Main:
public class Main{
public static void main(String[] args){
System.out.println(Convert.BtoI("10001"));
System.out.println(Convert.BtoI("101010101"));
}
}
Class:
public class Convert{
public static int BtoI(String num){
Integer i= Integer.parseInt(num,2);
return i;
}
}
So I was working on converters, I was struggling as I am new to java and my friend suggested using integer method, which works. However, which method would be most efficient to convert using the basic operators (e.g. logical, arithmetic etc.)
.... my friend suggested using integer method, which works.
Correct:
it works, and
it is the best way.
However, which method would be most efficient to convert using the basic operators (e.g. logical, arithmetic etc.)
If you are new to Java, you should not be obsessing over the efficiency of your code. You don't have the intuition.
You probably shouldn't optimize this it even if you are experienced. In most cases, small scale efficiencies are irrelevant, and you are better off using a profiler to validate your intuition about what is important before you start to optimize.
Even if this is a performance hotspot in your application, the Integer.parseint code has (no doubt) already been well optimized. There is little chance that you could do significantly better using "primitive" operations. (Under the hood, the methods will most likely already be doing the same thing as you would be doing.)
If you are just asking this because you are curious, take a look at the source code for the Integer class.
If you want to use basic arithmetic to convert binary numbers to integers then you can replace the BtoI() method within the class Convert with the following code.
public static int BtoI(String num){
int number = 0; // declare the number to store the result
int power = 0; // declare power variable
// loop from end to start of the binary number
for(int i = num.length()-1; i >= 0; i--)
{
// check if the number encountered is 1
/// if yes then do 2^Power and add to the result
if(num.charAt(i) == '1')
number += Math.pow(2, power);
// increment the power to use in next iteration
power++;
}
// return the number
return number;
}
Normal calculation is performed in above code to get the result. e.g.
101 => 1*2^2 + 0 + 1*2^0 = 5
This question already has answers here:
Java random numbers using a seed
(7 answers)
Closed 5 years ago.
Given the function:
static boolean chance(int percentage) {
return percentage != 0 && random.nextInt(101) <= percentage;
}
and a test for that function:
#Test
public void chance_AlwaysFalse_Percentage0() {
assertFalse(chance(0));
}
The test does not provide with certainty that chance will always return true. I could change the change function to the following:
static boolean chance(int percentage) {
return random.nextInt(101) <= percentage;
}
and the test would still pass. However, there is a very small chance that random.nextInt(100) will return 0, which would make the function return true, making the test fail.
I could execute this test a billion times as well, but given the nature of random numbers, there is still a minimal chance of failure.
How should I go about testing a function like this? Should it be tested at all? What is a better approach to this problem?
There are some functionalities in java that may serve for repeatable unit tests:
Random numbers: the Random constructor with a seed, for instance new Random(13) will always give the same sequence of random numbers. This already has been exploited to find a random sequence starting with 1, 2, 3, ..., 10. Or the alphabetic letters of someones name.
Time: the new java time functions allow for a faked clock, so "now" is always at a given time. Clock.fixed
And then there are mocking frameworks, that instrument the byte code of arbitrary calls so the return a provided result. Also useful for blending out more complex contexts.
Automated tests can't catch everything. In fact, the first example of your function might also have a bug, in that chance(1) will have a 2% chance instead of a 1% chance of returning true (since it would return true if the random number was either 0 or 1). But if you only test 0 and 100, it would pass those tests 100% of the time. (In fact, 0 and 100 are the only values that will return true the correct percentage of the time; everything else will be off by 1%. The effects of that bug are subtle enough that you may or may not ever notice it, depending on how the function is used.)
You could put your tests in a loop, if you really wanted to. If you ran the chance_AlwaysFalse_Percentage0 test 10,000 times, the odds would be very much in favor of any particular random number being hit. (No, it's not technically guaranteed, but if you calculate the odds, I think you'd be satisfied.) I'm not sure if that's worth doing.
Software random number generators are not random
They are deterministic if they are seeded with the same seed.
I also corrected the comparison logic to be correct in the range check.
Testable Implementation
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Random;
#ParametersAreNonnullByDefault
public class Q47336122
{
private final Random random;
public Q47336122(final long seed)
{
this.random = new Random(seed);
}
public boolean chance(final int percentage)
{
if (percentage <= 0) { return false; }
else if (percentage >= 100) { return true; }
else
{
final int r = this.random.nextInt(100);
return r > 0 && r <= percentage;
}
}
}
Deterministic Test
import org.junit.Test;
import javax.annotation.ParametersAreNonnullByDefault;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
#ParametersAreNonnullByDefault
public class Q47336122Test
{
#Test
public void testChance()
{
final Q47336122 q = new Q47336122(1000L);
/* poor man's code generator */
// for (int i=0; i <= 100; i++) {
// System.out.println(String.format("assertThat(q.chance(%d),is(%s));", i, q.chance(i)));
// }
assertThat(q.chance(0),is(false));
assertThat(q.chance(1),is(false));
assertThat(q.chance(2),is(false));
assertThat(q.chance(3),is(false));
assertThat(q.chance(4),is(false));
assertThat(q.chance(5),is(false));
assertThat(q.chance(6),is(false));
assertThat(q.chance(7),is(false));
assertThat(q.chance(8),is(false));
assertThat(q.chance(9),is(false));
assertThat(q.chance(10),is(false));
assertThat(q.chance(11),is(false));
assertThat(q.chance(12),is(false));
assertThat(q.chance(13),is(false));
assertThat(q.chance(14),is(false));
assertThat(q.chance(15),is(false));
assertThat(q.chance(16),is(false));
assertThat(q.chance(17),is(false));
assertThat(q.chance(18),is(true));
assertThat(q.chance(19),is(false));
assertThat(q.chance(20),is(false));
assertThat(q.chance(21),is(false));
assertThat(q.chance(22),is(false));
assertThat(q.chance(23),is(false));
assertThat(q.chance(24),is(true));
assertThat(q.chance(25),is(false));
assertThat(q.chance(26),is(false));
assertThat(q.chance(27),is(false));
assertThat(q.chance(28),is(false));
assertThat(q.chance(29),is(false));
assertThat(q.chance(30),is(false));
assertThat(q.chance(31),is(false));
assertThat(q.chance(32),is(false));
assertThat(q.chance(33),is(false));
assertThat(q.chance(34),is(false));
assertThat(q.chance(35),is(false));
assertThat(q.chance(36),is(true));
assertThat(q.chance(37),is(false));
assertThat(q.chance(38),is(true));
assertThat(q.chance(39),is(false));
assertThat(q.chance(40),is(true));
assertThat(q.chance(41),is(false));
assertThat(q.chance(42),is(true));
assertThat(q.chance(43),is(false));
assertThat(q.chance(44),is(false));
assertThat(q.chance(45),is(false));
assertThat(q.chance(46),is(false));
assertThat(q.chance(47),is(false));
assertThat(q.chance(48),is(false));
assertThat(q.chance(49),is(false));
assertThat(q.chance(50),is(true));
assertThat(q.chance(51),is(true));
assertThat(q.chance(52),is(false));
assertThat(q.chance(53),is(true));
assertThat(q.chance(54),is(false));
assertThat(q.chance(55),is(true));
assertThat(q.chance(56),is(false));
assertThat(q.chance(57),is(true));
assertThat(q.chance(58),is(false));
assertThat(q.chance(59),is(false));
assertThat(q.chance(60),is(true));
assertThat(q.chance(61),is(false));
assertThat(q.chance(62),is(false));
assertThat(q.chance(63),is(true));
assertThat(q.chance(64),is(true));
assertThat(q.chance(65),is(true));
assertThat(q.chance(66),is(true));
assertThat(q.chance(67),is(true));
assertThat(q.chance(68),is(true));
assertThat(q.chance(69),is(false));
assertThat(q.chance(70),is(false));
assertThat(q.chance(71),is(true));
assertThat(q.chance(72),is(true));
assertThat(q.chance(73),is(true));
assertThat(q.chance(74),is(true));
assertThat(q.chance(75),is(false));
assertThat(q.chance(76),is(true));
assertThat(q.chance(77),is(true));
assertThat(q.chance(78),is(true));
assertThat(q.chance(79),is(false));
assertThat(q.chance(80),is(true));
assertThat(q.chance(81),is(false));
assertThat(q.chance(82),is(true));
assertThat(q.chance(83),is(true));
assertThat(q.chance(84),is(true));
assertThat(q.chance(85),is(true));
assertThat(q.chance(86),is(true));
assertThat(q.chance(87),is(true));
assertThat(q.chance(88),is(true));
assertThat(q.chance(89),is(true));
assertThat(q.chance(90),is(true));
assertThat(q.chance(91),is(true));
assertThat(q.chance(92),is(true));
assertThat(q.chance(93),is(true));
assertThat(q.chance(94),is(true));
assertThat(q.chance(95),is(true));
assertThat(q.chance(96),is(true));
assertThat(q.chance(97),is(true));
assertThat(q.chance(98),is(true));
assertThat(q.chance(99),is(true));
assertThat(q.chance(100),is(true));
}
}
No matter how many times you run this test it will always pass.
It is a trivial exercise for the reader to expand this to test for thousands or millions of inputs. As long as the seed is the same as when the test data is generated, it will pass when tested.
An injectable random number generator instance would be a better design and would make testing even easier in cases where the random number source is actually not deterministic.
static methods are an anti-pattern and is the crux of your problem with testing as it stands, there is nothing here that can not be fixed with some simple refactoring to get rid of the static stuff and make it deterministic and testable as my code shows.
I'm learning about while loops. In my Java class currently I'm trying to modify a program to use a basic while loop to generate random numbers until a certain number is reached. In this particular case I want it to print until it goes below .0001. I've gotten myself confused while trying to do it and am not getting any output. I'm looking for any hints or tips that anyone might have to help me along with this or help further my understanding. Here's what I have for code so far:
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random rand = new Random();
double val = 1;
while(val < .0001){
val = rand.nextDouble();
System.out.println(val);
}
}
}
The while conditions says:
"While x condition is true, do this"
In this case, you have val=1 that is grather then 0.0001. So the while gets never executed.
So setting while(val>0.001), means:
"While my val is grater then 0.001, print it out. If is less then 0.001, return"
In code:
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random rand = new Random();
double val=1;
while(val>.0001){
val=rand.nextDouble();
System.out.println(val);
}
}
}
Simple logic error. Based on your current code the while loop will never run because val<.0001 will always be false (1 > .0001). You need to modify that line to this:
while(val > 0.0001){
Also it's usually better to write decimals with a 0 in front of the . for improved readability.
Your error is just simple to correct. You didn't tell your code to increase or decrease (++ or --) you should set your variable to increase or decrease base in what you want it to do.
I have a set of over 100 different probabilities ranging from 0.007379 all the way to 0.913855 (These probabilities were collected from an actuary table http://www.ssa.gov/oact/STATS/table4c6.html). In Java, how can I use these probabilities to determine whether something will happen or not? Something along these lines...
public boolean prob(double probability){
if (you get lucky)
return true;
return false;
}
The Random class allows you to create a consistent set of random numbers so that every time you run the program, the same sequence of values is generated. You can also generate normally distributed random values with the Random class. I doubt you need any of that.
For what you describe, I would just use Math.random. So, given the age of a man we could write something like:
double prob = manDeathTable[age];
if( Math.random() < prob )
virtualManDiesThisYear();
First you need to create an instance of Random somewhere sensible in your program - for example when your program starts.
Random random = new Random();
Use this code to see whether an event happens:
boolean happens = random.NextDouble() < prob;
I'm not sure where that range came from. If you have a distribution in mind, I'd recommend using a Random to generate a value and get on with it.
public ProbabilityGenerator {
private double [] yourValuesHere = { 0.007379, 0.5, 0.913855 };
private Random random = new Random(System.currentTimeMillis());
public synchronized double getProbability() {
return this.yourValuesHere[this.random.nextInt(yourValuesHere.length));
}
}
I need to create a Java method to return true or false randomly. How can I do this?
The class java.util.Random already has this functionality:
public boolean getRandomBoolean() {
Random random = new Random();
return random.nextBoolean();
}
However, it's not efficient to always create a new Random instance each time you need a random boolean. Instead, create a attribute of type Random in your class that needs the random boolean, then use that instance for each new random booleans:
public class YourClass {
/* Oher stuff here */
private Random random;
public YourClass() {
// ...
random = new Random();
}
public boolean getRandomBoolean() {
return random.nextBoolean();
}
/* More stuff here */
}
(Math.random() < 0.5) returns true or false randomly
This should do:
public boolean randomBoolean(){
return Math.random() < 0.5;
}
You can use the following code
public class RandomBoolean {
Random random = new Random();
public boolean getBoolean() {
return random.nextBoolean();
}
public static void main(String[] args) {
RandomBoolean randomBoolean = new RandomBoolean();
for (int i = 0; i < 10; i++) {
System.out.println(randomBoolean.getBoolean());
}
}
}
You will get it by this:
return Math.random() < 0.5;
You can use the following for an unbiased result:
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
Note: random.nextInt(2) means that the number 2 is the bound. the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!
If you want to give more probability to your result to be true (or false) you can adjust the above as following!
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;
//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;
Java's Random class makes use of the CPU's internal clock (as far as I know). Similarly, one can use RAM information as a source of randomness. Just open Windows Task Manager, the Performance tab, and take a look at Physical Memory - Available: it changes continuously; most of the time, the value updates about every second, only in rare cases the value remains constant for a few seconds. Other values that change even more often are System Handles and Threads, but I did not find the cmd command to get their value. So in this example I will use the Available Physical Memory as a source of randomness.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public String getAvailablePhysicalMemoryAsString() throws IOException
{
Process p = Runtime.getRuntime().exec("cmd /C systeminfo | find \"Available Physical Memory\"");
BufferedReader in =
new BufferedReader(new InputStreamReader(p.getInputStream()));
return in.readLine();
}
public int getAvailablePhysicalMemoryValue() throws IOException
{
String text = getAvailablePhysicalMemoryAsString();
int begin = text.indexOf(":")+1;
int end = text.lastIndexOf("MB");
String value = text.substring(begin, end).trim();
int intValue = Integer.parseInt(value);
System.out.println("available physical memory in MB = "+intValue);
return intValue;
}
public boolean getRandomBoolean() throws IOException
{
int randomInt = getAvailablePhysicalMemoryValue();
return (randomInt%2==1);
}
public static void main(String args[]) throws IOException
{
Main m = new Main();
while(true)
{
System.out.println(m.getRandomBoolean());
}
}
}
As you can see, the core part is running the cmd systeminfo command, with Runtime.getRuntime().exec().
For the sake of brevity, I have omitted try-catch statements. I ran this program several times and no error occured - there is always an 'Available Physical Memory' line in the output of the cmd command.
Possible drawbacks:
There is some delay in executing this program. Please notice that in the main() function , inside the while(true) loop, there is no Thread.sleep() and still, output is printed to console only about once a second or so.
The available memory might be constant for a newly opened OS session - please verify. I have only a few programs running, and the value is changing about every second. I guess if you run this program in a Server environment, getting a different value for every call should not be a problem.
ThreadLocalRandom.current().nextBoolean()
To avoid recreating Random objects, use ThreadLocalRandom. Every thread has just one such object.
boolean rando = ThreadLocalRandom.current().nextBoolean() ;
That code is so short and easy to remember that you need not bother to create a dedicated method as asked in the Question.