Making distinct selections from the given list - java

I am trying to make a team of unique members from the given set I have. This is what I have so far.
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
/* Putting all team-mates in HashMap */
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map.put("d", 4);
/* Printing out the random name and the Unique number with it*/
List<Integer> valuesList = new ArrayList<Integer>(map.values());
List<String> keyList = new ArrayList<String>(map.keySet());
System.out.println("The Team members are :");
for (int i = 0; i < 3; i++)
{
int randomIndex = new Random().nextInt(valuesList.size());
Integer randomValue = valuesList.get(randomIndex);
String randomKey = keyList.get(randomIndex);
System.out.println(randomValue+" "+randomKey);
}
}
}
When I run this, I get duplication in my list, do I use Collections.shuffle(valuesList)?
Thank You.

You can get the same number randomly twice, so Collections.shuffle(...) should do.

If a,b,c,d is all you are after, this is how I would do it:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
/* Putting all team-mates in a List*/
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
/* Printing out the random name */
System.out.println("The Team members are :");
for(int i = 0; i < 3; i++)
{
int randomIndex = new Random().nextInt(list.size());
//Integer randomValue = valuesList.get(randomIndex);
String randomValue = list.remove(randomIndex);
//String randomKey = keyList.get(randomIndex);
System.out.println(randomValue);
}
}
}
removing chosen elements from the list once chosen will make sure they don't reappear.
Fewer lines too.

Related

Initializing 2D ArrayList for for-loop summation (Java)

