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.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
public static int createArray(int theListSize)
{
ArrayList<Integer> possiblePrimeNum = new ArrayList<Integer>();
for (int i=0; i<=theListSize; i++) //simply creates the array
{
possiblePrimeNum.add(i, i+2);
}
return possiblePrimeNum;
}
I don't understand this code. I mean that I understand what I'm going to do, but I don't know why the array won't return. What's wrong here?
possiblePrimeNum=createArray(theListSize);
You declared this method as returning a single int value, a single number, and a primitive (not an object).
An ArrayList is a collection of numbers, Integer objects (not primitives).
You said:
Dynamic 1D Array
I do not know what you mean by "Dynamic".
An array in Java is not the same as an ArrayList. The first is a built-in basic type in Java. The second is a class found in the Java Collections Framework, bundled with all Java distributions.
Tutorial on arrays by Oracle
Tutorial on Collections by Oracle
You asked:
I mean that I understand what I'm going to do, but I don't know why the array won't return.
Change your method to return a List of Integer objects rather than a single int. Something like this.
public static List < Integer > possiblePrimes ( final int countOfPrimes )
{
List < Integer > possiblePrimes = new ArrayList < Integer >( countOfPrimes );
for ( int i = 0 ; i <= countOfPrimes ; i++ )
{
possiblePrimes.add( i , i + 2 );
}
return List.copyOf( possiblePrimes ); // Return a unmodifiable list, as a general best practice.
}
Call that method like this.
List < Integer > maybePrimes = App.possiblePrimes( 7 );
System.out.println( "maybePrimes = " + maybePrimes );
When run:
maybePrimes = [2, 3, 4, 5, 6, 7, 8, 9]
I think your algorithm for finding candidate primes needs some more work. 😵💫
If you really want an array, see:
How to convert an ArrayList containing Integers to primitive int array?
Convert ArrayList of Integer Objects to an int array?
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 6 years ago.
Improve this question
I'm currently learning Java and I stumbled on an exercise I can't finish.
The task is to write a recursive method that takes an array and returns the difference of the greatest and smallest value.
For example {12, 5, 3, 8} should return 5 (8 - 3). It is important to note that it is only allowed to compare values in their right order (result = rightValue - leftValue). For example 12-3 = 9 would not be allowed. Think of it like stock values. You want to find out which time to buy and sell the stocks to make the largest profit.
It was quiet easy to implement this iterative but I have no idea how to do it recursive. Also it is part of the task to solve it by using divide and conquer.
I've used divide and conquer approach here. I believe the trick here is to include middle in both the arrays that we're splitting the main array into.
/* edge cases ignored here */
int findMax(int[] arr, int left, int right){
if(right-left == 1) return (arr[right]-arr[left]);
int middle = left + (right-left)/2;
int max1 = findMax(arr, left, middle);
int max2 = findMax(arr, middle, right);
if(max1 >= 0 && max2 >= 0) return max1+max2;
else return Math.max(max1,max2);
}
Well I don't think recursion is very effective on this. You would probably never do this(other than homework). Something like this would do it:
int findGreatestDifference(Vector<Integer> numbers, int greaterDifference){
if(numbers.size() == 1 ) //return at last element
return greaterDifference;
int newDifference = (numbers.get(0) - numbers.get(1));
if (newDifference > greaterDifference)
greaterDifference = newDifference;
numbers.remove(numbers.size() - 1);
findGreatestDifference(numbers, greaterDifference);
return greaterDifference;
}
first time you call it, pass 0 as the greater difference, and again I don't find this as an effective way to do it. Iteration would be way better for this.
I hope this helps.
Algorithm (this is pretty much a sort task , then the subtraction step is trivial)
1) First sort the arrays (use recursive merge sort for large arrays and recursive insertion for smaller arrays).
Merge sort (https://en.wikipedia.org/wiki/Merge_sort)
Insertion sort (https://en.wikipedia.org/wiki/Insertion_sort)
2) Use the arrays smallest index[0] to get the smallest value & index[array.length-1] to get the largest
3)compute the difference (dont know what you mean by right order?)
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
I have to implement the following function:
public int solution(int[] A) {
// smth
}
However, this function may have zero or more solutions, I mean no solution (then should return -1), one solution, two solutions, etc. As you see the function just has int as return type (not an array) and I cannot change it. What should I do, if for example this function should return two values (5 and 9) or three values (1, 10, and 7)? How can I return them?
I thought about tuples, but I believe there is a better way to solve it.
Why don't you use crypting? This only works, if your solutions and numbers of solutions are small and you know two upper limits (number of solutions and biggest size of solution), but you can put more information in one int. Here mult is a number greater than the greatest expected solution:
public int solution(int[] A) {
int returnValue = 0;
//solution is an array of your solutions
for(i=0; i<solution.length; i++){
returnValue=returnValue*mult;
returnValue+=solution[i];
}
return returnValue;
}
public List<Integer> retrieveSolutions(int solution){
List<Integer> decryptedSolutions = new ArrayList<>();
while(solution>mult){
decryptedSolutions.add(solution%mult);
solution = (int) solution/mult;
}
return decryptedSolutions;
}
Just beware the case solution=0 is ignored here and you might get bigger values than the max-Value of Integer (hence you have to make sure, your upperBound+1 (=mult) power the biggest number of solutions+1 is smaller than the max-Value of Integer). Also negative solutions would break this (you can avoid this, if you know the lower bound of the solutions). An alternative would be (as mentioned in the comments) to put the solutions in an mutable Object given in the arguments:
Either in the array as Peter stated in his answer (works only, if the argument array has more elements, than your solutions) and now you have the solutions in the given array and the return value tells how many solutions you got:
public int solution(int[] A) {
int numberSolutions = solutions.length;
for(int i=0; i<solutions.length; i++){
A[i]=solutions[i];
}
return numberSolutions;
}
or in an extra "bag"
public int solution(int[] A, NumberBag putTheSolutionsHere) {
// puts solutions in your NumberBag, whatever Object you might want to use here (preferable List implementation)
}
If you cannot change the signature, you only option is to change the input. While that would be the worst possible solution, it might be your only one. You could return the number of solutions. e.g.
// return all the positive numbers
public int solution(int[] array) {
// put all the positive numbers at the start.
return numOfPositives;
}
A better solution would be to return an array of results
public int[] solution(int[] input)
If you can't change the function, overload it - write the same function with different signature.
more on overloading
If you can add one argument to the signature, add any Collection and the method will populate the Collection (trivial).
If you cannot change the signature and cannot change the return type : is it for a good reason? Discuss with the one who asked you to do it.
If there is a good reason for that (or if it is a sort of algorithmic exercise), you can use some bit masking. In java, an int is encoded on 32 bits. If the possible solution are smalls, you can divide those 32 bits in small groups and store each solution in a group.
Here is a solution which shows how you could store up to 8 solutions in [0; 15] by using groups of 4 bits:
public static void main(String[] args) throws Exception {
List<Integer> values = Arrays.asList(5, 7, 3, 8, 9);
String collect = values.stream().map(Object::toString).collect(Collectors.joining(", "));
System.out.println("Values to encode : "+collect);
int _1111 = (2 << 3) - 1;
System.out.println("\nMasks : ");
for (int i = 0; i < values.size(); i++) {
System.out.println(padWith0(Integer.toString(_1111 << 4 * i, 2)));
}
System.out.println("\nEncoding : ");
int result = 0;
for (int i = 0; i< values.size() ; i++) {
int partial = values.get(i) << (4 * i);
System.out.println(values.get(i) +" => " + padWith0(Integer.toString(partial, 2)));
result += partial;
}
System.out.println(" => "+Integer.toString(result, 2));
System.out.println("\nRestitution : ");
for(int i = 0; i< values.size(); i++) {
int mask = _1111 << (4 * i);
int partial = (result & mask) >> (4 * i);
System.out.println(Integer.toString(partial, 2) +" => " + partial);
}
}
public static String padWith0(String s) {
return ("00000000000000000000000000000000" + s).substring(s.length());
}
Output :
Values to encode : 5, 7, 3, 8, 9
Masks :
00000000000000000000000000001111
00000000000000000000000011110000
00000000000000000000111100000000
00000000000000001111000000000000
00000000000011110000000000000000
Encoding :
5 => 00000000000000000000000000000101
7 => 00000000000000000000000001110000
3 => 00000000000000000000001100000000
8 => 00000000000000001000000000000000
9 => 00000000000010010000000000000000
=> 00000000000010011000001101110101
Restitution :
101 => 5
111 => 7
11 => 3
1000 => 8
1001 => 9
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 6 years ago.
Improve this question
Actually, this question was asked one of the interviews, I do not know the exact answer, could you explain in detail ?
How would you select 100 random lines from a file with a 1 million
lines? Can`t read file into memory.
Typically, in such scenarios, you do not know the number of items in the input file in advance (and you want to avoid requiring two passes over your data, to check the number of available items first). In that case the solution proposed by #radoh and others, where you will create indices to select from, will not work.
In such cases, you can use reservoir sampling: You only need to know the number of items you want to select (k as follows) and you iterate over the input data (S[1..n]). Below is the pseudocode taken from Wikipedia, I'll leave it to your practice to convert this into a working Java method (the method would typically look something like List<X> sample(Stream<X> data, int k)):
/*
S has items to sample, R will contain the result
*/
ReservoirSample(S[1..n], R[1..k])
// fill the reservoir array
for i = 1 to k
R[i] := S[i]
// replace elements with gradually decreasing probability
for i = k+1 to n
j := random(1, i) // important: inclusive range
if j <= k
R[j] := S[i]
Note that although the code mentions n explicitly (i.e. the number of input items), you do not need to know that value prior to computation. You can simply iterate over an Iterator or Stream (representing lines from a file in your case) and only need to keep the result array or collection R in memory. You can even sample a continuous stream, and at each point in time (at least, as soon, as you've seen k samples) you have k randomly chosen items.
Generate the 100 random (unique) numbers (ranging from 0..1000000-1) into a list and then go through the file reading the lines with indexes from the list. Ideally, the list of numbers should be a Set.
Pseudocode:
int i = 0;
List<String> myLines = new ArrayList();
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
if (myRandomNumbers.contains(i)) {
myLines.add(line);
}
i++;
}
Here's a pretty efficient way to do it:
Iterator<String> linesIter = ...
List<String> selectedLines = new ArrayList();
Random rng = new Random(seed);
int linesStillNeeded = 100;
int linesRemaining = 1000000;
while (linesStillNeeded > 0) {
String line = linesIter.next();
linesRemaining--;
if (rng.nextInt(linesRemaining) < linesStillNeeded) {
selectedLines.add(line);
linesStillNeeded--;
}
}
I haven't coded in Java in a while, so you might want to treat this as pseudo-code.
This algorithm is based on the fact that the probability that any given line (assuming we are uniformly selecting k distinct lines out of a total of n lines) will be contained in the collection with probability k/n. This follows from
1) the number collections of k distinct lines (out of n lines) is choose(n, k),
2) the number of collections of k distinct lines (out of n lines) which contain a particular line is choose(n-1, k-1), and
3) choose(n-1,k-1)/choose(n,k) = k/n
Note that k and n here correspond to linesStillNeeded and linesStillRemaining in the code respectively.
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 8 years ago.
Improve this question
So i'm a beginner and I am trying to figure out how to add more than 2 numbers and display it through the output of netbeans. Its really confusing for me since i'm still new to programming.
First, you need to define variable.
what is variable?
A variable provides us with named storage that our programs can
manipulate.
There are different type variable in Java like int, double, char, String, and so on.
What do I mean by type variable?
determines the size and layout of the variable's memory
he range of values that can be stored within that memory
the set of operations that can be applied to the variable
How to define Variable in Java
data type variable [ = value][, variable [= value] ...] ;
For example , you can define two variable as int type as follows
int firstNumber = 1;
int secondNumber = 2;
Note if you like you can define more than two variables by following up the rules.
you can do Arithmetic Operators on your variables
Operator Description
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Here you want to add so you need to use + operator.
read this which is my source : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
At the end, you should define a variable that carries the summation of two variables like
int sum = number1 + number2;
and print the value on your console by using System.out.print/ln
System.out.print("the summation of number one and number two is " + sum);
Source:
http://www.homeandlearn.co.uk/java/java_int_variables.html
http://www.tutorialspoint.com/java/java_variable_types.htm
int a = 1;
int b = 2;
int c = 3;
int d = a + b + c;
System.out.println(d);
If you want to add up the numbers in an array or collection:
int[] numbers = { 1, 2, 3 };
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println(sum);