Randomize array of Strings, but without repeating elements [duplicate] - java

This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 8 years ago.
I'd like to ask how should I implement a method in Java that takes all the elements from an array and shuffle them. Think like a deck of playing cards.
This is my try:
// a is an array of type String
public void randomize()
{
for(int i=0; i<k; ++i)
{
int idx = new Random().nextInt(k);
String random = (a[idx]);
System.out.println(random);
}
}

You can use Collections.shuffle(). First convert your array to a List

Using built-in methods is probably the easiest and cleanest solution:
Collections.shuffle(Arrays.asList(a)); //shuffles the original array too
This works because the asList method (emphasis mine):
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

You mean somethin like this one? Or you are looking for something more complex?
static void shuffleArray(String[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}

Related

Take out sub set of indexes from array of type integer [duplicate]

This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 1 year ago.
So I have a List in which there are say 2 elements (suppose [1,2]), now the return type of method is int[] so I need to convert this Listto int[].
Here is my so far code,
public int[] twoSum(int[] nums, int target) {
List<Integer> l1 = new ArrayList<Integer>();
int lengthOfnums = nums.length;
int[] indexOfNums = new int[nums.length];
if(lengthOfnums != 0)
{
for(int i=0; i <=lengthOfnums-1; i++)
{
for(int j =1; j<=lengthOfnums-1;j++)
{
if(nums[i] + nums[j] ==target)
{
//l1.add(i);
//l1.add(j);
indexOfNums[i]=i;
indexOfNums[i+1]=j; // here somewhere logic goes boom
}
}
}
}
return indexOfNums;
}
When I use (to operate on l1 arrayList)
Integer[] boxed = l1.stream().filter(Objects::nonNull).toArray(Integer[]::new);
indexOfNums = ArrayUtils.toPrimitive(boxed);
It gives output something like - [I#6bf2d08e, I think it is something related to address of memory, (not sure on this part).
So this one didn't work.
Also I can not use the for loop as I have to think about the complexity O(n) for my method.
Already complexity has reached to O(n)2 (square).
**What I want is **
if sum of two numbers is target then I want to get the index of those numbers.
This can be done by converting the Stream<Integer> into a IntStream which has a toArray() method which generates an int[]
l1.stream().filter(Objects::nonNull).mapToInt(Integer::intValue).toArray()

Reverse Array (HackerRank) [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 3 years ago.
Am I leaning in the right direction with my code? I'm currently working on hacker rank and am on the easy section of data structures yet I still am confused about how to reverse this array!
Out of all my attempts, I like these two that I did. Check it out.
one attempt:
two attempts:
You can reverse array in two ways
Either by fetching elements from last to start index and putting elements into new array
for example
int[] b = new int[n];
for(int i = n-1; i>=0 ; i--){
n[i] = arrayTobeReverse[i];
}
for more you can visit : https://www.geeksforgeeks.org/reverse-an-array-in-java/
By using Collection.reverse() method first you have to convert array into List using Arrays.asList(array) you can create List using array and then reverse the List.
for example :
import java.util.*;
public class ReverseDemo
{
public static void main(String[] args)
{
// Let us create a list of strings
List<String> mylist = new ArrayList<String>();
mylist.add("practice");
mylist.add("code");
mylist.add("quiz");
mylist.add("geeksforgeeks");
System.out.println("Original List : " + mylist);
// Here we are using reverse() method
// to reverse the element order of mylist
Collections.reverse(mylist);
System.out.println("Modified List: " + mylist);
}
}
You should be walking down the input array, then populating the target array in the opposite direction:
public static int[] reverseArray(int[] a) {
int[] b = new int[a.length];
for (int i=0; i < a.length; ++i) {
b[i] = a[a.length-i-1];
}
return b;
}
Just for fun, here is way to reverse the order of an original array, without using any extra storage:
// give input int[] a
for (int i=0; i < a.length / 2; ++i) {
a[i] = a[a.length-i-1];
}
Note that this approach just walks down half of the array, and swaps elements about the median.

Implentation of a Selection Shuffle in Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
public static void selectionShuffle(int[] values) {
Random rand = new Random();
for(int i = values.length; i > 0; i--) {
int r = rand.nextInt(i);
swap(values, r, i);
}
//updated answer to include below method
public static void swap(int[]a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
I am writing a card game and need to randomly sort the cards in place, I got an ArrayOutOfBoundsException when I ran the above code, with the compiler complaining particularly about the reassignment from values[i] = values[r] . To be clear, this is , not intended to be a selection sort but instead a selection shuffle. Any help is appreciated!
Alternatively, you may try Collections.shuffle() but it would be more handy if you have to use the wrapper class Integer instead of the primitive type intat first.
Integer[] version:
public static void selectionShuffle(Integer[] values) {
Collections.shuffle(Arrays.asList(values));
}
int[] version:
public static void selectionShuffle(int[] values) {
Integer[] boxedArr = Arrays.stream(values).boxed().toArray( Integer[]::new );
Collections.shuffle(Arrays.asList(boxedArr));
for(int i=0 ; i<values.length ; i++){
values[i] = boxedArr[i];
}
}
Your start condition needs to be values.length-1, as Java arrays are 0 to length-1.
Also the test should be >=0, since as you wrote it'll only go down to index 1.
for(int i = values.length - 1; i >= 0; i--) {
Or as pointed out by Iłya Bursov, you could compare at index i-1 and leave your for loop conditions as you have them. Not sure what's the best form I always do it as in my example above.
Also, you aren't shuffling. You set the value at index i to the one at r, but you lost the value that was previously at i. You need a temp variable to swap the values.
tmp = values[i];
values[i] = values[r];
values[r] = tmp;

Changing Array to ArrayList [duplicate]

This question already has answers here:
How to convert int[] into List<Integer> in Java?
(21 answers)
Closed 5 years ago.
I am trying to find duplicate element in an array. I have already solved it using traversing the array. But now i want to convert array to arraylist and use contains keyword of arraylist.
I am not able to convert array to arraylist and use the contains keyword. please look in following code:
public void findDuplicate2() {
int arr[] = { 1, 2, 3, 4, 5, 3, 7, 5 };
ArrayList<int[]> arrlist = new ArrayList<>(Arrays.asList(arr));
for (i = 0; i < len; i++) {
if (arrlist.contains(arr[i]))
System.out.println(arr[i]);
else
System.out.println("no duplicate" + arr[i]);
}
}
There are a number of problems with your code:
You are creating an ArrayList<int[]>, that is, an array list of arrays of int. This list contains one array, namely the one you started out from. I don’t think this was what you intended. My guess is you wanted an ArrayList<Integer> containing the numbers from the array. khelwood’s link should help you out.
You haven’t declared i nor len. I suggest you use for (int i = 0; i < arr.length; i++).
arrlist.contains(arr[i]) always returns false since a list of arrays cannot contain a number (the numbers inside the array are not searched). It’s a design problem with ArrayList that you can ask for whether it contains an element of the wrong type (there are historical reasons for this). If you change the arraylist to ArrayList<Integer> as I suggested above, it will work, though.
Once you get the above to work, arrlist.contains(arr[i]) will always return true since each number from the array will be in the array list, also the ones that are not duplicates.
Here your arrlist variable is of type int[]. Here your arrlist size is 1(the entire input array as single entry).
So, you can only check the existence of any integer array in the list by using contains method of arrlist. if (arrlist.contains(arr)) //returns true in your case
An easier way to find dublicates is this one:
public void findDuplicate2(){
int arr[] = {1,2,3,4,5,3,7,5};
for (int i = 0; i < arr.length; i++) {
boolean dublicate = false;
for (int j = 0; j < arr.length; j++) {
if(arr[i] == arr[j] && i != j){
System.out.println(arr[i]);
dublicate = true;
break;
}
}
if(!dublicate)
System.out.println("No dublicate " + arr[i]);
}
}
In your code the arraylist contains one element, the array arr. You can check this with
System.out.println(arrlist.get(0));
System.out.println(arrlist.get(1));
The right way would be to transfer each element of arr to arraylist...

Arrays.asList(an_array).contains(an_integer) always false.Why? [duplicate]

This question already has answers here:
Why does Arrays.asList on an int[] return a List<int[]>, and not a List<int>?
(3 answers)
Arrays.asList().contains() on Double vs double arrays [duplicate]
(3 answers)
Closed 9 years ago.
I'm trying to build a lottery program and I want to check if a number already exists in the previous winning numbers (inside the array). So I was trying this
int[] winningNumbers = new int[6]; //array holding 6 random numbers
for(i = 0; i < winningNumbers.length; i++ ){
int randomNums = new Random().nextInt(49) + 1;
while (Arrays.asList(winningNumbers).contains(randomNums)){
System.out.println(Arrays.asList(winningNumbers).contains(randomNums));//always false
randomNums = new Random().nextInt(49) + 1;
}
winningNumbers[i] = randomNums ;
System.out.println(winningNumbers[i]);
}
Arrays.asList(winningNumbers).contains(randomNums) always was false regardless if the number exist or not so the while loop never was executed, so I solved it by writing a method
public static boolean findIfExist(int a[], int x){
for (int i=0; i<a.length; i++){
if (a[i]==x){
return true;
}
}
return false;
}
My question is why Arrays.asList(winningNumbers).contains(randomNums) always was false. What I'm doing wrong here?
Thanks for your time.
The problem lies in the interpretation of the varargs method Arrays.asList. It interprets the type to be int[], so that you receive back a List<int[]>, not a List<Integer>. So none of the numbers you pass in will be equal to an int[].
You could declare winningNumbers to be an array of Integers, so that the array will interpreted as you expect, and you receive a List<Integer> back. Your own findIfExist method works well also.

Categories