java random numbers generator which generate twenty four numbers - java

I want to create a program that gives a random 24 digit number. I have tried different ways but I can't figure out how to make it. An example response would be 392834756843456012349538, which is just a random twenty four digit number.

Here's the easiest way I can think of:
#Test
public void random24Numbers() {
String random = RandomStringUtils.random(24, false, true);
System.out.println(random);
}
This uses RandomStringUtils.random. The first parameter is the length, the second says, "no letters". The third says, "give me numbers". Here's an example output:
564266161898194666197908
Yes, it's a String, but I'm going to assume you know how to convert a String into a number.

This sample works for generating numbers of 'digits' length including leading zeros and doesn't require any external jar files.
private String generateInt(int digits) {
StringBuilder str = new StringBuilder();
Random random = new Random();
for(int i = 0; i < digits; i++) {
str.append(random.nextInt(10));
}
return str.toString();
}
An example response would be:
081140561664657769754888

The following uses only core java.lang stuff and seems to get the job done. As in other solutions, the result is a string rather than a java numeric type because none of the basic java datatypes can store 23-digit decimal numbers.
import java.lang.Math;
import java.lang.StringBuilder;
public class random24 {
static char digits[] = {'0','1','2','3','4','5','6','7','8','9'};
public static char randomDecimalDigit() {
return digits[(int)Math.floor(Math.random() * 10)];
}
public static String randomDecimalString(int ndigits) {
StringBuilder result = new StringBuilder();
for(int i=0; i<ndigits; i++) {
result.append(randomDecimalDigit());
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(randomDecimalString(24));
}
}

int[] randomNumbers = new int[24];
for(int i = 0; i < 24; i++) {
randomNumbers[i] = (int)Math.floor(Math.random() * 10);
System.out.println(randomNumbers[i]);
}
Added in response to the comment below, code to set a label with this random number sequence:
String randomString = "";
for(int i = 0; i < 24; i++) {
randomString = randomString.concat(String.valueOf((int)Math.floor(Math.random() * 10)));
}
NumbersLabel.setText(randomString);

See How to generate a random BigInteger value in Java? where code is provided which does generate a BigInteger random number not greater than n:
BigInteger r;
do {
r = new BigInteger(n.bitLength(), rnd);
} while (r.compareTo(n) >= 0);

Related

Is there a way to use Math.random instead of import java.util.Random but keep the same output

so I want to use Math.random instead of importing java.until.Random but keep the same output of my code
This is my code:
import java.util.Random;
public class MyStrings {
public String randomAlphanumericString(int length) {
String letters = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String randomWord = "";
Random random = new Random();
for (int i = 1; i <= length; i++) {
randomWord += String.valueOf(letters.charAt(random.nextInt(letters.length())));
}
return randomWord;
}
public boolean validAlphanumericString(String word) {
for (char letter : word.toCharArray()) {
if (Character.isLetter(letter) || Character.isDigit(letter)) {
} else { System.out.println(word + " contains non alphanumeric characters");
return false;
}
}
return true;
}
}
I think you are looking for something like:
...
randomWord += String.valueOf(letters.charAt((int) (Math.random() * letters.length())));
...
From the JavaDoc for Math.random():
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
So that's why if you just multiply by the length and truncate it to int you get the range that you need.
If you write a Lambda to get a random value, you can use it just like
Random.nextInt()
IntFunction<Integer> rand = x-> (int)(Math.random()*x);
int v = rand.apply(10); // value between 0 and 9 inclusive.

Scrambling characters of String

public class WordScrambleEx1 {
public static void main(String[] args) {
String[] strArr = {"CHANGE", "LOVE", "HOPE", "VIEW"};
String answer = getAnswer(strArr);
String question = getScrambledWord(answer);
System.out.println("Question :" + question);
System.out.println("Answer: " + answer);
}
public static String getAnswer(String[] strArr) {
String i = strArr[(int)Math.random()*4];
return i;
}
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = null;
for(int i = 0; i < character.length; i ++)
{
char[] java = new char [(int)Math.random()*i] ;
question1 = new String(java);
}
return question1;
}
}
I am very new to Java and was given a question where I am given four letters of words and my method needs to pick one of them randomly using Math.random and scramble the characters of that string.
My code finds a String from the given array but does not scramble the string. Can anyone tell me what I am doing wrong?
Understanding constructor and scope is really hard.
first mistake:
(int) Math.random() * i
will always return 0, because Math.random() returns a float between 0 and 1, so it will always be zero when you cast it to int (int doesnt round, it just cuts off the numbers after the comma).
you can fix this by using this:
(int) (Math.random() * i)
now we are first multiplying the float result of Math.random() with i which results in a float because the first number is a float. then we are casting this float to an int.
second mistake:
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = null;
for(int i = 0; i < character.length; i ++)
{
char[] java = new char [(int)Math.random()*i] ;
question1 = new String(java);
}
return question1;
}
each iteration you create a new char array with a length of 0 and then you set question1 to it, which is always an empty string because the java array has nothing in it.
i would do it as follows:
public static String getScrambledWord(String str) {
char[] character = str.toCharArray();
String question1 = new String();
ArrayList<Character> chars = new ArrayList<Character>(); //an arraylist is an array wich dynamically changes its size depending on the amount of its elements
for (int i = 0; i < character.length; i++) {// first we put all characters of the word into that arraylist
chars.add(character[i]);
}
while(chars.size()>0){//then we iterate over the arraylist as long as it has more than 0 elements
int index = (int)(Math.random() * chars.size());//we create a random index in the range of 0 and the arraylists size
question1 += chars.get(index);// we add the letter at the index we generated to the scrambled word variable
chars.remove(index);// then we remove the character we just added to the scrambled word, from the arraylist, so it cant be in there twice
}// thus the size decreases by 1 each iteration until every element of the arrraylist is somewhere in the scrambled word
return question1;
}
There are some mistakes in your code. The way you generate random integers is misleading. Let's look at the statement (int)Math.random() * 4 for an explanation. Math.random() does:
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Now, in Java a type cast has precedence over +, -, * and /, so what actually happens is ((int)Math.random()) * 4. Math.random() returns a floating point number between 0.0 and 1.0 exclusive, so roughly [0.0, 0.999999...]. A cast to int will truncate all decimal places and you will always get 0. Your statement then simplifies to 0 * 4 = 0. Overall, you always get the first word.
I recommend you to use the Random class instead. It provides a method nextInt(int n), which returns a random integer between 0 inclusive and n exclusive, so [0, n - 1].
Since there are a lot of errors in your code, I would like to provide you this solution:
import java.util.Random;
public class WordScrambleEx1 {
private static Random random;
public static void main(String[] args) {
// Create object of class (initializes the
// random generator with a default seed)
random = new Random();
String[] strArr = { "CHANGE", "LOVE", "HOPE", "VIEW" };
String answer = getAnswer(strArr);
String question = getScrambledWord(answer);
System.out.println("Question: " + question);
System.out.println("Answer: " + answer);
}
public static String getAnswer(String[] strArr) {
// Chooses a random index in [0, strArr.length - 1]
int index = random.nextInt(strArr.length);
String i = strArr[index];
return i;
}
public static String getScrambledWord(String str) {
String remaining = str;
String scrambled = "";
// Loop over the string, each time choose a random letter
// and add it to the scrambled word, then remove that letter
// from the remaining word. Repeat until all letters are gone.
for (int i = str.length(); i > 0; i--) {
// Choose the index of a letter in the remaining string
int index = random.nextInt(remaining.length());
// Add the letter at the random index to your scambled word
scrambled += remaining.charAt(index);
// Remove the chosen character from the remaining sequence
remaining = remaining.substring(0, index) + remaining.substring(index + 1);
}
return scrambled;
}
}

