I have a set of 100 object.
How can i get a subset of 5 objects from this set ?
I'm doing this for now but it only returns me one object
int size = memberSet.size();
Set<Member> randomSet = new HashSet<Member>();
int item = new Random().nextInt(size);
int i = 0;
for(Member mbr : memberSet)
{
if (i == item){
randomSet.add(mbr);
}
i = i + 1;
}
List<Member> list = new LinkedList<Member>(memberSet);
Collections.shuffle(list);
Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5));
Full example:
public static void main(String... args) {
Set<Member> memberSet = new HashSet<Member>();
for (int i = 0; i < 100; i++)
memberSet.add(new Member(i));
List<Member> list = new LinkedList<Member>(memberSet);
Collections.shuffle(list);
Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5));
System.out.println(randomSet);
}
static class Member {
final int value;
public Member(int value) {
this.value = value;
}
#Override
public String toString() {
return "" + value;
}
}
Although #dacwe solution is much better I can't help myself, on joke, to just say put a for(int i=0; i<5; i++) around everything and move out the Set randomSet = new HashSet();
Outside the for loop :
Related
I am trying to find the longest possible path based on how many connections a variable number has, without repeating connections. The way I thought of doing this was creating a list that holds all points that have already been gone through, but when a path ends, and I need to check a new path, all of those old connections remain in the list. How can I restart my list from the initial point?
Putting it in the recursive function itself would just clear the list each time. Is there a better option than using a list?
Relevant code:
package testapp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.IOException;
import java.util.List;
class TestApp {
// Store list of objects we have already matched with
static List<NumberObject> holdingList = new ArrayList<NumberObject>();
//Test objects
static int[] array1 = {2,2};
static int[] array2 = {3,1};
static int[] array3 = {2,1};
static int[] array4 = {1,1};
static NumberObject eight = new NumberObject(array1, 8);
static NumberObject two = new NumberObject(array2, 2);
static NumberObject three = new NumberObject(array3, 3);
static NumberObject four = new NumberObject(array4, 4);
// Test objects ^^
public static int longestSequence(int[][] grid) {
// TODO: implement this function
// Code exists here not relevant to the problem
//Setting up a new numberList array for testing
NumberObject[] newNumberList = {eight, two, three, four};
NumberObject[] connections1 = {two, four};
NumberObject[] connections2 = {two, three};
//Adding connections
eight.connections = connections1;
four.connections = connections2;
for (NumberObject s: newNumberList){
recursive(s);
}
return 0;
}
public static void recursive(NumberObject object){
for (NumberObject x: holdingList){
System.out.println(x);
}
if (!holdingList.contains(object)){
holdingList.add(object);
if (object.hasConnections()){
NumberObject[] newobject = object.getConnections();
for(NumberObject y: newobject){
recursive(y);
}
}
else {
System.out.println(holdingList.size());
return;
}
}
else {
System.out.println(holdingList.size());
return;
}
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int numRows = 0;
int numCols = 0;
String[] firstLine = reader.readLine().split("\\s+");
numRows = Integer.parseInt(firstLine[0]);
numCols = Integer.parseInt(firstLine[1]);
int[][] grid = new int[numRows][numCols];
for (int row = 0; row < numRows; row++) {
String[] inputRow = reader.readLine().split("\\s+");
for (int col = 0; col < numCols; col++) {
grid[row][col] = Integer.parseInt(inputRow[col]);
}
}
int length = longestSequence(grid);
System.out.println(length);
}
}
class NumberObject {
int[] id;
int value;
NumberObject[] connections;
//Constructor
public NumberObject(int[] id, int value){
this.id = id;
this.value = value;
}
//print statement
public String toString(){
return ("NumberOject: Id = " + id + "\nValue = " + value);
}
//Check if it has connections
public boolean hasConnections(){
if (connections == null){
return false;
}
else if (connections.length != 0){
return true;
}
else
return false;
}
//Return the connections it has
public NumberObject[] getConnections(){
return connections;
}
}
Ideally, the image displays what I want to happen.
Instead, all the old branching connections remain on holdingList.
it should be noted paths can branch off to more than two other objects.
Instead of storing the list in a field, you could just pass an instance of a copy of your list to the function as an argument. So the signature of your function recursive would look like:
public static void recursive(NumberObject object, List<NumberObject> visited)
To hide this implementation detail, I recommend writing two functions, whereby the second function just passes an empty list to the other one.
However, I'd choose a different approach since yours acquires as many new lists as entries are in your tree. In the following implementation, you only have one list per "tree end". Moreover, just like in the previous suggestion, this keeps your class stateless.
static List<NumberObject> findLongestPath(NumberObject currentNode) {
if (currentNode.getConnectedNodes().isEmpty()) {
List<NumberObject> result = new ArrayList<>();
result.add(currentNode);
return result;
}
List<NumberObject> longestPath = currentNode.getConnectedNodes().stream()
.map(PathFinder::findLongestPath)
.max(Comparator.comparing(List::size))
.get();
longestPath.add(currentNode);
return longestPath;
}
How to retrieve element from ArrayList<long[]>?
I wrote like this:
ArrayList<long []> dp=new ArrayList<>();
//m is no of rows in Arraylist
for(int i=0;i<m;i++){
dp.add(new long[n]); //n is length of each long array
//so I created array of m row n column
}
Now how to get each element?
every element in that list is an array... so you need to carefully add those by:
using anonymous arrays new long[] { 1L, 2L, 3L }
or especifying the size using the new keyword new long[5]
public static void main(String[] args) throws Exception {
ArrayList<long[]> dp = new ArrayList<>();
// add 3 arrays
for (int i = 0; i < 3; i++) {
dp.add(new long[] { 1L, 2L, 3L });
}
// add a new array of size 5
dp.add(new long[5]); //all are by defaul 0
// get the info from array
for (long[] ls : dp) {
for (long l : ls) {
System.out.println("long:" + l);
}
System.out.println("next element in the list");
}
}
You get the arrays the same way you get anything from an ArrayList. For example, to get the tenth long[] stored in the ArrayList, you'd use the get method:
long[] tenthArray = dp.get(9);
You could also have an ArrayList of objetcs that contain an array of longs inside. But the problem so far with your code is that you are not putting any values in each long array.
public class NewClass {
private static class MyObject {
private long []v;
public MyObject(int n) {
v = new long[n];
}
#Override
public String toString() {
String x = "";
for (int i = 0; i < v.length; i++) {
x += v[i] + " ";
}
return x;
}
}
public static void main(String[] args) {
ArrayList<MyObject> dp = new ArrayList();
int m = 3;
int n = 5;
for (int i = 0; i < m; i++) {
dp.add(new MyObject(n));
}
for (MyObject ls : dp) {
System.out.println(ls);
}
}
}
I'm trying to access a document class that has id, name, text and list of words. I try to compare a document id which I have with the ids and when found get the list of words attached to this id to find exact word and return its frequency.
Any help is highly appreciated.
public class Doc {
private int documentID;
private static Doc docInstance = null;
private String documentText;
private ArrayList<String> listOfTokens;
static int docCount = 0;
int tokFreq = 0;
public Doc() {
documentID = 0;
listOfTokens = new ArrayList<String>();
tokFreq = 0;
docCount++;
}
public static Doc getDocInstance() {
if (docInstance == null) {
docInstance = new Doc();
}
return docInstance;
}
public ArrayList<String> getListOfTokens() {
return listOfTokens;
}
public void setDocumentID(int x){
if (getDocumentID() != x)
this.documentID = x;
}
}
and I am trying this
public static void createDocumentVector(TreeMap<Integer,Integer>
documentVector, TreeMap<String, ArrayList<Integer>>qm, int N)
{
int eachDoc = 0;
Collection<String> allKeys = qm.keySet();
ArrayList<Integer> l1 = new ArrayList<Integer>();
boolean addedTerm = false;
/**
Obtain an Iterator for Collection
*/
Iterator<String> itr = allKeys.iterator();
String key;
int termFrequency = 0;
int documentFrequency = 0;
/**
Iterate through TreeMap values iterator
*/
while(itr.hasNext())
{
key = (String)itr.next();
Integer LL = 0;
l1 = qm.get(key); // Returns value of that key
for (int k = 0; k < l1.size(); k++)
{
LL = l1.get(k);
Doc doc = new Doc();
doc.getDocInstance().setDocumentID(LL);
int size = doc.getListOfTokens().size();
String[] docIdTokens = doc.getListOfTokens().toArray(new String[size]);
for (String s : docIdTokens){
if(s.equalsIgnoreCase(key)){
termFrequency++;
}
}
documentFrequency = l1.size();
eachDoc = getTFIDF(termFrequency, documentFrequency, N);
documentVector.put(eachDoc, LL);
}
}
}
It doesn't run completely and gives source not found, in debugging.
I am thinking to change class Doc into this:
public class Doc<ListOfTokens> {
private static int documentID;
private static Doc docInstance = null;
private String documentName;
private String documentText;
private HashMap<String, Integer> ListOfTokens = new HashMap<String, Integer>();
private TreeMap<Integer, ListOfTokens> documentMap = new TreeMap<Integer, ListOfTokens>();
int tokFreq = 0;
static int docCount = 0;
-----
}
but this would be a bit complicated I think. So any suggestions would be a great help.
You don't need to use the keyword static for the documentID property of class Doc. Since you are expecting that there will be multiple doc objects and each needs to have their own value for documentID, you need to use documentID as a non-static field.
My apologize, I have a class on my Project, called test01.java. And i used the library from Tadaki Graphlib contained many class. On of them is Graph.java.
Test01.java:
public class test01 extends Graph{
public test01(String name, int n) {
super(name);
public test01(String name, int n) {
super(name);
graphLib.Vertex vList[] = new graphLib.Vertex[n];
for (int i = 0; i < n; i++) {
vList[i] = new graphLib.Vertex(String.valueOf(i));
addVertex(vList[i]);
}
int deg = 0;
System.out.println("<---------- Random val ---------->");
addArc(vList[0], vList[1], String.valueOf(0)); deg++;
addArc(vList[1], vList[0], String.valueOf(1)); deg++;
System.out.println("Vertex-0 with Vertex-1");
System.out.println("Vertex-1 with Vertex-0");
int k = 2;
int l;
int m=0;
Random randomval = new Random();
int isAvailInt [] = new int[n];
while (k<n) {
for(l=0;l<k;l++){
isAvailInt [l]= Integer.parseInt(vList[l].toString());
m=isAvailInt[l];
}
int chosen = randomval.nextInt(m);
addArc(vList[k], vList[chosen], String.valueOf(k));
System.out.println("Vertex-"+k+" with Vertex-"+chosen+
" exp = " + String.valueOf(k));
k++;
}
}public static void main(String args[]) {
int n;
String num = JOptionPane.showInputDialog("Masukkan nilai jumlah iterasi = ");
String degnum = null;
n = Integer.parseInt(num);
int deg []= new int [n];
test01 t = new test01("test",n);
System.out.println("<---------- Vertex-i = Degree-i ------------>");
graphLib.Graph g= new Graph("test");
int [][]adj = g.getAdjacent();
System.out.println(adj[0][0]);
for (int i=0; i<t.getSize();i++){
for (int j=0; j<t.getSize();j++){
}
}}
and one other class called Graph.java
public class Graph extends GraphBase { int adjacent[][] = null;
public Graph(String name) {
this.name = name;
vertexes = Utils.createVertexList();
arcs = Utils.createArcList();
a2vHead = new HashMap<>();
a2vTail = new HashMap<>();
v2a = new HashMap<>();
}
public int[][] getAdjacent() {
int n = vertexes.size();
adjacent = new int[n][];
for (int i = 0; i < n; i++) {
adjacent[i] = new int[n];
for (int j = 0; j < n; j++) {
adjacent[i][j] = 0;
}
}
if (directed) {
for (int i = 0; i < n; i++) {
Vertex v = vertexes.get(i);
for (Arc a : v2a.get(v)) {
Vertex t = a2vTail.get(a);
int l = vertexes.indexOf(t);
adjacent[l][i]++;
}
}
} else {
for (int i = 0; i < n; i++) {
Vertex v = vertexes.get(i);
for (Arc a : v2a.get(v)) {
Vertex t = a2vTail.get(a);
if (!t.equals(v)) {
int l = vertexes.indexOf(t);
adjacent[i][l]++;
adjacent[l][i]++;
}
}
}
}
checkConnectedness();
return adjacent;
}}
From above, method - int [][] Adjacent() - has an array return value:
return adjacent;
Then I want to received it with array variable declared:
int [][]adj = g.getAdjacent();
But when I run the program, the code :
System.out.println(adj[0][0]);
Has appeared error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
I've declare the variable vertexes in Graph.java that extended from other class, GraphBase.java:
vertexes = Utils.createVertexList();
How do I obtain an array value form a variable adjacent in Graph.java to test01.java and how do I display it with System.out.println() ?
Well you haven't shown where vertexes is initialized (or even declared) in Graph. I suspect it's empty, so when you execute this code:
public int[][] getAdjacent() {
int n = vertexes.size();
adjacent = new int[n][];
...
return adjacent;
}
... you'll end up with an empty array. That would cause the problem you've seen. You can easily check the size in your main method:
System.out.println(adj.length);
I suspect you'll find it's 0. Either that, or adj[0].length is 0.
It's not clear how you expect the Graph to find any vertexes - you don't supply it with any, or even the value of n. You just call the constructor with a string:
graphLib.Graph g= new Graph("test");
Unless that's meant to be the name of a file which is loaded in the constructor, there's nowhere for it to get data from. You need to take a step back and think about where you expect the data to come from, then make sure that it can actually flow through your program. The problem isn't getting the array reference back to main - the problem is that the array is empty.
I doubted about this line returning 0.
int n = vertexes.size();
You can reproduce this issue by running below code
int adjacent[][] = new int[0][];
System.out.println(adjacent[0][0]);
You will get the same exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
To solve this issue
Make sure before proceeding vertexes have expected values.
I have this class and in the printVotes method I had to do the if statement every time to print each votes. Is there any way to combine both the if statements. Could I print all the names of the candidates and the number of votes they got at the same time?
public class TestCandidate {
public static void main(String[] args)
{
Canidate[] canidate = new Canidate[5];
// create canidate
canidate[0] = new Canidate("John Smith", 5000);
canidate[1] = new Canidate("Mary Miller", 4000);
canidate[2] = new Canidate("Michael Duffy", 6000);
canidate[3] = new Canidate("Tim Robinson", 2500);
canidate[4] = new Canidate("Joe Ashtony", 1800);
printVotes(canidate) ;
}
public static void printVotes(Canidate [] List)
{
double max;
int index;
if (List.length != 0)
{
index = 0;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
}
if (List.length != 0)
{
index = 1;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
return;
}
}
}
If you pass in a List<Candidate> candidates; and assuming that each candidate has a List<Integer> Votes:
List<Integer> votes= new ArrayList<Integer>() ;
for(Candidate c:candidates)
{
votes.add(c.GetVote()) ;
}
for(Integer v:votes)
{
System.out.println(v);
}
You could override the Candidate class's toString() method like so:
public String toString() {
return "Candidate Name: " + this.name + "\nVotes: " + this.votes;
}
Then your printVotes method would look something like this:
public static void printVotes(Candidate[] list) {
for(Candidate c : list) {
System.out.println(c);
}
}
As someone else mentioned, avoid using capital letters in variable names especially in cases where words such as List are used. List is a collection type and can be easily confused.