I have a List called listTeams which comprises of Strings. I need to generate all unique combinations of these strings and store them in another ArrayList called lines. I've tried the following but the results are not desirable:
for(int i=0; i<listTeams.size();i++){
for(int j=1;j<listTeams.size();j++){
if (listTeams.get(j).equals(listTeams.get(i)))
continue;
for(int k=2;k<listTeams.size();k++){
if (listTeams.get(k).equals(listTeams.get(i)) || listTeams.get(k).equals(listTeams.get(j)))
continue;
String str = listTeams.get(i)+listTeams.get(j)+listTeams.get(k);
lines.put(str,new ArrayList<String>());
}
}
}
Here's the original list : {"A","B","C","D"}
What I am getting is
a_b_c
a_b_d
a_c_d
a_d_c
b_c_d
b_d_c
c_b_d
d_b_c
What I desire is:
a_b_c
a_b_d
a_c_d
b_c_d
for(int i=0; i<listTeams.size();i++){
for(int j=i+1;j<listTeams.size();j++){
for(int k=j+1;k<listTeams.size();k++){
String str = listTeams.get(i)+listTeams.get(j)+listTeams.get(k);
lines.put(str,new ArrayList<String>());
}
}
}
You need to modify your for loops like this:
for (int j = i;
and
for (int k = j;
So that only unique combinations appear
As #Berger said, the following code is working as you expect.
for (int i = 0; i < listTeams.size(); i++) {
for (int j = i+1; j < listTeams.size(); j++) {
if (listTeams.get(j).equals(listTeams.get(i)))
continue;
for (int k = j+1; k < listTeams.size(); k++) {
if (listTeams.get(k).equals(listTeams.get(i)) || listTeams.get(k).equals(listTeams.get(j)))
continue;
String str = listTeams.get(i) + listTeams.get(j) + listTeams.get(k);
lines.add(str);
}
}
}
Related
I am working on an assignment for my java class and part of the assignment requires reading in a .csv file that is 20x20 and inserting each string into an array.
I am trying to convert my 1d array from the initial reading in of the file into a 2d array, but I seem to be doing something wrong in my output of the data.
I made an add method, and when running the program and calling the method I only get one column of strings and listed in reverse order, but if I do a System.out.println() I don't the output I desire. I am still fairly new to this so I'm sure I just don't see the simple error, but to me, it looks correct.
the reading in of the file
try {
Scanner fileScanner = new Scanner(toOpen);
while (fileScanner.hasNext()) {
fromFile = fileScanner.nextLine();
String temp[] = fromFile.split(" ");
theList.add(temp[0]);
System.out.println(fromFile);
String[][] arr = new String[20][20];
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[i];
System.out.print(arr);
}
}
System.out.println();
}
fileScanner.close();
my add method
public void add(String tableValue) { // Adds a new node
Node newNode = new Node(tableValue);
if (isEmpty()) {
setRoot(newNode);
} else {
newNode.setNext(getRoot());
setRoot(newNode);
}
}
and my method that prints the result
public String makeString() { // A Class that makes a string
String theString = new String();
if (isEmpty()) {
theString = "List is empty";
} else {
Node printer = getRoot();
while (printer != null) {
theString += printer.getTableValue() + " ";
printer = printer.getNext();
}
}
return theString;
}
I guess your problem is here:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[i];
This assigns the same value (temp[i]) to all slots in arr[i]. Again guessing, I think you need something like:
int tmpIndex = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[tmpIndex];
tmpIndex++;
In other words: you have 400 different values in temp. But your code is only assigning the first 20 values 20 times again and again.
Beyond that: System.out.print(arr); isn't doing what you expect it to do - to learn how to print arrays correctly, see this.
As we don't know the number of lines in a file, we can start by storing each line into an ArrayList (of String[]) and then convert it into a 2D array, e.g.:
List<String[]> lines = new ArrayList<>();
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
String temp[] = line.split(" ");
lines.add(temp);
}
Now, convert it into an array:
String[][] array = new String[lines.size()][];
for(int i=0 ; i<lines.size() ; i++){
array[i] = lines.get(i);
}
I hevent seen where you have really used your add and makeString methods, and what is the role of the theList variable.
Also, could you please send your file Content.
any way:
If this is your calling to the add method: theList.add(temp[0]); that means that you are inside an Extended class structure that you have not shown it. but Any way you have not used it to fill the 2d Array in the for loop
the Code here is also error: you insert the same element temp[i] in every line !!!!
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[i];
System.out.print(arr);
}
}
You can use a dynamic structure like ArrayList to fill the Elements...
Thanks for taking the time to check out my question. I have to write some code in Dr. Java that takes in a word and then prints it out in a specific pattern. Basically here are some examples:
Input: fishy
Output: f
fifi
fisfisfis
fishfishfishfish
fishyfishyfishyfishyfishy
Basically, I'm just adding another character to the previous one and printing it out that many number of times.
Here is my attempt at my solution:
String wordcopy = word;
int size = wordcopy.length();
for (int i=1; i<=size; i+=1)
{
for (int j=0; j<i; j++)
{
System.out.print(word.substring(0,j+1));
}
System.out.println("");
}}
I have already set up my parameters so that's fine. The only thing I seem to be missing is the method itself that prints out what it's supposed to. Can anyone please help me with this problem and how I can go from here?
Thanks!
Replace word.substring(0,j+1) with word.substring(0,i):
String wordcopy = word;
int size = wordcopy.length();
for (int i = 1; i <= size; i += 1) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}
There are some cleanup things you can do. For instance, this code yields the same result:
for (int i = 1; i <= word.length(); i++) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}
I have a array of chars called votacoes. And when I do:
for (int i = 0; i < nDeputados; i++) {
System.out.println(votacoes[i]);
}
the output is:
S
A
S
S
S
N
A
As you can see you there is a blank char in index 2.
To print everything except the blank char what is the condition in the following if?
for (int i = 0; i < nDeputados; i++) {
if(???????????){
System.out.println(votacoes[i]);
}
}
You can use String isBlank method:
for (int i = 0; i < nDeputados; i++) {
if(!StringUtils.isBlank(votacoes[i])){
System.out.println(votacoes[i]);
}
}
Look here:
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29
for (int i = 0; i < nDeputados; i++) {
if(!String.valueOf(votacoes[i]).matches("\\s")){
System.out.println(votacoes[i]);
}
}
This will skip up any type of space characters and print out a continuous output.
for (int i = 0; i < nDeputados; i++)
{
if(Character.isAlphabetic(votacoes[i]))
System.out.println(votacoes[i]);
}
The Character.isAlphabetic() method returns true if the value passed is an alphabet. Hope this helps :)
use this code
for (int k = 0; k < votacoes.length; k++) {
if (votacoes[k]==' ') {
k++;
}
System.out.println(votacoes[k]);
hope it would work for you..
char[] votacoes = {'S','A',' ','S','S','S','N','A'};
for (char b : votacoes) {
if(!Character.isWhitespace(b)) {
System.out.println(b);
}
}
I want to compare two arrays and store the difference in another array
For example the two arrays might be
String[] a1 = { "cat" , "dog" };
String[] a2 = { "cat" , "rabbit" };
The resultant array would be like this
{ "rabbit" }
I use this code, but it does not work
int n = 0;
for (int k = 0; k <= temp.length; k++)
{
for (int u = 0; u <= origenal.length; u++)
{
if (temp[k] != origenal[u] && origenal[u] != temp[k])
{
temp2[n] = temp[k];
System.out.println(temp[u]);
n++;
}
}
}
This should do the trick.
String[] result = new String[100];
Int k = 0;
Boolean test = true;
for(i=0; i < a1.length; i++){
for(j=0; j < a2.length; j++){
if(a2[i].equals(a1[i])) continue;
test = false
}
if(test == false) result[k++] = a1[i];
}
I think that this may be what you are looking for. Note that it will only add to the third 'array' if the value exist in second array but not in first. In your example only rabbit will be stored, not dog (even though dog does not exist in both). This example could possibly be shortened but I wanted to keep it like this so it is easier to see what is going on.
First import:
import java.util.ArrayList;
import java.util.List;
Then do the following to populate and analyze the arrays
String a1[] = new String[]{"cat" , "dog"}; // Initialize array1
String a2[] = new String[]{"cat" , "rabbit"}; // Initialize array2
List<String> tempList = new ArrayList<String>();
for(int i = 0; i < a2.length; i++)
{
boolean foundString = false; // To be able to track if the string was found in both arrays
for(int j = 0; j < a1.length; j++)
{
if(a1[j].equals(a2[i]))
{
foundString = true;
break; // If it exist in both arrays there is no need to look further
}
}
if(!foundString) // If the same is not found in both..
tempList.add(a2[i]); // .. add to temporary list
}
tempList will now contain 'rabbit' as according to the specification. If you necessary need it to be a third array you can convert it to that quite simply by doing the following:
String a3[] = tempList.toArray(new String[0]); // a3 will now contain rabbit
To print the content of either the List or Array do:
// Print the content of List tempList
for(int i = 0; i < tempList.size(); i++)
{
System.out.println(tempList.get(i));
}
// Print the content of Array a3
for(int i = 0; i < a3.length; i++)
{
System.out.println(a3[i]);
}
how would I increment the key [i] by 1 in this situation every time I run through this for loop with the way I currently have it set up all the elements only get mapped to 1. I am trying to find out how many times each number occurs. I have tried +1 in the empty spot after list.get(i) but again only maps each element to 1. thank you.
List<Integer> list = new ArrayList<Integer>();
HashMap<Integer,Integer> Mode = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
list.add(arr[i][j]);
}
}
System.out.println(list);
int count = 1;
for(int i = 0; i < list.size(); i ++) {
Mode.put(list.get(i), );
You need to specify a Key here.
for(int i = 0; i < list.size(); i++) {
int value=list.get(i);
if(!Mode.containsKey(value))
Mode.put(value,1);
else
Mode.put(value,Mode.get(value)+1);
}
According to your comment,
for(int i = 0; i < list.size(); i ++) {
if(Mode.containsKey(list.get(i)) ){
Integer count = Mode.get(list.get(i));
Mode.put(list.get(i), ++count);}
else
Mode.put(list.get(i), 1);
If you have the option, you may find it easier to use something like Multiset from Guava.
Multiset<Integer> seen = HashMultiset.create();
for (int[] row : arr) {
for (int elem : row) {
seen.add(elem); // none of that nasty dealing with the Map
}
}
// you can look up the count of an element with seen.count(elem)
E mostCommon = null;
int highestCount = 0;
for (Multiset.Entry<Integer> entry : seen.entrySet()) {
if (entry.getCount() > highestCount) {
mostCommon = entry.getElement();
highestCount = entry.getCount();
}
}
return mostCommon; // this is the most common element