Assign a value to Integer between two constant values? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Lets say I have 3 Integers:
int a, b, c;
b = 25;
c = 10;
Now I want a to be either 25 or 10 but by random not something like:
a = b;
I want something like in if statement:
a = b || c;
How can I achieve it?

if(Math.random() < 0.5)
a = 25;
else
a = 10;
Math.random() returns a random number from 0 to 1, so if you want a 50% chance of something being true, just check if it's less than (or greater than) 0.5.

one way is to do by taking the millis of time like:
if(System.currentTimeMillis() % 2 == 0){
a=b;
} else{
a=c;
}

#immibis' answer is the simplest way to achieve this.
For testability, I would strongly advise that you use an explicit Random instance, rather than using Math.random():
static int pickRandomValue(Random r, int b, int c) {
return r.nextInt(2) == 1 ? b : c;
}
This allows you to inject a mock Random instance, allowing you to fix the behaviour when you need to test specific behaviour. Non-deterministic tests are a pain, and should be avoided.

Try the below code:
Random rand = new Random();
int myRandom = rand.nextInt(2); // will be 0 or 1
if (myRandom == 0) {
a=b;
} else {
a=c;
}

Related

How in the most elegant way output unknown number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
my method is getting one number and this number contains in [0, 1, 2]. And i am looking for the most elegant and straightforward way to get two others from this array. For now, I came up with that:
method(int number){
int firstNumber = number;
int secondNumber;
int thirdNumber;
List<Integer> rows = new ArrayList<>();
rows.add(0);
rows.add(1);
rows.add(2);
rows.remove(Integer.valueOf(number));
secondNumber = rows.remove(0);
thirdNumber = rows.remove(0);
}
but this solution takes so many lines
Streams.
public static List<Integer> method(int i) {
return Stream.of(0, 1, 2).filter(j -> j != i).collect(Collectors.toList());
}
To elaborate, since streams can be rather unreadable if you don't know what they're doing, Stream.of() creates a stream with the hardcoded values there, though it actually accepts varargs, so you can send an actual array. If you have a list, you can use List.stream().
.filter() accepts a function which should return a boolean. If it returns false, that particular value stays in the stream and is passed on to the next stage, if it returns true, it is filtered out (removed).
.collect() takes the stream and collects the values into, in this case, a List, though you can use Collectors.toSet() to get a Set, or write your own custom method to do return whatever you want.
Use modulo to find the others:
public static void method(int number){
int secondNumber = (number + 1) % 3;
int thirdNumber = (number + 2) % 3;
System.out.println(secondNumber);
System.out.println(thirdNumber);
}
Another variant being:
List<Integer> source = new ArrayList<>(Arrays.asList(0,1,2));
source.removeIf(x -> x == number);
System.out.println(source);
but probably better to just do:
List<Integer> source = new ArrayList<>(Arrays.asList(0,1,2));
source.remove(Integer.valueOf(number));
to benefit from short-circuiting.

Generate 100 random UNIQUE Double numbers between 1-10 in java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to generate a 100 unique random numbers, but the numbers need to be in the range of 1-10.
Right now I am doing this:
for (int i = 0; i < 100; i++) {
Double n = rand.nextDouble(10) + 1;
arr[i] = n;
}
I could get Double numbers by checking if they're unique using if/else statements in arrays but it is very difficult and inefficient because the numbers(Doubles) could be almost infinite.
So how do i make sure the numbers are unique without using arrays?
Are there any data structures in java which do not allow duplicate elements?
As you alluded to in the comments, there's no way to generate 100 unique integers between 1 and 100. Using doubles allows you to do that, but does not guarantee uniqueness by itself (even though there's an infinitesimal chance of getting repeating items), so you would have to guarantee this yourself - e.g., by using a Set:
Set<Double> doubles = new HashSet<>();
while (doubles.size() < 100) {
doubles.add(1 + rand.nextDouble() * 9);
}
EDIT:
JDK 8 provides an arguably more elegant way of achieving this with streams:
List<Double> doubles =
rand.doubles()
.distinct()
.map(d -> 1 + d * 9)
.limit(100)
.boxed()
.collect(Collectors.toList());
You can use something like this.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
double[] arr = new double[100];
for (int i = 0; i < 100; i++) {
Random rand = new Random();
double n = 10*rand.nextDouble();
System.out.println(n);
arr[i] = n;
}
}
}
But it is not possible to get unique 100 integers between 1-10.
The above program generate something like this
4.142037859604101
2.655156962359073
3.7397565068261205
2.9699181925544247
2.747362791293101
3.243100861992423
9.308481386292623
4.96298205308679
3.4319099852820822
9.951375372917328
3.6941158775736316
1.0388381644118727
1.6895078811799191
0.9166823110491484
9.60259797093202
2.3365812211691708
8.556399515524168
2.570971809286772
1.6621912919374215
0.5896588206170794
6.921688301938134
6.325470591144598
2.35492413118687
2.1778674294915454
The class Math has a bunch of useful functions, also at least one which you could use for this.
for(int i = 0; i < 100; i++) {
double n = (Math.random()*9) + 1;
arr[i] = n;
}
Math.random returns a random positive greater than or equal to 0.0 and less than 1.0, so if you multiply that by 9, you get a number greater than or equal to 0.0 and less than 9.0. And then the plus 1 is to make sure the range is between 1 - 10.
If you really want to make sure that all numbers are unique you could write a method that checks if the number is not already in the array.
Hopefully this helps you out. Good luck!

