I have looked at Randomize or shuffle an array Randomize or shuffle an array
I am not sure if this is the best approach to make.
I want to randomize the indices of an array with 3 items.
12
4
5
int numbers[] = new int[3];
I tried using the Maths.Random
int randomoption2 = opmin + (int)(Math.random() * ((opmax - opmin) + 1));
but I then have an issue with repetition of the indices values. What is the best approach to randomize the indices so there is no repetition .
eg
a[1] = 2;
I don't want two elements in the array coming back with an indices of one
http://www.exampledepot.com/egs/java.util/coll_Shuffle.html
public class randomorder {
public static void main(String [] args)
{
randomorder();
System.out.println(randomorder());
}
public static ArrayList randomorder(){
ArrayList nums = new ArrayList();
nums.add(1);
nums.add(2);
nums.add(3);
Collections.shuffle(nums);
return nums;
}
}
I now need to store each of the numbers in variables so they can be outputted
System.out.println(options[0]);
Use Collections.shuffle:
Integer[] numbers = { 1, 2, 3, 4, 5 };
Collections.shuffle(Arrays.asList(numbers));
See it working online: ideone
It uses the Fisher-Yates shuffle internally. This is an efficient shuffling algorithm that won't give you duplicates.
Related
Java's Collections.shuffle is doing what?
How to convert int[] to Integer[] in Java?
Arrays.asList() not working as it should?
Just keep three booleans through an array of booleans. Once you hit 0, 1, or 2 index set them to true.
Choose a random position and do while(boolean[number chosen] == true) redo your random choice.
Related
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);
For example int new [] {1, 2, 3, 4, 5, 6, 7, 8}, I'd like to take 4 of them randomly then insert them to another array for later use.
Dumb question, but does this also need generators? The elements are already there so I don't see any use for generators here...
Below snippet should do the trick:
private static final Random RANDOM = new Random();
public int[] getRandom4( int[] input ){
final int[] output = new int[4];
for( int i = 0; i < 4; i++ ){
output[i] = input[RANDOM.nextInt(input.length)];
}
return output;
}
Note: I prefer the Random instance to be static, but if you dislike that. Then just move it inside the method
You can but the elements inside ArrayList instead of simple array
and then shuffle the elements usingCollections.shuffle(list)
and then take first three or four elements or whatever you wants.
My algorithm to find the maximum number of unique integers among all possible contiguous subarrays doesn't work for larger amounts of Integers and subarrays.
For instance, I have to read a total amount of 6 Integers from the console and each subarray has a size of 3.
So, for this kind of input 5 3 5 2 3 2
my program should print 3 and this works fine.
The first subarray stores 5 3 5 so the number of unique Integers is 2.
The second subarray stores 3 5 2 so the number of unique Integers is 3.
The third subarray would also print 3 because it stores 5 2 3 and so on...
But, it seems like my algorithm can't handle a total amount of 100000 Integers with a subarray size of 99877.
Can anyone explain me, what I have done wrong?
FYI: I have to use a Deque implementation like LinkedList or ArrayDeque
for (int i = 0; i < totalAmountOfIntegers; i++) {
int anyIntegerNumber = consoleInput.nextInt();
arrayDequeToStoreAllIntegers.addLast(anyIntegerNumber);
hashSetToStoreUniqueIntegers.add(anyIntegerNumber);
if (arrayDequeToStoreAllIntegers.size() == sizeOfEachArrayDequeAsSubArray) {
if (hashSetToStoreUniqueIntegers.size() > quantityOfUniqueIntegersInSubarray) {
quantityOfUniqueIntegersInSubarray = hashSetToStoreUniqueIntegers.size();
}
int firstNumberInDeque = arrayDequeToStoreAllIntegers.remove();
if (hashSetToStoreUniqueIntegers.size() == sizeOfEachArrayDequeAsSubArray) {
hashSetToStoreUniqueIntegers.remove(firstNumberInDeque);
}
}
}
The answer would be simply the unique integers in the whole array, since the array is the superset of all subarrays, all numbers would be present in it
Just find how many unique element exist
To be honest, i don't understand your algorithm. I don't really get what the variables are referring to (although they seem to be named in a semantic way).
But what about this:
import java.util.HashSet;
import java.util.Set;
public class UniqueIntegers {
public static void main(String[] args) {
UniqueIntegers ui = new UniqueIntegers();
Integer[][] integers = {
{3,5,3,4,6},
{1,6,3,2,4},
{2,3,4},
{3,3,6,9,2}
};
Set<Integer> unique = ui.uniqueIntegers(integers);
System.out.println("Unique Integers: " + unique.size());
System.out.println("Integers: " + unique);
}
private Set<Integer> uniqueIntegers(Integer[][] ints){
Set<Integer> result = new HashSet<Integer>();
for (Integer[] iSub : ints){
for (Integer i : iSub){
result.add(i);
}
}
return result;
}
}
It prints:
Unique Integers: 7
Integers: [1, 2, 3, 4, 5, 6, 9]
After a day of researching, I have found my mistake.
My third IF-Statement is wrong. I am comparing, if the size of my HashSet variable is equal to the maximum size of elements each subarray can hold.
Instead, I should compare, if my int variable firstNumberInDeque, which I remove first from my ArrayDeque variable, contains another int variable with the same value. So if this is true, my HashSet variable remains unchanged.
But, if my ArrayDeque variable doesn't contain another int with the same value of firstNumberInDeque than firstNumberInDeque should be removed from my HashSet variable.
Here is the right code:
int firstNumberInDeque = arrayDequeToStoreAllIntegers.remove();
if (!arrayDequeToStoreAllIntegers.contains(firstNumberInDeque)) {
hashSetToStoreUniqueIntegers.remove(firstNumberInDeque);
}
I want my String[] array; to be static but I still don't know it's size.
Is there any way to declare string array of unknown size?
As much as possible I don't want to use ArrayList
You don't need to know the array size when you declare it
String[] myArray;
but you do need to know the size when you initialize it (because Java Virtual Machine needs to reserve a continuous chunk of memory for an array upfront):
myArray = new String[256];
If you don't know what the size will need to be in the moment you initialize it, you need a List<String>, or you'll be forced to make your own implementation of it (which is almost certainly worse option).
No, it needs to be declared, and thus have a length before you can set elements in it.
If you want to resize an array, you'll have to do something like: Expanding an Array?
String [] array = new String[1];
it will be garbage collected later after you init with a real array n elements.
array = new String[n];
ofcourse it has a performance decrease but it should be non-importance unless you repeat same for many different arrays.
The list is better for manipulation of an "array" for which you don't know length.
Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.
Example:
List unindexedVectors = new ArrayList();
unindexedVectors.add(2.22f);
unindexedVectors.get(2);
My apologies to the nay-say-ers, this can be done easily.
import java.util.Random;
public class Roll_2 {
static Random random = new Random();
public static void main(String[] args) {
int[] variableArray1 = init(random.nextInt(9)); // random size
int[] variableArray2 = init(random.nextInt(9)); // random size
int[] variableArray3 = init(random.nextInt(9)); // random size
randomaize(variableArray1); // randomize elements
randomaize(variableArray2); // randomize elements
randomaize(variableArray3); // randomize elements
print(variableArray1); // print final
print(variableArray2); // print final
print(variableArray3); // print final
}
private static int[] init(int x) {
int[] arr = new int[x];
return arr;
}
private static void print(int[] body) {
System.out.print("[");
for (int i=0;i<body.length;i++) {
System.out.print(body[i]);
if (i<body.length-1) System.out.print(" ");
}
System.out.println("]");
}
private static void randomaize(int[] body) {
for (int i=0;i<body.length;i++) {
body[i] = random.nextInt(9);
}
}
}
Sample Run 1:
[1 7 2]
[5 2 8 6 8 3 0 8]
[]
Sample Run 2: [2 5 6 8 0 7 0 6] [0 0 1] [2 1 2 1 6]
Sample Run 3: [8 3 3] [7] [1 3 7 3 1 2]
I'm trying to create a simple method to move the first element in an array to the back of the array.
Here's my code
public class Ex5_ShiftLeft {
public static void main(String[] args) {
int[] a = new int[] {6, 2, 5, 3};
swap (a);
}
public static void swap(int[] array){
array[0] = array[array.length];
System.out.println(Arrays.toString(array));
}
}
Eclipse doesn't seem to detect an error with my code, but when I run it, I get the error text
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
4 at
apollo.exercises.ch04_loops.Ex5_ShiftLeft.swap(Ex5_ShiftLeft.java:19)
at
apollo.exercises.ch04_loops.Ex5_ShiftLeft.main(Ex5_ShiftLeft.java:1)"
Any tips?
Arrays represent a segment of memory which your program has reserved to store a series of numbers or whatever else your array has. Because of this, arrays cannot be resized; you can't go past the end of the segment of memory you've reserved because another program might be using that memory. Your solution does not work because it tries to take the first element and put it after the end of the array, which is out of bounds. Instead, you have to remember the first element, then move each element except for the first one space to the left to create room at the end of the array, and then you can put the first element at the end of the array.
I take it as you're a beginner so i'll say just keep at it and you'll sure improve. I improved your code below for you:
public class Ex5_ShiftLeft {
public static void main(String[] args) {
int[] a = {6, 2, 5, 3};
swap (a);
}
public static void swap(int[] array){
int temp = array[0]
array[0] = array[array.length-1];
array[array.length-1]
for(int x : array){
System.out.println(x+" ");
}
}
}
CHANGES:
You can declare an array just with this: int[] myArray = {6,2,5,3};
There was a problem with your swap function. You have to create temporary variable so you can swap the first element of the array with the last.Also, the last element of the array is array[array.length-1]
Second, I used an Enhanced For-loop to print out the array. Hope this helps
The size of an array is basically static.
For this purposes, you can use an ArrayList which is dynamic.
The error is because of line :
array[0] = array[array.length];
If you want to access the last element of the array and populate it to array[0] then use below
array[0] = array[array.length-1];
Use array[0] = array[array.length - 1]; to access the last item in the Array.