Sorting values off array in Java [closed] - java

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 5 years ago.
Improve this question
I am new to this site and new to java so pleas help me out. If i have array of positive and negative numbers all are int,
how to sort all the positive ones in a new array and all negative in a other new array.

Asking a question in StackOverflow without any selfstudy on basics would attract downvotes. Kindly take time in doing your research. However to make you understand the way to solve I am providing you with a solution.
Step 1: You have an array of positive and negative values
Integer[] initialArray = new Integer[10];
//This contains the list of all values.
Step 2: Create two ArrayLists to save the negative and positive values in each of these.
ArrayList<Integer> positiveValues = new ArrayList<>();
ArrayList<Integer> negativeValues = new ArrayList<>();
Step 3: Iterate through initialArray and save the respective values in both lists.
for(int i =0; i< initialArray.length; i++) {
if(initialArray[i] < 0) {
negativeValues.add(initialArray[i]);
} else {
positiveValues.add(initialArray[i]);
}
}
Step 4: Now sort the values
Collections.sort(negativeValues);
Collections.sort(positiveValues);
Step 5: If Required If you need in arrays instead of ArrayList,
Integer[] negativeArray = new Integer[negativeValues.size()];
Integer[] positiveArray = new Integer[positiveValues.size()];
And cast these to get the array

I actually think this is a pretty good question. Here is an implementation you can try using Java 8 streams.
Given an integer array full of mixed negative/positive numbers:
int[] a = new int[] { 5, 6, 7, 4, -2, 5, -9, 2 };
One solution could be as follows:
int[] pos = Arrays.stream(a).filter(i -> i >= 0).sorted().toArray();
int[] neg = Arrays.stream(a).filter(i -> i < 0).sorted().toArray();
The pos[] array will have all the positive numbers sorted, and neg[] all the negative numbers sorted. The only thing I really dislike is that a[] is traversed twice, but at least it is short.

First seperate positive and negative numbers. I mean find size of positive numbers and create-set new positive numbers array. Then find size of negative numbers and create-set new negative numbers array.
Then just call sort method on both arrays.
Arrays.sort(array);

Related

How to merge arrays in alternating pattern without duplicates