Java: binary series representation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am doing some experiments on my own about quantization processes etc.
I try to implement a binarization process which makes a "binary string" which will get processed by xor afterwards and some other stuff.
Anyhow the binarization is the following, where d and u are some numbers that will get compared:
String b = "";
for (int i = 0; i < u.length; u++) {
if(d[i] < u[i]) {
b[i] += '0';
} else {
b[i] += '1';
}
}
Currently like described I have a string where each character is 0 or 1.
Using a BigInteger gives me an Object where I can XOR two values against each other:
BigInteger bi = new BigInteger(b, 2);
(...)
BigInteger result = bi.xor(other_bi);
Is there another way to achieve what I want to do? I didn't find anything but maybe there is one I have not found?
The BitSet class is more appropriate for representing a sequence of bits. To set a bit you would use the BitSet.set method.
Taking your example as a BitSet.
BitSet bs = new BitSet(u.length);
for (int i = 0; i < u.length; u++)
if(d[i] >= u[i])
bs.set(i);
BitSet bs2 = ...
bs2.xor(bs); // changes and reuses bs2.
int bitsSet = bs2.cardinality();
int firstSetBit = bs2.nextSetBit(0);

Program is supposed to determine if the input number is prime or not [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
//I am supposed to do it with loops and decision statements, but it's not working. Help!
import java.util.Scanner;
public class main {
/**
* #param args
*/
public static void main(String[] args) {
//Declare variables
Scanner abc;
abc = new Scanner (System.in);
int input;
int divide = 2;
int count=0;
//Ask for input
System.out.println("Please enter an integer to determine if it is prime");
input = abc.nextInt();
//Do math
for (int x=1; x < input; x++) {
if ((input%divide) == 0)
count += 1;
divide = divide + 1;
}
if (count == 0)
System.out.println("It is a prime number");
else
System.out.println("It is not a prime number");
}
}
In your for loop, for the last iteration, x = input - 1, but that means divide = input (since divide was one greater in the beginning, and you increment both once per iteration of the loop), so count will actually be equal to 1 if the number is prime, not 0.
You're counting the number of divisors; all you need to do is determine if there is at least one divisor. Here's a better algorithm:
function isPrime(n)
if n is even
return n == 2
d := 3
while d * d <= n
if n % d == 0
return False
d := d + 2
return True
I discuss this algorithm, among others in the essay Programming with Prime Numbers at my blog, which includes implementations in Java.
It looks like count is supposed to count the number of factors of input not counting 1 and input. For readability, I'd recommend using a name like numOfFactors instead of count.
Given that, now look at your loop and answer these questions. I'm not going to give you the answer. (Yes, you can get the answer by looking at others' comments, but I think you will learn more by answering these questions anyway.)
(1) What are x and divide the first time you go through the loop, at the beginning of the loop?
(2) If you look at what happens to x and divide, there's a simple relationship between x and divide at the beginning of each time through the loop. What is it?
(3) What is x the last time you go through the loop?
(4) Based on the answers to #2 and #3, what is divide at the beginning of the last time through the loop? What will input%divide be equal to?
That's why it isn't working. Figure that out first. Then we can talk about how to can make it work more efficiently.
MORE: OK, I'll say one more thing. If all you care about is whether count is zero or not, you can quit your loop as soon as you find a factor. Like this:
if ((input%divide) == 0)
{
count += 1;
break;
}
(And if you do it that way, then instead of count you should use a boolean foundAFactor because all it says is whether you found a factor, not how many there are.)
But if you really want to know the exact number of factors, don't do that.
Hello do it like this:
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("is a prime");
else
System.out.println("is not a prime");
break;
}
}
for (int x=2; x < input; x++) (change x=1 to x=2)
otherwise you end up trying to divide 5 by 5 to test if 5 is prime

Fastest way to sort 3 values in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have to put 3 values in correct order and print them out to the console.
A solution is to put them into an array and then sort them, but I remember (from school times) that there was faster to compare and order them, however I can't find the correct comparison order.
Could you please show me how to compare 3 values with the minimum number of if statements?
bubble sort would have only 3 compare ops, and 6 assignments at worst case (it will be very similar if not identical to the behavior of insertion sort in this case):
if (a > b)
swap(a,b)
if (b > c)
swap(b,c)
if (a > b)
swap(a,b)
print a,b,c
It cannot be done in less then 3 compares because there are n!=6 possible permutations for the array, and ceil(log_2(n!)) = 3
There is no point in optimizing this. It will not gain any speed. O(n!) for 3 is still only 3*2 = 6 operations. Even O(2^n) is going to be 8. You could really do whatever it takes to sort these 3 values and not see a difference in performance.
edit
int a, b, c, min, max, med;//assume values are there for a b c
if( a > b ){
if( a > c ){
max = a;
if( b > c ){
med = b;
min = c;
}else{
med = c;
min = b;
}
}else{
med = a;
max = c;
min = b;
}
}else{
if( b > c ){
max = b;
if( a > c ){
med = a;
min = c;
}else{
med = c;
min = a;
}
}else{
med = b;
max = c;
min = a;
}
}
As far as i know, Java uses the Quicksort algorithm for sorting - an already optimized approach. No speed to harvest here!

Categories