I am trying to sum N pairs of ints--an Nx2 ArrayList--and return the N summations as an ArrayList. While I understand it is not necessary to set up a class to accomplish this, I would like to do so as practice for future projects.
import java.util.ArrayList;
public class SumsInLoop {
public SumsInLoop(int numberOfPairs, ArrayList<ArrayList<Integer>> numbersList) {}
public ArrayList<Integer> getSums(int numberOfPairs, ArrayList<ArrayList<Integer>> numbersList) {
ArrayList<Integer> pairsOfSums = new ArrayList<Integer>();
for (ArrayList<Integer> Pair : numbersList) {
int x = Pair.get(0);
int y = Pair.get(1);
int sum = x + y;
pairsOfSums.add(sum);
}
System.out.println(pairsOfSums);
return pairsOfSums;
}
The data that I am given is a random assortment of N pairs (numbersOfPairs) of integers, e.g. 612673 108695. I would like to add these pairs of integers to a 2D ArrayList (numbersList) that will be called by getSums.
However, I am having difficulties initializing numbersList. My main function is as follows:
public static void main(String[] args) {
int myNumberOfPairs = 13;
ArrayList[][] myNumbersList = new ArrayList[13][2];
myNumbersList[0][0] = new ArrayList<>();
myNumbersList[0][0].add(612673);
myNumbersList[0][1].add(108695);
myNumbersList[1][0] = new ArrayList<>();
myNumbersList[1][0].add(756875);
myNumbersList[1][1].add(496058);
SumsInLoop mySum = new SumsInLoop(myNumberOfPairs,myNumbersList);
mySum.getSums(myNumberOfPairs, myNumbersList);
The last two lines of code throw errors, asking me to change myNumbersList to type ArrayList<List<Integer>> which throws even more errors, even after changing all 2D ArrayLists to type ArrayList<List<Integer>>.
So, my two questions are as follows:
How can I initialize an NxM ArrayList and populate it correctly?
Is there a faster way of accomplishing this task while still using a class method?
P.S. I'm used to coding in Python and am self-teaching myself Java, so any other information or resources you can provide me with are much appreciated.
You may want to simplify your input by using 2D array of int : int[][] myNumbersList = new int[13][2];
The expected output in that case is a 1D array of int[13] that can be obtained as follows (demonstrated with 2 pairs. See mcve ) :
public class SumsInLoop {
//pairsOfInts should be an [n][2] array
private static int[] sumOfPairs(int[][] pairsOfInts) {
int[] sums = new int[pairsOfInts.length];
for(int pairIndex = 0; pairIndex < pairsOfInts.length; pairIndex++) {
sums[pairIndex]= pairsOfInts[pairIndex][0]+pairsOfInts[pairIndex][1];
}
return sums;
}
public static void main(String[] args) {
int numberOfPairs = 2;
int[][] pairsOfInts = new int[numberOfPairs][2];
pairsOfInts[0] = new int[] {612673,108695 };
pairsOfInts[1] = new int[] {756875,496058 };
int[] sumOfPairs = sumOfPairs(pairsOfInts);
System.out.println(Arrays.toString(sumOfPairs));
}
}
If you want a solution implemented with List you can make use of javafx Pair (or make your own pair class.
The input can be defined as List<Pair<Integer,Integer>> pairsOfInts = new ArrayList<>();
The out put can be an array as above, or a List<Integer>:
import java.util.ArrayList;
import java.util.List;
import javafx.util.Pair;
public class SumsInLoop {
private static List<Integer> sumOfPairs(List<Pair<Integer, Integer>> pairsOfInts) {
List<Integer> sums = new ArrayList<>();
for(Pair<Integer,Integer> pair : pairsOfInts) {
sums.add(pair.getKey()+ pair.getValue());
}
return sums;
}
public static void main(String[] args) {
List<Pair<Integer,Integer>> pairsOfInts = new ArrayList<>();
pairsOfInts.add (new Pair<>(612673,108695 ));
pairsOfInts.add (new Pair<>(756875,496058));
List<Integer> sumOfPairs = sumOfPairs(pairsOfInts);
System.out.println(sumOfPairs);
}
}
The (compile) exception you are getting is due to the fact that you expect a ArrayList<ArrayList<Integer>>, but pass an ArrayList[][]. (which is not the same in Java)
In your case you'd need (in the main method):
ArrayList<ArrayList<Integer>> myNumbersList = new ArrayList</* when java > 6 ;)*/>(13);
this only sets the capacity of the (parent) list (..and the underlying/internal backing array)
to initialize the child lists, you'd not come around looping (somehow...even not in python :):
for (int i = 0; i < 13; i++) {
myNumbersList.add(new ArrayList<Integer>(2));
}
Depends on what means "correctly" ...but I assume with "random data", ideally you would again inner loop:
java.util.Random rnd = new Random(/*seed default current timestamp*/);
//...
for (int i = 0; i < 13; i++) {
ArrayList<Integer> innerList = new ArrayList<>(2);
for (int j = 0; j < 2; j++) {
innerList.add(rnd.netxInt(/*bound default Integer.MAX_VALUE*/) /*+/-/% offset*/);
}
myNumberList.add(innerList);
}
Sorry I am not aware of one (faster way), but much depends on the "input format".
Since you already know the amount of values in a pair, an ArrayList is unnecessary. You can create your own, simpler implementation of a pair.
class Pair {
public final int left;
public final int right;
public Pair(int left, int right){
this.left = left;
this.right = right;
}
}
You can then access the values by creating a pair object and accessing its fields.
Pair p = new Pair(10, 7);
System.out.println(p.left); // 10
System.out.println(p.right); // 7
You can then more easily redefine your getSums method.
public static List<Integer> getSums(List<Pair> pairs){
List<Integer> pairsOfSums = new ArrayList<>();
for(Pair pair : pairs){
int sum = pair.left + pair.right;
pairsOfSums.add(sum);
}
return pairsOfSums;
}
Please also notice the function can be static and you don't need to pass the number of pairs. The for-each loop will cycle through all of them regardless.
Initializing the array is then easier than the method you have described in the question.
List<Pair> pairs = new ArrayList<>();
pairs.add(new Pair(7, 10));
pairs.add(new Pair(18, 3));
pairs.add(new Pair(-6, 0));
pairs.add(new Pair(4, 2));
System.out.println(SumsInLoop.getSums(pairs));

Random Presentation Topic Picker returns null

Today my teacher asked me to program a random presentation topic picker for him.
The idea was, that the student goes to the pc and clicks on the message Dialog which then randomly generates a number between 1 and the max index of the topics and then prints the according topic.
I tried it with HashMaps. to put in the key that stays with the String together so that I can then (after the output) remove that entry so that no other student can get the same topic.
But it always returns at least 1 empty reference -> null.
Here is the code:
static HashMap<Integer, String> map = new HashMap<>();
public static void main(String[] args){
int anzahlEintraege = Integer.parseInt(JOptionPane.showInputDialog("Wie viele Themen gibt es?"));
for(int i = 0; i < anzahlEintraege; i++){
map.put((i+1),JOptionPane.showInputDialog("Geben Sie das Thema Nummer " + (i+1) + " ein!"));
}
JOptionPane.showMessageDialog(null, "Jetzt geht's Los!");
int max = map.size();
int removed = 0;
for(int i = 0; i < max; i++){
Random r = new Random();
int random = r.nextInt(max-1)+1;
JOptionPane.showMessageDialog(null, "Sie haben das Thema "+ map.get(random) + " gezogen!");
map.remove(random);
removed++;
}
}
The problem you're running into is that you can pick the same random number more than once, even if you've already removed the element with that key.
Instead of trying to pick non-duplicating random numbers, you would be better off to simply create a list of your keys, randomize their order, and then simply iterate over them.
Here's a simple example using strings that you should be able to adapt:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Scratch {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "foo");
map.put(2, "bar");
map.put(3, "baz");
List<Integer> keys = new ArrayList<>(map.keySet());
Collections.shuffle(keys);
for (Integer key : keys) {
String randomValue = map.get(key);
System.out.println(randomValue);
}
}
}

Array are not selecting values randomly and split into two arrays

I have got an array list of animals, on click on 'select' button I
would like to randomly select these animals and pass animals into two
arrays (split) called 'teamA and teamB'. Here is my code, but I am getting the same array list always as per screenhot link ? Could someone please
help me to figure out the problem ?
import java.lang.Math;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class RandomExample {
private Random random = new Random();
public static void main(String[] args) {
// 'list' array list contains animals
List<String> list = new ArrayList<String>();
list.add("Tiger");
list.add("Crocodile");
list.add("Cat");
list.add("Dog");
list.add("Elephant");
list.add("Lion");
list.add("Deer");
list.add("Eagle");
RandomExample obj = new RandomExample();
for(int i = 0; i < 10; i++){
obj.getRandomList(list);
List<String> teamA = list.subList(0, 4);
List<String> teamB = list.subList(4, 8);
System.out.println(teamA);
System.out.println(teamB);
}
}
public String getRandomList(List<String> list) {
//0-4
int index = random.nextInt(list.size());
System.out.println("\nIndex :" + index );
return list.get(index);
}
}
As I asked I am not sure why you do not capture the returned string from getRandomList()… I am guessing you are thinking that the list gets returned? Another issue is that when you get a random number from the list you could get the same number. Therefore you will possibly get the same animal on both teams or even the same animal twice or more on the same team. When you put an animal on a team… you need to remove them from the list.
Below I create the two teams. Then setup two loops, one for each team. Using your getRandomList method to get a random animal then remove that animal from the list. After we have both lists, print the results. Hope this helps.
Edit: As per OP request to have a different number of animals for the teams.
Example: use 5 total animals for the teams.
Obviously it’s better to look at the amount of available data before you actually set the team sizes. Example: if you want teamB to have 5 and teamA to have 4, then there better be at least 9 animals in the list. So check the team sizes before you start the loops. If totalAnimalsForTeams is greater than the number of animals in the list or totalAnimalsForTeams is less than two , then we need to indicate this to the user and exit. This approach allows you to use only part of the list if needed. In the implementation below, if the totalAnimalsForTeams is an odd number the second loop will have the extra animal member.
public class Main
{
private static Random random = new Random();
public static void main(String[] args)
{
// 'list' array list contains animals
List<String> list = new ArrayList<String>();
list.add("Tiger");
list.add("Crocodile");
list.add("Cat");
list.add("Dog");
list.add("Elephant");
list.add("Lion");
list.add("Deer");
list.add("Eagle");
list.add("Monster");
list.add("Alien");
list.add("Vombie");
list.add("Politician");
list.add("Donkeye");
List<String> teamA = new ArrayList<String>();
List<String> teamB = new ArrayList<String>();
String newAnimal;
int totalAnimalsForTeams = 7; // <- probably get this value from the user?
if (totalAnimalsForTeams > list.size())
{
System.out.println("There are only " + list.size() + " animals in the list. Requested animals was: " + totalAnimalsForTeams);
return;
}
int firstHalf = totalAnimalsForTeams / 2;
if (firstHalf < 1)
{
System.out.println("Requested " + totalAnimalsForTeams + " animals for teams... not enough to make two teams!");
return;
}
for(int i = 0; i < firstHalf; i++)
{
newAnimal = getRandomList(list);
teamA.add(newAnimal);
list.remove(newAnimal);
}
int secondHalf = totalAnimalsForTeams - firstHalf;
for(int i = 0; i < secondHalf; i++)
{
newAnimal = getRandomList(list);
teamB.add(newAnimal);
list.remove(newAnimal);
}
System.out.println(teamA);
System.out.println(teamB);
}
public static String getRandomList(List<String> list) {
//0-4
if (list.size() > 1)
{
int index = random.nextInt(list.size());
//System.out.println("\nIndex :" + index );
return list.get(index);
}
else
{
return list.get(0);
}
}
}
try this .. it should work ..
import java.lang.Math;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
import java.util.Random;
public class RandomExample {
private Random random = new Random();
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Tiger");
list.add("Crocodile");
list.add("Cat");
list.add("Dog");
list.add("Elephant");
list.add("Lion");
list.add("Deer");
list.add("Eagle");
RandomExample obj = new RandomExample();
List<String> teamA = list.subList(0,4);
List<String> teamB = list.subList(4,8);
for(int i = 0; i < 10; i++){
obj.getRandomList(list);
teamA = list.subList(0,4);
teamB = list.subList(4,8);
Collections.rotate(teamA, 1);
Collections.rotate(teamB, 1);
System.out.println(teamA);
System.out.println(teamB);
}
}
public String getRandomList(List<String> list) {
//0-4
int index = random.nextInt(list.size());
System.out.println("\nIndex :" + index );
return list.get(index);
}
}
Calling obj.getRandomList(list); returns a String but you donot do anything with it. I know this method is supposed to return a randomly picked item.
To correctly do what you are asking for, You would have to declare a new ArrayList say temp and then assign list to it.
To avoid Repetition of the same object, you need to remove the randomly generated item from the temp ArrayList created.
Then after you are done, remove the temp ArrayList created.
I have made the necessary changes to your main method as per the suggestions I made.
public static void main(String[] args) {
// 'list' array list contains animals
List<String> list = new ArrayList<String>();
list.add("Tiger");
list.add("Crocodile");
list.add("Cat");
list.add("Dog");
list.add("Elephant");
list.add("Lion");
list.add("Deer");
list.add("Eagle");
RandomExample obj = new RandomExample();
List<String> teamA = new ArrayList<String>();
List<String> teamB = new ArrayList<String>();
List<String> temp = list;
String animal;
for(int i = 0; i < 10; i++){
if(temp.isEmpty() == false){
animal = obj.getRandomList(temp);
if(i <= 3){
teamA.add(animal);
}else{
teamB.add(animal);
}
temp.remove(animal);
//System.out.println("temp is "+temp);
}
}
temp.clear();
System.out.println(teamA);
System.out.println(teamB);
}