I'm currently learning in school but am unable to complete this part of the assignment.
An explanation with the use of for loops would be greatly appreciated.
The numbers should be added to the merged array in an alternating pattern: first from list 1, then from list 2, then list 1 again, etc. If a number in one of the arrays already appears in the merged array, then it should be ignored, and the program should alternate to the other list again. For example, if the first list begins 1 2 3 10, and the second begins 3 4 5 8, then the merged list would begin 1 3 2 4 5 10 8.
Because the number of elements in the merged array is unknown, its size should be set to the maximum possible number of elements it should contain, and after all elements which should form the merged array appear, any remaining unfilled spaces in the array should be 0. The first 0 encountered in the array should signal the end of the “actual” elements of the array, and therefore the 0s at the end of the array should not be printed by your program.
I propose to use a HashSet to remember which number you have already inserted into the array. For each number, you first check if the hash set already contains the number; if not, you add it to both the array and the set. For large inputs, this is much faster than checking the result array for each number. O(n*log(n)) or so (depending on how well the HashSet works for your input) instead of O(n^2).
#bubble
An example using a Set is very simple - however your teacher is asking for
an alternate list:
Integer[] one = new Integer[] {10,2,3,1};
Integer[] two = new Integer[] {3,8,5,4};
List<Integer> li_one = Arrays.asList(one); // First convert the arrays to a list
List<Integer> li_two = Arrays.asList(two);
Set<Integer> set = new HashSet<>();
set.addAll(li_one);
set.addAll(li_two);
System.out.println("The unique list is: " + set);
A HashSet was my first idea too, but the order of storing values depends
one hash values. The ... teacher likes to have alternating values which
I dont like to comment - because it is a really strange request.
Following code prints: merged list is: [1, 3, 2, 4, 5, 10, 8]
int[] one = new int[] {1,2,3,10};
int[] two = new int[] {3,4,5,8};
int one_len = one.length;
int two_len = two.length;
List<Integer> merged = new ArrayList<>();
int oneval,twoval;
for (int i = 0;i < one_len;i++)
{
oneval = one[i];
if (!merged.contains(oneval)) merged.add(oneval);
if (i < two_len)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
if (two_len > one_len)
{
for (int i = one_len; i < two_len;i++)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
System .out.println("merged list is: " + merged);

How to create an int[] with fixed length and specific number with java stream? [duplicate]

This question already has answers here:
How do I fill arrays in Java?
(8 answers)
Closed 4 years ago.
I know how to get an int[] with a range of numbers:
int[] array = IntStream.of(0, 3).toArray();
But how can I get it with fixed length and one specific number?
IntStream.generate(() -> x).limit(y)
is what you need. Replace x and y with any number you like and you will produce a stream that has y lots of the number x.
You can obviously then call toArray or do whatever operation you want.
IntStream.generate creates an infinite stream using the supplier.
Here's one way:
int[] array = IntStream.rangeClosed(1, n).map(x -> m).toArray();
should produce an array of length n filled with m.
The following Q&A has other answers that use other approaches, such as the Arrays.fill method.
How do I fill arrays in Java?
Or simpler again.
// n elements of value m
int[]a=new int[n];
Arrays.fill(a,m);
Or even simpler with an API that was written for that:
int[] arr = new int[10];
Arrays.setAll(arr, x -> 1);
// or if you have enough data for parallel to make any difference
Arrays.parallelSetAll(arr, x -> 1);

Adding a range of numbers to a Java array [duplicate]

This question already has answers here:
How can I generate a list or array of sequential integers in Java?
(9 answers)
Closed 5 years ago.
I am relatively new to Java programming and am trying to create an array with values from (2017 - 3017).
I was wondering if there is a way to create an array and have it pre-filled with these values so instead of doing:
int[] anArray = {2017, 2018, 2019, 2020... 3017}
which seems extremely long-winded, I can simply define a range of integers I wish to add to the array.
I know there are similar question to this one on the site, however none of them have answers that help me.
Thanks!
Edit: I forgot to mention I am using Java 7 and therefore cannot use IntStream.
How about this:
int[] anArray = IntStream.rangeClosed(2017, 3017).toArray(); //closed includes upper bound
Java 7 would simply require a loop to fill the array:
int min = 2017, max = 3017;
int count = max - min + 1; //we're including upper bound
int[] anArray = new int[count];
for (int i = 0; i < count; i++, min++) {
anArray[i] = min; //reused and incremented min
}
Well it is answered. But just to point out another way in java .. you can count the number of integers that will be coming and use iterator to fill the array.Let me know if you have any doubts in this In short I am saying to do like the following:
int arr[] = new int[1001];
for(int i=2017;i<=3017;i++){
arr[i-2017]=i;
}

Random numbers between my own values [duplicate]

This question already has an answer here:
Select a random value from an Array
(1 answer)
Closed 8 years ago.
I'm writing a program that generates co-primes of a number.
Now for example a number 'A' has 50 co-primes, my objective is to randomly select a co-prime from the list of all co-primes generated for the number A.
Again for example:
consider a number 15, it has co-primes - {1, 2, 4, 7, 8, 10, 11, 13, 14}. So now i have to select randomly from these values. Likewise, if i generate an array of any values, then how to randomly select from this array.
So in general my question is how to generate a random number from the array of numbers that i have. Now, those numbers in the array can be anything. Like not necessarily natural numbers, or prime numbers, etc.
So is there any java function to do so. I've burnt my brain searching the internet, but didn't find one. I usually go for finding result on google, rather than asking quetions on forums. But when one gets exhausted, it's better to ask experts out there who might have faced similar problems.
Thanks in advanced!!
Is that what you want ?
int[] arr = { 1,5,9,3,2,7 };
Random rd = new Random();
int dice = arr[rd.nextInt(arr.length)];
You can use the java.util.Random class for this:
public int chooseRandom(int[] coPrimes) {
//Creates the Random instance
Random randomizer = new Random();
//Generate a random integer between 0 and the length of the array (exclusive)
int value = randomizer.nextInt(coPrimes.length);
//Return the element at that generated index
return coPrimes[value];
}

"Yahtzee" game Java Programming [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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
Closed 9 years ago.
Improve this question
My assignment is to make "Yahtzee" game on Java Program.
I am almost done except the Small Straight method. (Cannot figure it out.)
Small Straight is when the dice got 4 straight number. (Ex. 12334, 23345, 34556, and etc.)
Here is my code of isSmallStraight method (This code is not completed!):
public static boolean isSmallStraight(List<Die> dice) {
boolean result = false;
List<Die> copy = new ArrayList<Die>(dice);
Collections.sort(copy);
List<Die> testCase1 = new ArrayList<Die>();
testCase1.add(new Die(1));
testCase1.add(new Die(2));
testCase1.add(new Die(3));
if(copy.containsAll(testCase1)) {
result = true;
System.out.println(result);
}
return result;
}
What I want to do in here is I passed 5 random numbers of dice from the main method (List dice) and put them into the "copy" object.
Since I need to use java.util.List.containsAll() method(requirement), I think I need to make one other object "testCase1" to compare with "copy". (If you have other method to solve this question, it is fine at least you use java.util.containsAll() method.)
However, what I don't know right now is if I use dice.add(new Die(3)), it means the program picks random numbers from 1,2, and 3. (Not die number 3) - Also, it gave me compile-time error.
So, I want to know how I can store dice specific number 1,2,3, and 4 for "testCase1", 2,3,4, and 5 for "testCase2", and 3,4,5, and 6 for "testCase3" and use copy.containsAll(testCase1) becomes true.
Please help me as soon as possible!
PS. Die class is already programmed by my professor. (So, cannot change any in the Die class).
Put the numbers into a TreeSet to get rid of duplicates and get sorting for free.
You have 4 straight dice if:
The set contains exactly 4 numbers
The difference between the largest and the smallest is 3
The method I like to use (for large and small straights as well as all other scoring) is to create a new int array from the int array that holds the dice values. Like this:
int[] numDice = new int[6];
for (int i: diceValues)
numDice[i-1] += 1;
This counts up all your dice and puts the number of each, in order, in a new array. For instance, if the 5 dice you rolled were 3, 4, 3, 1, and 6, your new array would be {1, 0, 2, 1, 0, 1}, and a yahtzee of all 4s would turn into {0, 0, 0, 5, 0, 0}. From this new array it's fairly trivial to determine all of the scores. For straights:
int straightCount = 0;
for (int i: numDice) {
if (i > 0)
straightCount++;
else
straightCount = 0;
if (straightCount > 3)
smallStraight = true;
if (straightCount > 4)
largeStraight = true;
}
If you wanted to you could use this array to easily determine all the valid scores in one short method, and store the booleans in a single array.

Categories