I am trying to generate unique random number using the below function. Whenerver I run my code in a loop of 1000, it generates duplicate number also.
Code
private static String randomize() {
int count = 10;
List<Integer> digits = createList(count);
Collections.shuffle(digits); // this re-arranges the elements in the list
return listToString(digits);
}
private static <T> String listToString(List<T> list) {
StringBuilder result = new StringBuilder();
for (T object : list) {
result.append(object);
}
return result.toString();
}
private static List<Integer> createList(int size) {
List<Integer> result = new ArrayList<Integer>(size);
for (int i = 0; i < size; i++) {
result.add(i);
}
return result;
}
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
String strName = randomize();
System.out.println(strName);
}
I searched a lot in google and tried ThreadLocal also, it did not help me. Any help or guide on this will be really helpful. My idea is to generate 10 digit non-repeating random number within a loop.
You're not really generating random numbers, are you? You're generating random permutations of the 10 unique digits [0..9]. (e.g. "0123456789", "9834105672", etc.) Since there are only 3268800 (10!) unique permutations, you have a decent chance of hitting a duplicate with 1000 tries.
(I haven't worked out the math, but since 1000^2 is within an order of magnitude of 10!, my intuition tells me there's at least a 10% chance of a duplicate in any given set. Google "birthday paradox" for details.)
What you want to do, and what #Andrei is trying to explain, is to check/store the result every time you call randomize() to make sure you don't have duplicates. Roughly:
public static void main(String[] args) {
Set<String> results = new HashSet<>(1000);
while (results.size() < 1000) {
String strName = randomize();
if (!results.contains(strName)) {
System.out.println(strName);
results.add(strName);
}
}
}
Unless of course you actually want a set of random numbers:
public static void main(String[] args) {
Set<Long> results = new HashSet<>(1000);
while (results.size() < 1000) {
// Random number on [1E9..1E10]
long random = (long) (Random.nextDouble() * 900000000L) + 100000000L;
if (!results.contains(random)) {
System.out.println(random);
results.add(random);
}
}
}
Related
I have tried some solutions from the forum but did not worked for me, if the answer be specific in kotlin language then it will me more helpful for me.
You can try this out with recursion function that will only return unique random number in the range of 0 to 6.
private var randomNumber: Int = 0
private var integerList: MutableList<Int>? = null
private fun getRandomNumber(): Int {
val rand = Random()
randomNumber = rand.nextInt(7)
if (integerList!!.contains(randomNumber)) {
getRandomNumber()
} else {
integerList!!.add(randomNumber)
}
return randomNumber
}
As Andrew Thompson say here you can
Add each number in the range sequentially in a list
Shuffle it
Take the first 'n' numbers from the list
A simple implementation would be:
import java.util.ArrayList;
import java.util.Collections;
public class UniqueRandomNumbers {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<11; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<3; i++) {
System.out.println(list.get(i));
}
}
}
This would print 3 unique random numbers from 1 to 10
int[] Numbers;
int num = 0;
getRandomNum();
public void getRandomNum()
{
Random rand = new Random(10);
if(Numbers.contains(rand))
{
Log.i("console","Try Again");
}
else
{
num = rand;
Numbers.add(rand);
}
}
First of all I wouldn't recommend a function for that, rather use a class that encapsulates the logic which increases usability.
1st option
You can use the List function (yes, it's really a function here) to generate a list of all possible numbers, then shuffle it and after that iterate over it.
class UniqueRandomNumbers(lowerBound: Int, upperBound: Int) {
private val iterator = List(upperBound - lowerBound) {
lowerBound + it + 1
}.shuffled().iterator()
val next get() = if (iterator.hasNext()) iterator.next() else null
}
2nd option
Alternatively you could generate random numbers until you find one that has not been consumed before.
class UniqueRandomNumbers(val lowerBound: Int, val upperBound: Int) {
private val consumedNumbers = mutableSetOf<Int>()
val next: Int?
get() {
var newNumber: Int
if (consumedNumbers.size == (upperBound - lowerBound + 1)) {
return null
}
do {
newNumber = Random.nextInt(lowerBound, upperBound + 1)
} while (newNumber in consumedNumbers)
consumedNumbers += newNumber
return newNumber
}
}
Usage in both cases:
val numberProvider = UniqueRandomNumbers(0, 2)
// returns 0, 1, 2 or null if all numbers have been consumed
numberProvider.next
Im sorry if this question has been asked a lot. Im still pretty new to programming and obviously have some issues in phrasing questions/searching for answers.
I want to do the following:
My algorithm includes 2 methods. One has the task to find out how many of the numbers between 0 to 30 are even and which one are not. I want those even numbers to be somehow stored and redirected to my second method to get added. How can I store those even numbers?
My code looks currently like this: (not even close to being finished)
public class Add
{
static long method(long end)
{
long number = even;
return;
}
static long even() {
if (i%2 == 0) { // even
}
else { // uneven
}
}
public static void main(String[ ] args)
{
int number = method(30);
System.out.println("");
}
}
edit:Im having formating problems... Im sorry the code looks even harder to understand. Im trying to fix it this instant.
Like it was said in the comments, add them to a list, then iterate the list while updating a variable that will be the sum of the even numbers.
public class Add {
private static ArrayList<Integer> evenNums = new ArrayList<>();
private static void evenNumbers(int max) {
for (int i = 0; i < max; i++) {
if (i % 2 == 0) {
evenNums.add(i);
}
}
}
private static int sum(ArrayList<Integer> array){
int sum = 0;
for(int i = 0; i < array.size(); i++){
sum = sum + i;
}
return sum;
}
public static void main (String[]args){
evenNumbers(30);
int sum = sum(evenNums);
System.out.println(sum);
}
}
I'm creating a program that will generate 100 random numbers between 1 and 1000, add them to a list, and then sum up those numbers. Here's my code:
public class Iteration {
public static void main (String [] args){
private int RandomDataAnalyzer(int Rando) {
Random rand = new Random();
List<Integer> NumList = new ArrayList<Integer>();
for (int i=0;i<=100;i++){
Rando = rand.nextInt(1001);
NumList.add(Rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
Rando = rand.nextInt(100);
sum = sum + Rando;
}
return sum;
}
}
}
And here's my errors:
H:\Java\Iteration.java:12: error: illegal start of expression
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
Any help, please?
You can't define a method inside another method. Close your main method first, then start RandomDataAnalyzer:
public static void main(String[] args) {
// Contents of main.
}
public int RandomDataAnalyzer(int Rando) {
// Contents of RandomDataAnalyzer.
}
I'm going to assume that this isn't a homework problem and that you're learning Java on your own. If I'm wrong, shame on me for giving a working version. But my impression is that you'll learn from this:
public class gpaCalc
{
static Random rand;
static int rando;
public static void main(String[] args)
{
ArrayList<Integer> NumList = new ArrayList<>(); // use ArrayList
for (int i=0;i<=100;i++)
{
rand = new Random();
rando = rand.nextInt(1001);
NumList.add(rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
rando = NumList.get(i); // get is "opposite" of put--get the value put into the list earlier
sum = sum + rando;
}
System.out.println(sum);
}
}
There doesn't seem to be a need for a separate method called randomDataAnalyzer.
Welcome to StackOverflow.
Let's begin with the first issue: randomDataAnalyzer is being defined inside main method. Which is wrong, you should be actually defining it at the same level.
Taken into consideration, you should also add the static word before this function because this method is part of the class, and not of the elements. It's not necessary to create a new element of the class 'Iteration' for using a simple method.
Last, but not least, you are looping through the arraylist incorrectly. You are not even calling it. As you will see now:
import java.util.*;
public class Iteration
{
public static void main(String[] args)
{
ArrayList<int> numberList = new ArrayList<int>(); // we define the arraylist
for (int i = 0; i < 100; i++)
{
numberList.add(new Random().nextInt(1001)); // we add a random number to the list
}
// finally, after the 100 values were added..
System.out.println(randomDataAnalyzer(numberList)); // we show the output
}
public static int randomDataAnalyzer(ArrayList<int> list) // we will send this function an arraylist which will get the Σ.
{
int sum = 0;
for (int value : list) // this is how we loop through foreach value in the list
{
sum += value; // which means sum = sum + value.
}
return sum; // after looping and summing up, here'll be the result
}
}
I hope this was what you were looking for.
Here's a working version. Note the changes to your original:
Don't define methods inside methods: it is illegal syntax.
Rando, NumList: the naming conventions are to start classes, interfaces, enums (i.e. types) with a capital letter, and methods, fields, and variables with a lowercase case letter;
Removed the int Rando parameter alltogether: it's value was never used (it was only assigned to)
Use the values from numList rather than generating new numbers.
Added a method illustrating that the use of such a list is not needed in this case; the 'list' of 1000 numbers is still present, but only conceptually.
import java.util.*;
public class Iteration {
public static void main (String [] args) {
int sum = new Iteration().randomDataAnalyzer();
System.out.println(sum);
}
private int randomDataAnalyzer() {
Random rand = new Random();
List<Integer> numList = new ArrayList<Integer>();
for ( int i=0; i<100; i++ )
{
numList.add( 1 + rand.nextInt(1000) );
}
int sum = 0;
for ( int i=0; i<numList.size(); i++ )
{
sum = sum + numList.get(i);
}
return sum;
}
// Note that the above method has the same effect as this one:
private int moreEfficient() {
Random rand = new Random();
int sum = 0;
for ( int i=0; i < 100; i++)
sum += 1 + rand.nextInt(1000);
return sum;
}
}
I want to make a function that pick a randomly number in array and avoid to pick the same number in next time.
Here is my code (it work in sometime and mostly inf-loop)
please help me, Thank you.
private static int pick(int[] x) {
int upperbound = x[x.length-1];
int lowerbound = x[0];
int count=0;
int ranvalue;
int ranindex;
Random rand = new Random();
do{
ranindex = rand.nextInt(upperbound-lowerbound) + lowerbound;
count++;
}while(x[ranindex]==-1||count!=x.length-1);
ranvalue=x[ranindex];
x[ranindex]=-1;
return ranvalue;
}
If your array has size n, then you can get at most n different indexes. I advise the following :
Create an array with numbers from 0 to n-1.
Shuffle it.
At each step, take the next element from this array and use it as an offset for your source array.
You should also wrap this logic into a class like this :
public class Picker {
private int[] source;
private List<Integer> offsets;
private int currentIndex = 0;
public Picker(int[] source) {
this.source = source;
Integer[] indexes = new Integer[source.length];
for(int i=0;i<source.length;i++) {
indexes[i] = i;
}
this.offsets = Arrays.asList(indexes);
Collections.shuffle(this.offsets);
}
public Integer next() {
return source[offsets.get(currentIndex++)];
}
}
Example :
public static void main(String[] args) {
int[] source = {8,3,5,9};
Picker picker = new Picker(source);
for(int i = 0; i<4;i++) {
System.out.println(picker.next());
}
}
Output :
5
3
8
9
EDIT : Or even simpler :
Integer[] source = {8,3,5,9};
//Copy the source and shuffle it
List<Integer> dest = Arrays.asList(source);
Collections.shuffle(dest);
//Then display
for (int i = 0;i<source.length;i++) {
System.out.println(dest.get(i));
}
I'm trying to solve Project Euler problem #16, where I need to sum all the digits of 2^1000. I've gotten stuck dealing with such a big number. My program worked for any number below 10^16, but failed afterwards. This told me that my logic was correct. I went ahead and converted all variables and methods to BigDecimal, but now the program does not run properly. It compiles as it is and there is no error; it just does not terminate. Does anyone have an idea on where I went wrong here?
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Powerdigitsum {
private static final BigDecimal one = new BigDecimal("1");
private static final BigDecimal ten = new BigDecimal("10");
private static BigDecimal sumofDigits(BigDecimal n){
BigDecimal sum = new BigDecimal("0");
while(n.compareTo(one) == 1 || n.compareTo(one) == 0){
sum.add(n.remainder(ten));
n.divide(ten);
n = n.setScale(0, RoundingMode.FLOOR);
}
return sum;
}
public static void main(String[] args) {
final double the_number = Math.pow(2,1000);
final double test = 15;
final BigDecimal two_to_the_thousandth_power = new BigDecimal(test);
System.out.println(sumofDigits(two_to_the_thousandth_power));
}
}
Just use BigInteger properly:
BigInteger a = new BigInteger("2").pow(1000);
The whole method is kinda wrong. See this:
private static BigInteger sumOfDigits(BigInteger n) {
BigInteger sum = BigInteger.ZERO;
while (n.compareTo(BigInteger.ZERO) == 1) {
sum = sum.add(n.remainder(ten));
n = n.divide(ten);
}
return sum;
}
You needed to compare to zero, not one. And you need to assign the values for BigIntegers and BigDecimals, their methods do nothing on their own, the instances of those classes are immutable.
For integers, it's generally better to use BigInteger. The decimal part (that gets there from dividing) is just thrown away.
final double the_number = Math.pow(2,1000);
This won't work because the_number is not large enought to take the result. You need to convert the pow call to BigInteger:
BigInteger result = new BigInteger("2").pow(1000);
But be aware.. this can take some time..
Don't use the BigDecimal(double) constructor: it is limited by the double primitive type, which cannot represent 2^1000.
You can use a BigInteger. Something along these lines should work (probably suboptimal, but...):
public static void main(final String... args)
{
// 2^1000
final BigInteger oneTo2000 = BigInteger.ONE.shiftLeft(1000);
BigInteger digitSum = BigInteger.ZERO;
// We don't want to split against the empty string, the first element would be ""
for (final String digit: oneTo2000.toString().split("(?<=.)"))
digitSum = digitSum.add(new BigInteger(digit));
System.out.println(digitSum);
}
public class SumofDigitsPow {
public static void main(String[] args) {
//2(2^1000)
String temp = BigInteger.ONE.shiftLeft(1000).toString();
int sum = 0;
for(int i=0;i<temp.length();i++){
sum+= temp.charAt(i) - '0';
}
System.out.println(Integer.toString(sum));
}
}
java.math.BigInteger.shiftLeft(int n) method returns a BigInteger whose value is (this << n),So you can get the answer by using BigInteger and LeftShift Method
import java.math.BigInteger;
public class Problem16 {
public static void main(String[] args) {
BigInteger number2 = new BigInteger("2");
BigInteger number3 = new BigInteger("0");
number3 =number2.pow(1000);
String str = number3.toString();
BigInteger sum = new BigInteger("0");
for(int i=0; i<str.length(); i++)
{
char c= str.charAt(i);
int value = Character.getNumericValue(c);
BigInteger value2 = new BigInteger(Integer.toString(value));
sum =sum.add(value2) ;
}
System.out.println(sum);
}
}
IF YOU THINK BIGINTEGER IS CHEATING AND/OR don't feel like using it/learning how to use it, this algorithm is the way to go.
Think about how you would calculate 2^1000 by hand. You'd start with 2^1 and multiply by two repeatedly. Now notice that the number of digits of powers of two increase by 1 for AT LEAST every 3 powers (could be after 4 powers like with 1024 to 8192). So make a jagged 2D array like this
int a[][]= new int[1000][];
for(int i=0;i<1000;i++)
{
a[i]= new int[1+(i/3)];
}
Then initialize a[0][0] to 2. After this, you want to write a for loop such that each row is filled from the rightmost spot. So make two variables "digit" and "carry". Digit is the number that you will input into the row you're working on, and the carry is the one you're going to take to the next calculation and add to the product of 2 and whatever digit you're multiplying it with. Be careful with the order you update digit and carry and reinitialize them to zero after every calculation. I think the hardest part is coming up with the limits for the for loop, so that it fits with the every 3 powers thing. You can make this simpler by just making a triangular jagged array that increments by one every row. I did it like this though. Here's my whole code.
import java.util.*;
public class ProjectEuler16
{
public static void main(String[] args)
{
long t1=System.currentTimeMillis();
ProjectEuler16 obj = new ProjectEuler16();
System.out.println(obj.bigNumHandler());
long t2= System.currentTimeMillis();
System.out.println(t2-t1);
}
int bigNumHandler()
{
int a[][] = new int[1000][];
for(int i=0;i<1000;i++)
{
a[i]= new int[1+(i/3)];
}
a[0][0]=2;
for(int i=1;i<1000;i++)
{
int carry=0;
int digit=0;
int f=0;
if(i%3==0)
{
f=1;
}
for(int j=a[i-1].length-1+f;j>=0;j--)
{
if(j==0&f==1)
{
a[i][0]=carry;
}
else
{
digit=((2*a[i-1][j-f])+carry)%10;
carry=((2*a[i-1][j-f])+carry)/10;
a[i][j]=digit;
}
}
}
int sum=0;
for(int k=0;k<a[999].length;k++)
{
sum=sum+a[999][k];
}
return sum;
}
}
Note that the last row lists the digits for 2^1000.I think you can figure out how to sum the digits. The program took about 5 seconds to come up with the answer.
solution::::
import java.math.BigInteger;
public class PR9 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BigInteger zero=BigInteger.valueOf(0);
BigInteger ten=BigInteger.valueOf(10);
BigInteger sum=zero;
BigInteger a = new BigInteger("2").pow(1000);
while(a.compareTo(zero)>0){
sum=sum.add(a.mod(ten));
a=a.divide(ten);
}
System.out.println(sum);
}
}
output:::::
1366
import java.math.BigInteger;
public class P16 {
public static BigInteger digitSum(int n) {
BigInteger sum = BigInteger.ZERO;
BigInteger number = new BigInteger("2").pow(n);
while (number.compareTo(BigInteger.ZERO) == 1) {
BigInteger remainder = number.remainder(BigInteger.TEN);
sum = sum.add(remainder);
number = number.divide(BigInteger.TEN);
}
return sum;
}
public static void main(String[] args) {
final double START = System.nanoTime();
System.out.println(digitSum(Integer.parseInt(args[0])));
final double DURATION = System.nanoTime() - START;
System.out.println("Duration: " + DURATION / 1000000 + "ms.");
}
}
While there maybe a way of solving this problem without the use of BigIntegers, it is clear that they make the code run way faster.
Mine only took about 4ms to find an answer.