Adding Multiple Values in ArrayList at a single index

I have a double ArrayList in java like this.
List<double[]> values = new ArrayList<double[]>(2);
Now what I want to do is to add 5 values in zero index of list and 5 values in index one through looping.
The zeroth index would have values {100,100,100,100,100}
The index 1 would have values {50,35,25,45,65}
and all of these values are stored in a double array in following order
double[] values = {100,50,100,35,100,25,100,45,100,65}
How can i do it?
#Ahamed has a point, but if you're insisting on using lists so you can have three arraylist like this:
ArrayList<Integer> first = new ArrayList<Integer>(Arrays.AsList(100,100,100,100,100));
ArrayList<Integer> second = new ArrayList<Integer>(Arrays.AsList(50,35,25,45,65));
ArrayList<Integer> third = new ArrayList<Integer>();
for(int i = 0; i < first.size(); i++) {
third.add(first.get(i));
third.add(second.get(i));
}
Edit:
If you have those values on your list that below:
List<double[]> values = new ArrayList<double[]>(2);
what you want to do is combine them, right? You can try something like this:
(I assume that both array are same sized, otherwise you need to use two for statement)
ArrayList<Double> yourArray = new ArrayList<Double>();
for(int i = 0; i < values.get(0).length; i++) {
yourArray.add(values.get(0)[i]);
yourArray.add(values.get(1)[i]);
}
How about
First adding your desired result as arraylist and
and convert to double array as you want.
Try like this..
import java.util.ArrayList;
import java.util.List;
public class ArrayTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Your Prepared data.
List<double[]> values = new ArrayList<double[]>(2);
double[] element1 = new double[] { 100, 100, 100, 100, 100 };
double[] element2 = new double[] { 50, 35, 25, 45, 65 };
values.add(element1);
values.add(element2);
// Add the result to arraylist.
List<Double> temp = new ArrayList<Double>();
for(int j=0;j<values.size(); j++) {
for (int i = 0; i < values.get(0).length; i++) {
temp.add(values.get(0)[i]);
temp.add(values.get(1)[i]);
}
}
// Convert arraylist to int[].
Double[] result = temp.toArray(new Double[temp.size()]);
double[] finalResult = new double[result.length]; // This hold final result.
for (int i = 0; i < result.length; i++) {
finalResult[i] = result[i].doubleValue();
}
for (int i = 0; i < finalResult.length; i++) {
System.out.println(finalResult[i]);
}
}
}
ArrayList<ArrayList> arrObjList = new ArrayList<ArrayList>();
ArrayList<Double> arrObjInner1= new ArrayList<Double>();
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjList.add(arrObjInner1);
You can have as many ArrayList inside the arrObjList. I hope this will help you.
create simple method to do that for you:
public void addMulti(String[] strings,List list){
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
}
Then you can create
String[] wrong ={"1","2","3","4","5","6"};
and add it with this method to your list.
Use two dimensional array instead. For instance, int values[][] = new int[2][5]; Arrays are faster, when you are not manipulating much.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
List<String> threadSafeList = new ArrayList<String>();
threadSafeList.add("A");
threadSafeList.add("D");
threadSafeList.add("F");
Set<String> threadSafeList1 = new TreeSet<String>();
threadSafeList1.add("B");
threadSafeList1.add("C");
threadSafeList1.add("E");
threadSafeList1.addAll(threadSafeList);
List mainList = new ArrayList();
mainList.addAll(Arrays.asList(threadSafeList1));
Iterator<String> mainList1 = mainList.iterator();
while(mainList1.hasNext()){
System.out.printf("total : %s %n", mainList1.next());
}
}
}
You can pass an object which is refering to all the values at a particular index.
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
ArrayList<connect> a=new ArrayList<connect>();
a.add(new connect(100,100,100,100,100));
System.out.println(a.get(0).p1);
System.out.println(a.get(0).p2);
System.out.println(a.get(0).p3);
}
}
class connect
{
int p1,p2,p3,p4,p5;
connect(int a,int b,int c,int d,int e)
{
this.p1=a;
this.p2=b;
this.p3=c;
this.p4=d;
this.p5=e;
}
}
Later to get a particular value at a specific index, you can do this:
a.get(0).p1;
a.get(0).p2;
a.get(0).p3;.............
and so on.