Converting Decimal into binary in java

I am trying to convert decimal to binary numbers from the user's input using Java but so far, I'm running into errors I'm not sure why. What am I doing wrong? Don't mind the naming, ultimately I would like to convert decimal into binary without using if and while statements. Also without using the decimaltobinary string.
Thanks a lot.
package r
public static void main(String[] args) {
int number;
int remainder;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
remainder= number %2;
System.out.print(remainder);
{
return null;
This is what I have so far.
This is how to convert a decimal to binary :
Using for loop :
public class DecimalToBinary {
public void printBinaryFormat(int decimalNumber){
int remainder = 0;
for (int i = 1; decimalNumber > 0; i++) {
remainder = decimalNumber % 2;
decimalNumber /= 2;
System.out.print(remainder);
}
}
public static void main(String a[]){
DecimalToBinary dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Using while loop :
public class DecimalToBinary
{
public void printBinaryFormat(int number){
int binary[] = new int[25];
int index = 0;
while(number > 0){
binary[index++] = number%2;
number = number/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
}
public static void main(String a[]){
DecimalToBinary dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Hope I helped .
Happy Coding :D
Try this:
String binaryString = Long.toBinaryString(Double.doubleToRawLongBits(yourDecimalNumber));
Where yourDecimalNumber is the name of the decimal variable that you want to convert to binary.
You can also use a for loop and bitwise operation without using any if or while statements like so:
int number = 10;
String binaryString = "";
final int intBitSize = 32; // 32 is the number of bits in an int.
for(int i=0; i<intBitSize; i++)
{
binaryString = String.valueOf(number&1) + binaryString;
number = number >>> 1;
}
System.out.println(binaryString);

scrambling a string using .toCharArray()

My problem is that I am trying to make (for example) String "asdf" changed to "sdfa" by using Random() and .toCharArray().
How do I not get duplicate random numbers?
I figure that I am supposed to create a new Char array in order to randomly store the char's without changing my original array because if I do, then the new string will be messed up, if that makes any sense.
I didn't do it here in this code, but that might be an alternative???
edit: I have made it into a main class, which should make it easier. Thank You.
import java.util.Random;
public class Scramble {
public static void main(String[] args) {
String str = "asdf";
Random randomGenerator = new Random();
int lengthOfStr = str.length();
char[] chars = str.toCharArray();
// do for length of str
for (int i=0; i < lengthOfStr; i++)
{
int n = randomGenerator.nextInt(lengthOfStr);
chars[i] = chars[n];
String newStr = new String(chars);
str = newStr;
}
System.out.println(str);
}
}
Look up the Fisher-Yates shuffle for how to correctly randomly scramble an array. (That algorithm, by the way, is perfectly suited to how Java's random number generators provide you with random numbers, and doesn't require making your random numbers unique.)
As to your first question, you can avoid (to a large extent) duplicated random numbers by making the random number generator a member of your class, as opposed to a local variable in your method. The following code should generate a fairly random distribution of scrambled words. You can blame its length on the lack of a shuffle method that can work with primitive arrays. Adapt as appropriate to your needs:
public class Flipper {
Random randomGenerator = new Random();
public static void main(String[] args) {
final String sample = "Hello World";
final Flipper flipper = new Flipper();
for (int i = 0; i < 100; i++) {
System.out.println(flipper.scramble(sample));
}
}
public String scramble(String str) {
if (str == null)
return null;
char[] arr = str.toCharArray();
List<Character> charList = new ArrayList<Character>(arr.length);
for (final char c : arr) {
charList.add(c);
}
Collections.shuffle(charList, randomGenerator);
char[] converted = new char[charList.size()];
for (int i = 0; i < charList.size(); i++) {
converted[i] = charList.get(i).charValue();
}
return new String(converted);
}
}
Here is a simple one with a O(n) duration order. The loop has only 3 instructions:
It appends the random char in a new string and removes it from the original one, so when the next random char is obtained, the previously obtained chars are not eligible.
I noticed after writing this function that it seems it is a form of the Fisher–Yates shuffle algorithm.
public class Scramble {
public static String scramble(String str) {
StringBuilder newStringBuilder = new StringBuilder();
StringBuilder stringBuilder = new StringBuilder(str);
while (stringBuilder.length() > 0) {
int n = (int)(Math.random() * stringBuilder.length()));
newStringBuilder.append(stringBuilder.charAt(n));
stringBuilder.deleteCharAt(n);
}
return newStringBuilder.toString();
}
public static void main(String[] args) {
System.out.println(scramble("hola"));
}
}

Java: How to format String number with tenth exponent

I have a number as a string like this: "9.756088256835938E-4" but I only can use a specified number of characters (in this special case 9 char). So I want to have something like this: "9.7561E-4". I already tried to convert the String to a Double and then used the format method to get a less characters but I don't got a correct solution.
The problem is that I need ten exponential output since some numbers are longer than the number of characters I have. If it is possible, the number should be displayed with no ten exponent, if not just use the ten exponent.
Also correct rounding would be good.
And it should work for negative numbers. (minus needs one character!!!)
Is there a format function where I can define the maximum length of the output string? Any ideas?
I'm having trouble findind a single format pattern that will cover all of the cases that you described. But here's a combination of logic that I think works:
public static void main(String[] args) throws Exception {
// 97.560883
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+1")));
// 9.756E+11
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+11")));
// 0.0009756
System.out.println(formatNum(Double.parseDouble("9.756088256835938E-4")));
// -9.8E+111
System.out.println(formatNum(Double.parseDouble("-9.756088256835938E+111")));
}
private static final int MAX_LENGTH = 9;
private static String formatNum(double number) {
String out = null;
for ( int i = 0; i < MAX_LENGTH; i++ ) {
String format = "%." + i + "G";
out = String.format(format, number);
if ( out.length() == MAX_LENGTH ) {
return out;
}
}
return out; //the best we can do
}
The "G" in the pattern instructs the formatter to forego the use of the exponent when it will allow for the same or better precision. We grow up to the maximum length and stop when our output string is 10 characters. I think you could take the same approach with a DecimalFormat, but I'm more familiar with Formatter.
Seeing the Mark's example meet your requirements, I updated my answer to show the DecimalFormat implementation. I used Mark's test cases. It is definitely an uglier option because there is no easy way to turn on/off exponents. The only advantage over the String.format option is that it handles very small numbers well.
public static void main(String[] args) throws Exception {
// 97.560883
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+1")));
// 9.756E+11
System.out.println(formatNum(Double.parseDouble("9.756088256835938E+11")));
// 0.0009756
System.out.println(formatNum(Double.parseDouble("9.756088256835938E-4")));
// -9.8E+111
System.out.println(formatNum(Double.parseDouble("-9.756088256835938E+111")));
}
private static final int MAX_LENGTH = 9;
private static String formatNum(double number) {
int digitsAvailable = MAX_LENGTH - 2;
if (Math.abs(number) < Math.pow(10, digitsAvailable)
&& Math.abs(number) > Math.pow(10, -digitsAvailable)) {
String format = "0.";
double temp = number;
for (int i = 0; i < digitsAvailable; i++) {
if ((temp /= 10) < 1) {
format += "#";
}
}
return new DecimalFormat(format).format(number);
}
String format = "0.";
for (int i = 0; i < digitsAvailable; i++) {
format += "#";
}
String r = new DecimalFormat(format + "E0").format(number);
int lastLength = r.length() + 1;
while (r.length() > MAX_LENGTH && lastLength > r.length()) {
lastLength = r.length();
r = r.replaceAll("\\.?[0-9]E", "E");
}
return r;
}
This reminded me of a similar question where the OP only had 5 or so spaces for a number and wanted to show a decimal only when there was enough space. But instead of exponents, wanted to use a suffix of (k,m, etc)

Categories

Resources