No repeat list java

Non-repeating random numbers inside array JAVA

I would like to generate 6 numbers inside an array and at the same time, having it compared so it will not be the same or no repeating numbers. For example, I want to generate 1-2-3-4-5-6 in any order, and most importantly without repeating. So what I thought is to compare current array in generated array one by one and if the number repeats, it will re-run the method and randomize a number again so it will avoid repeating of numbers. Here is my code:

import javax.swing.*; public class NonRepeat < public static void main(String args[]) < int Array[] = new int [6]; int login = Integer.parseInt(JOptionPane.showInputDialog("ASD")); while(login != 0) < String output=""; for(int index = 0; index> > for(int index = 0; index JOptionPane.showMessageDialog(null, output); > > public static int numGen() < int random = (int)(1+Math.random()*6); return random; >> 

I’ve been thinking it for 2 hours and still cant generate 6 numbers without repeating. Hope my question will be answered. Btw, Im new in codes so please I just want to compare it using for loop or while loop and if else .

My first thought on this is that if you want real random numbers, you should allow for repetition. If you generate a random number and then check for clauses, discard it and, say, generate another random number, the resulting array will not contain completely random numbers.

Читайте также:  Install eclipse java ide

You could add the generated numbers in a Set (which automatically removes duplicates), until the size() of the Set is 6 , and then convert the Set to an array using toArray() .

A clause is a logical statement. So checking whether your data structure already contains the same random number would be a clause.

7 Answers 7

You can generate numbers from, say, 1 to 6 (see below for another solution) then do a Collections.shuffle to shuffle your numbers.

 final List l = new ArrayList(); for (int j = 1; j < 7; j++ ) < l.add( j ); >Collections.shuffle( l ); 

By doing this you’ll end up with a randomized list of numbers from 1 to 6 without having twice the same number.

If we decompose the solution, first you have this, which really just create a list of six numbers:

 final List l = new ArrayList(); for (int j = 1; j

So at this point you have the list 1-2-3-4-5-6 you mentioned in your question. You’re guaranteed that these numbers are non-repeating.

Then you simply shuffle / randomize that list by swapping each element at least once with another element. This is what the Collections.shuffle method does.

The solutions that you suggested isn’t going to be very efficient: depending on how big your list of numbers is and on your range, you may have a very high probability of having duplicate numbers. In that case constantly re-trying to generate a new list will be slow. Moreover any other solution suggesting to check if the list already contains a number to prevent duplicate or to use a set is going to be slow if you have a long list of consecutive number (say a list of 100 000 numbers from 1 to 100 000): you’d constantly be trying to randomly generate numbers which haven’t been generated yet and you’d have more and more collisions as your list of numbers grows.

If you do not want to use Collections.shuffle (for example for learning purpose), you may still want to use the same idea: first create your list of numbers by making sure there aren’t any duplicates and then do a for loop which randomly swap two elements of your list. You may want to look at the source code of the Collections.shuffle method which does shuffle in a correct manner.

EDIT It’s not very clear what the properties of your «random numbers» have to be. If you don’t want them incremental from 1 to 6, you could do something like this:

final Random r = new Random(); final List l = new ArrayList(); for (int j = 0; j < 6; j++ ) < final int prev = j == 0 ? 0 : l.get(l.size() - 1); l.add( prev + 1 + r.nextInt(42) ); >Collections.shuffle( l ); 

Note that by changing r.nextInt(42) to r.nextInt(1) you’ll effectively get non-repeating numbers from 1 to 6.

Источник

Get random element from array without repeats in Java

I’m creating a java GUI based program, and I have an array of questions. I need to create a method that gets the next question after I click a JButton . The next question should be chosen randomly and shouldn’t repeat a previously-asked question. See the code below — how would getNextQuestion be implemented?

public class QuestionBank < String [] questions; int currQuestionIndex; public QuestionBank() < questions = new String [10]; //increase array size if you will add more questions questions[0]= "Which three words describe you best?"; questions[1]= "Which is your best feature?"; questions[2]= "Which common saying or phrase describes you?"; questions[3]= "What’s the best thing that’s happened to you this week?"; questions[4]= "Who was your role model when you were a child?"; questions[5]= "Who was your favorite teacher and why?"; questions[6]= "What was your favorite subject at school?"; questions[7]= "What did you want to be when you grew up?"; questions[8]= "If you could have one wish come true what would it be?"; questions[9]= "Which would you prefer — three wishes over five years or one wish right now?"; //add more questions >public String getNextQuestion() < //get the next question, randomly from the array and without repeats >> 

3 Answers 3

If you want to get items from a collection in a random order without repeats (as clarified in the comments), you can first shuffle the collection and then iterate through the collection normally.

In Java it’s easier to shuffle an ArrayList compared to an array, so consider the following:

public class QuestionBank < Listquestions; int currQuestionIndex; public QuestionBank() < questions = new ArrayList<>(); // no size needed questions.add("Which three words describe you best?"); questions.add("Which is your best feature?"); // add more questions currQuestionIndex = 0; // it's 0 by default but this makes it explicit Collections.shuffle(questions); // shuffle all questions > public String getNextQuestion() < // get the next question, randomly from the list and without repeats if (currQuestionIndex >= questions.size()) < return null; // no more questions! >String nextQuestion = questions.get(currQuestionIndex); currQuestionIndex++; // move forward in the shuffled list return nextQuestion; > > 

If you have to use an array instead of a List , see this question on shuffling an array. The rest of the strategy stays the same.

The likely hood is the OP isn’t allowed to use ArrayList or Set or all the really nice stuff that would make this simple

import java.util.*; public class QuestionBank < static Queuequestions; public QuestionBank() < ListtmpQuestions = new ArrayList<>(); // no size needed tmpQuestions.add("Which three words describe you best?"); tmpQuestions.add("Which is your best feature?"); tmpQuestions.add("Which common saying or phrase describes you?"); tmpQuestions.add( "What’s the best thing that’s happened to you this week?"); tmpQuestions.add("Who was your role model when you were a child?"); tmpQuestions.add("Who was your favorite teacher and why?"); tmpQuestions.add("What was your favorite subject at school?"); tmpQuestions.add("What did you want to be when you grew up?"); tmpQuestions.add("If you could have one wish come true what would it be?"); tmpQuestions.add( "Which would you prefer — three wishes over five years or one wish right now?"); Collections.shuffle(tmpQuestions, new Random()); // shuffle all questions 

Using ArrayDeque as suggested by pkpnd with the following reason

 questions = new ArrayDeque<>(tmpQuestions); > public String getNextQuestion() < // get the next question, from the randomly populated queue if (questions.isEmpty()) < return null; // no more questions! >return questions.remove(); > public static void main(String[] args) < QuestionBank qb = new QuestionBank(); String question; while((question = qb.getNextQuestion()) != null)< System.out.println(question); >> > 
 // 1st execution Who was your role model when you were a child? What?s the best thing that?s happened to you this week? Which common saying or phrase describes you? Which is your best feature? Which three words describe you best? What was your favorite subject at school? Which would you prefer ? three wishes over five years or one wish right now? If you could have one wish come true what would it be? Who was your favorite teacher and why? What did you want to be when you grew up? //2nd execution Which common saying or phrase describes you? What did you want to be when you grew up? What?s the best thing that?s happened to you this week? Which three words describe you best? What was your favorite subject at school? Which would you prefer ? three wishes over five years or one wish right now? Who was your role model when you were a child? Which is your best feature? Who was your favorite teacher and why? If you could have one wish come true what would it be? //3rd execution and so on . What?s the best thing that?s happened to you this week? Which common saying or phrase describes you? Which is your best feature? What was your favorite subject at school? Which would you prefer ? three wishes over five years or one wish right now? If you could have one wish come true what would it be? What did you want to be when you grew up? Which three words describe you best? Who was your role model when you were a child? Who was your favorite teacher and why? 

Источник

Printing a list (without repeated items) with lambda expressions in Java 8

I will show you guys only the code I think is related to the question, if you need more information please do not hesitate to ask.

// Instanciar productos Producto p1 = new Producto("Sal 100gr", LocalDate.now(), 0.5f, 1); Producto p2 = new Producto("Pimienta 25gr", LocalDate.now(), 0.2f, 1); Producto p3 = new Producto("Sal 1kg", LocalDate.now(), 2, 1); Producto p4 = new Producto("Te limón", LocalDate.now(), 3.5f, 2); Producto p5 = new Producto("Azucar 1kg", LocalDate.now(), 2, 1); Producto p6 = new Producto("Azucar 5kg", LocalDate.now(), 10, 1); Producto p7 = new Producto("Xilitol 1kg", LocalDate.now(), 15, 1); Producto p8 = new Producto("Xilitol 1kg", LocalDate.now(), 15, 1); // Añadir productos a la lista del super Supermercado.getSupermercado().addProducto(p1); Supermercado.getSupermercado().addProducto(p2); Supermercado.getSupermercado().addProducto(p3); Supermercado.getSupermercado().addProducto(p4); Supermercado.getSupermercado().addProducto(p5); Supermercado.getSupermercado().addProducto(p6); Supermercado.getSupermercado().addProducto(p7); Supermercado.getSupermercado().addProducto(p8); // Printing the list System.out.println("\nLista productos."); Supermercado.getSupermercado().printListaProductos(); // Printing distinct items (do not repeat xilitol plz) System.out.println("\nLista de productos sin repetir."); Supermercado.getSupermercado().printListaProductosSinRepetir(); 

Supermercado.java

// Printing the list public void printListaProductos() < listaProducto.stream() .forEach(p ->System.out.println("Producto " +p.getNombre() + '\t' + "Precio " + p.getPrecio() + "€" + '\t' + "Caducidad " + p.getFechaCaducidad())); > // Printing distinct items (do not repeat xilitol plz) public void printListaProductosSinRepetir() < listaProducto.stream() .distinct() .forEach(p ->System.out.println("Producto " +p.getNombre() + '\t' + "Precio " + p.getPrecio() + "€" + '\t' + "Caducidad " + p.getFechaCaducidad())); > 

Producto.java

private String nombre; private int seccion; private LocalDate fechaCaducidad; private float precio; // constructor public Producto(String pNombre, LocalDate pFechaCaducidad, float pPrecio, int pSeccion) < this.nombre = pNombre; this.fechaCaducidad = pFechaCaducidad; this.precio = pPrecio; this.seccion = pSeccion; >public LocalDate getFechaCaducidad() < return this.fechaCaducidad; >public float getPrecio() < return this.precio; >public int getSeccion() < return this.seccion; >public String getNombre()

The Output

Lista productos. Producto Sal 100gr Precio 0.5€ Caducidad 2016-05-27 Producto Pimienta 25gr Precio 0.2€ Caducidad 2016-05-27 Producto Sal 1kg Precio 2.0€ Caducidad 2016-05-27 Producto Te limón Precio 3.5€ Caducidad 2016-05-27 Producto Azucar 1kg Precio 2.0€ Caducidad 2016-05-27 Producto Azucar 5kg Precio 10.0€ Caducidad 2016-05-27 Producto Xilitol 1kg Precio 15.0€ Caducidad 2016-05-27 Producto Xilitol 1kg Precio 15.0€ Caducidad 2016-05-27 Lista de productos sin repetir. Producto Sal 100gr Precio 0.5€ Caducidad 2016-05-27 Producto Pimienta 25gr Precio 0.2€ Caducidad 2016-05-27 Producto Sal 1kg Precio 2.0€ Caducidad 2016-05-27 Producto Te limón Precio 3.5€ Caducidad 2016-05-27 Producto Azucar 1kg Precio 2.0€ Caducidad 2016-05-27 Producto Azucar 5kg Precio 10.0€ Caducidad 2016-05-27 Producto Xilitol 1kg Precio 15.0€ Caducidad 2016-05-27 Producto Xilitol 1kg Precio 15.0€ Caducidad 2016-05-27 

The Problem

Clearly, the .distinct() code in printListaProductosSinRepetir() method is not working for me. It should display this:

Lista de productos sin repetir. Producto Sal 100gr Precio 0.5€ Caducidad 2016-05-27 Producto Pimienta 25gr Precio 0.2€ Caducidad 2016-05-27 Producto Sal 1kg Precio 2.0€ Caducidad 2016-05-27 Producto Te limón Precio 3.5€ Caducidad 2016-05-27 Producto Azucar 1kg Precio 2.0€ Caducidad 2016-05-27 Producto Azucar 5kg Precio 10.0€ Caducidad 2016-05-27 Producto Xilitol 1kg Precio 15.0€ Caducidad 2016-05-27 

Without the extra Xilitol 1kg . The items shouldn’t repeat.

Why do I need this

I am trying to learn how Java 8 works with the Lambda-expressions . So I am building myself some examples for this. The thing is that .distinct() is not working. I couldn’t find this solution in SO. Thanks in advance.

Источник

Оцените статью