Storing names in a vector and convert the data into a hash table in Java

I need to store some names into a vector and then convert that data into hashtable.The id of the hash table entry will be a serial no. What i did is
import java.io.*;
import java.util.*;
class VecToHash{
public static void main(String [] args){
Vector<String> vec = new Vector<String>();
Hashtable names=new Hashtable();
vec.addElement(new String("name1"));
vec.addElement(new String("name2"));
vec.addElement(new String("name3"));
vec.addElement(new String("name4"));
vec.addElement(new String("name5"));
int VecSize=vec.size();
for (int i=0;i<VecSize;i++){
for (int j=0;j<VecSize;j++){
names.put(("j"), new String(vec.elementAt(i)));
}
Set set=names.keySet();
Iterator itr=set.iterator();
while (itr.hasNext()){
String str=(String) itr.next();
System.out.println(str+":"+names.get(str));}
System.out.println();
}}}
but its not taking the serial number as ID and i also to need to remove duplicates in Hastable. Please help me.
Ooh, Hashtable and Vector, very old-school. I wonder if you could simplify things by using Set and HashMap?
Something like:
Set<String> vec = new HashSet<String>();
Map<Integer, String> names = new HashMap<Integer, String>();
//the set will automatically filter out duplicate values
vec.add(new String("name1"));
vec.add(new String("name2"));
vec.add(new String("name3"));
vec.add(new String("name4"));
vec.add(new String("name5"));
Integer serialNumber = 0;
for (String name : vec) {
names.put(serialNumber, name);
serialNumber++;
}
for (Integer temp : names.keySet()) {
System.out.println(temp + ":" + names.get(temp));
System.out.println();
}
Here is the right code.
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
public class Main {
/**
* #param args
*/
/*public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
intList.add(0, new Integer(1));
intList.add(1, new Integer(1));
intList.add(2, new Integer(1));
intList.add(3, new Integer(1));
intList.add(4, new Integer(1));
intList.add(5, new Integer(1));
}*/
public static void main(String [] args){
Vector<String> vec = new Vector<String>();
Hashtable<Integer, String> names=new Hashtable();
vec.addElement(new String("name1"));
vec.addElement(new String("name2"));
vec.addElement(new String("name3"));
vec.addElement(new String("name4"));
vec.addElement(new String("name5"));
int VecSize=vec.size();
for (int i=0;i<VecSize;i++){
names.put(new Integer(i), new String(vec.elementAt(i)));
}
Set set=names.keySet();
Iterator itr= set.iterator();
while (itr.hasNext()){
Integer temp = (Integer) itr.next();
System.out.println(temp+":"+names.get(temp));}
System.out.println();
}}

Categories