Members of List<String> as follows
U1,U2
U2,U1
U3,U2
U2,U3
U3,U4
Output should be
U1,U2
U2,U3
U3,U4
Code Tried
import java.util.*;
public class Main {
static List<String> opList = new ArrayList<String>();
static List<String> FinalopList = new ArrayList<String>();
static List<String> processStrings(List<String> friends) {
for (int i = 0; i < friends.size(); i++) {
StringBuilder newInp = new StringBuilder();
boolean statusOpp = false;
boolean statusSimilar = false;
String inp = opList.get(i);
String[] splitFriends = inp.split(",");
newInp.append(splitFriends[1]).append(",").append(splitFriends[0]).toString();
System.out.println("newInp:" + newInp);
for (int j = 0; j < friends.size(); j++) {
if (friends.get(j).contains(newInp.toString())) {
statusOpp = true;
}
else if (friends.get(j).contains(inp)) {
statusSimilar = true;
}
}
if (statusOpp) {
FinalopList.add(inp.toString());
System.out.println(inp.toString());
}
else {
FinalopList.add(inp.toString());
System.out.println(inp.toString());
}
}
return FinalopList;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number of Friends Combinations separated by comma");
int inp = sc.nextInt();
for (int i = 0; i < inp; i++) {
opList.add(sc.next());
}
processStrings(opList);
}
}
Stuck in get Unique values.
Please suggest
You could check whether the new list already contains any combination of elements and add it to the list otherwise.
static List<String> opList = new ArrayList<String>();
static List<String> finalopList = new ArrayList<String>();
static List<String> processStrings(List<String> friends) {
for (int i = 0; i < friends.size(); i++) {
StringBuilder newInp = new StringBuilder();
String inp = opList.get(i);
String[] splitFriends = inp.split(",");
String newInpStr = newInp.append(splitFriends[1]).append(",").append(splitFriends[0]).toString();
if(!finalopList.contains(inp) && !finalopList.contains(newInpStr)) {
finalopList.add(inp);
}
}
System.out.println(finalopList);
return finalopList;
}
Related
This was a question i came across when i was generally practicing some java questions online . I concentrated on finding the most frequent words as i thought that coding the least frequent words would be easy. I finally managed to code the most frequent words part but I'm unable to code the least frequent words part. Expecting a help from you guys
Thanks in advannce
This is the code for the most frequent part
import java.io.*;
public class wordFreq {
private static String[] w = null;
private static int[] r = null;
public static void main(String[] args){
try {
System.out.println("Enter 'n' value :: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
w = new String[n];
r = new int[n];
FileReader fr = new FileReader("acq.txt");
BufferedReader br = new BufferedReader(fr);
String text = "";
String sz = null;
while((sz=br.readLine())!=null){
text = text.concat(sz);
}
String[] words = text.split(" ");
String[] uniqueLabels;
int count = 0;
uniqueLabels = getUniqLabels(words);
for(int j=0; j<n; j++){
r[j] = 0;
}
for(String l: uniqueLabels)
{
if("".equals(l) || null == l)
{
break;
}
for(String s : words)
{
if(l.equals(s))
{
count++;
}
}
for(int i=0; i<n; i++){
if(count>r[i]){
r[i] = count;
w[i] = l;
break;
}
/* else if(count==1){
System.out.println("least frequent");
System.out.println("("+w[i]+":"+r[i]+"),");
}*/
}
count=0;
}
display(n);
} catch (Exception e) {
System.err.println("ERR "+e.getMessage());
}
}
public static void display(int n){
System.out.println("Most Frequent");
for(int k=0; k<n; k++){
System.out.print("("+w[k]+":"+r[k]+"),");
}
}
private static String[] getUniqLabels(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
}
I need to compare words to tweets and count how many times they appear on text.
I used two for cycle to compare ArrayList with words and ArrayList with tweets but the first word of ArrayList with words don't display correctly and don't want to count.
Output Image
It is supposed to champions word count twice
My code is:
Read txt with words and save on arraylist
public ArrayList <String> fread(String dir) throws FileNotFoundException, IOException {
Scanner s = new Scanner(new File(dir));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next().toLowerCase());
}
s.close();
return list;
}
Get Tweets and save them on arraylist
public ArrayList<String> showTimeLine() throws TwitterException {
List<Status> statuses = twitter.getHomeTimeline(new Paging (1,200));
ArrayList<String> allTweets=new ArrayList<String>();
for (Status status : statuses) {
allTweets.add(status.getText().replaceAll("https[^\\s]+","").toLowerCase());
}
return allTweets;
}
Compare two arrays:
public ArrayList<String> result(ArrayList<String>tweets, ArrayList<String> palavras){
for (int i = 0; i <palavras.size() ; i++) {
int count = 0;
for (int j = 0; j <tweets.size() ; j++) {
if (tweets.get(j).contains(palavras.get(i))){
count++;
}
}
numero.add(count);
result.add(palavras.get(i));
}
return result;
}
And print
for (int i = 0; i <result.size() ; i++) {
System.out.printf("%40s",result.get(i)+" "+numero.get(i)+"\n");
}
Static ArrayList:
static ArrayList<Integer> numero = new ArrayList<Integer>();
static ArrayList<String> result = new ArrayList<String>();
Thanks ! :)
In the method
public ArrayList<String> result(ArrayList<String>tweets, ArrayList<String> palavras){
for (int i = 0; i <palavras.size() ; i++) {
int count = 0;
for (int j = 0; j <tweets.size() ; j++) {
if (tweets.get(j).contains(palavras.get(i))){
count++;
}
}
numero.add(count);
result.add(palavras.get(i));
}
return result;
}
Your if-statement finds a single result and then ends. You can fix this like so
public static ArrayList<String> result(ArrayList<String>tweets, ArrayList<String> palavras){
for (int i = 0; i <palavras.size() ; i++) {
int count = 0;
for (int j = 0; j <tweets.size() ; j++) {
boolean isDone = false; //NEW
int tweetCharIter = 1; //NEW
while (!isDone){ //NEW
if (tweets.get(j).substring(tweetCharIter).contains(palavras.get(i))){ //ALTERED
tweetCharIter += tweets.get(j).substring(tweetCharIter).indexOf(palavras.get(i)) +1; //ALTERED
count++;
} else { //NEW
isDone = true; //NEW
}
}
}
numero.add(count);
result.add(palavras.get(i));
}
return result;
}
i got this program by someone but but i could not handle it please anyone tell me how to handle it in a easy way. Thank you
public class Program {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "a11b4c5";
System.out.println(getAnswerByPassingString(str));
}
public static String getAnswerByPassingString(String str) {
String number = "";
String letter = "";
String resStr = "";
ArrayList<String> stringList = new ArrayList<String>();
ArrayList<String> numbersList = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
char a = str.charAt(i);
if (Character.isDigit(a)) {
number = number + a;
//numbersList.add("" + a);
} else {
letter = letter + a;
stringList.add("" + a);
}
}
Matcher m = Pattern.compile("\\d+").matcher(str);
//List<Integer> numbers = new ArrayList<Integer>();
while(m.find()) {
numbersList.add(""+Integer.parseInt(m.group()));
}
// System.out.println(numbers);
for (int i = 0; i < stringList.size(); i++) {
int j = Integer.parseInt(numbersList.get(i));
String concatStr = stringList.get(i);
int count = 0;
for (int k = 1; k <= j; k++) {
concatStr = concatStr + concatStr;
if (k == j)
count = k;
}
resStr = resStr + concatStr.substring(0, count);
concatStr = "";
}
return resStr;
}
}
Using the below code you can get numbers from the string :
public static void main(String[] args) {
String str = "a2bc45cd5";
Matcher m = Pattern.compile("\\d+").matcher(str);
List<Integer> numbers = new ArrayList<Integer>();
while(m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
System.out.println(numbers);
Matcher m1 = Pattern.compile("[A-z]+").matcher(str);
List<String> string = new ArrayList<String>();
while(m1.find()) {
string.add(m1.group());
}
System.out.println(string);
}
//Output :
[2, 45, 5] // For numbers
[a, bc, cd] // For string
After get the number using loop you achieve your output result.
Given an array of strings, return another array containing all of its longest strings.
For (String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};)
output will be
{"serm", "sazi" , "kart"}.
The following code is wrong, What can I do to fix it.
public class Tester {
public static void main(String[] args) {
Tester all = new Tester();
String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};
String [] y = all.allLongestStrings(x);
System.out.println(y);
}
String[] allLongestStrings(String[] input) {
ArrayList<String> answer = new ArrayList<String>(
Arrays.asList(input[0]));
for (int i = 1; i < input.length; i++) {
if (input[i].length() == answer.get(0).length()) {
answer.add(input[i]);
}
if (input[i].length() > answer.get(0).length()) {
answer.add(input[i]);
}
}
return answer.toArray(new String[0]);
}
}
I will give you solution, but as it homework, it will be only sudo code
problem with your solution is, you are not finging longest strings, but strings same size or bigger than size of first element
let helper = []
let maxLength = 0;
for each string in array
if (len(string) >maxLength){
maxLength = len(string);
clear(helper)
}
if (len(string) == maxLength)
helper.add(string)
}
return helper;
You can try below code
private static String[] solution(String[] inputArray) {
int longestStrSize = 0;
List<String> longestStringList = new ArrayList<>();
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] != null) {
if (longestStrSize <= inputArray[i].length()) {
longestStrSize = inputArray[i].length();
longestStringList.add(inputArray[i]);
}
}
}
final int i = longestStrSize;
return longestStringList.stream().filter(x -> x.length() >= i).collect(Collectors.toList()).stream()
.toArray(String[]::new);
}
My input string is
element1-element2-element3-element4a|element4b-element5-
Expected output is
element1-element2-element3-element4a-element5-
element1-element2-element3-element4b-element5-
So the dash (-) is the delimiter and the pipe (|) indicates two alternative elements for a position.
I am able to generate combinations for input containing a single pipe:
ArrayList<String> finalInput = new ArrayList<String>();
String Input = getInputPath();
StringBuilder TempInput = new StringBuilder();
if(Input.contains("|")) {
String[] splits = Input.split("\\|", 2);
TempInput.append(splits[0]+"-"+splits[1].split("-", 2)[1]);
finalInput.add(TempInput.toString());
TempInput = new StringBuilder();
String[] splits1 = new StringBuilder(Input).reverse().toString().split("\\|", 2);
finalInput.add(TempInput.append(splits1[0]+"-"+splits1[1].split("-", 2)[1]).reverse().toString());
}
But this logic fails if there are multiple pipe symbols.
How to split a String on the last occurrance only?
Is there any efficient way to use split String with combinations?
Input:
element1-element2-element3-element4a|element4b-element5-element6a|element6b
Output:
element1-element2-element3-element4a-element5-element6a
element1-element2-element3-element4b-element5-element6a
element1-element2-element3-element4a-element5-element6b
element1-element2-element3-element4b-element5-element6b
Recursion helps.
public static void main(String[] args) {
produce("element1-element2-element3-element4a|element4b"
+ "-element5-element6a|element6b");
}
private static void produce(String input) {
String[] sequence = input.split("-");
String[][] elements = new String[sequence.length][];
for (int i = 0; i < sequence.length; ++i) {
elements[i] = sequence[i].split("\\|");
}
List<String> results = new ArrayList<>();
walk(results, elements, 0, new StringBuilder());
}
private static void walk(List<String> results, String[][] elements,
int todoIndex, StringBuilder done) {
if (todoIndex >= elements.length) {
results.add(done.toString());
System.out.println(done);
return;
}
int doneLength = done.length();
for (String alternative : elements[todoIndex]) {
if (done.length() != 0) {
done.append('-');
}
done.append(alternative);
walk(results, elements, todoIndex + 1, done);
done.setLength(doneLength); // Undo
}
}
The String.split method is used twice to get a navigatable String[][]. And to build a final String a StringBuilder is used.
You can use StringTokenizer in Java. Basically it makes tokens of the string.
public StringTokenizer(String str, String delim)
Here's an example:
String msg = "http://100.15.111.60:80/";
char tokenSeparator= ':';
StringTokenizer st = new StringTokenizer(msg, tokenSeparator + "");
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
I have write a demo for you as what I comment after your post, the code may be ugly, but it works
public class TestSplit {
//define a stringList hold our result.
private static List<String> stringList = new ArrayList<String>();
//this method fork the list array when we meet a "|"
public static void forkStringList(){
List<String> tmpList = new ArrayList<String>();
for(String s: stringList){
tmpList.add(s);
}
stringList.addAll(tmpList);
}
//when we meet "|" split two elems, should add it to
//the string list half-half
public static void addTowElems(String s1, String s2){
for(int i=0;i<stringList.size()/2;i++){
stringList.set(i,stringList.get(i)+s1);
}
for(int i = stringList.size()/2;i<stringList.size();i++){
stringList.set(i,stringList.get(i)+s2);
}
}
// if not meet with a "|" just add elem to everyone of the stringlist
public static void addOneElem(String s){
for(int i=0;i<stringList.size();i++){
stringList.set(i,stringList.get(i)+s);
}
}
public static void main(String[] argvs){
//to make *fork* run, we must make sure there is a "init" string
//which is a empty string.
stringList.add("");
// this is your origin string.
String input = "a-b-c-d|e-f";
for (String s: input.split("\\-")){
if(s.contains("|")){
//when meet with "|", first fork the stringlist
forkStringList();
// then add them separately
addTowElems(s.split("\\|")[0],s.split("\\|")[1]);
}else {
// else just happily add the elem to every one
// of the stringlist
addOneElem(s);
}
}
//checkout the result, should be expected.
System.out.println(stringList);
}
}
Here's my iterative solution:
import java.util.*;
public class PathParser {
private static final String DELIMINATOR_CONCAT = "-";
private static final String DELIMINATOR_OPTION = "|";
private List<String> paths;
private List<String> stack;
private List<String> parse(final String pathSpec) {
stack = new ArrayList<String>();
paths = new ArrayList<String>();
paths.add("");
final StringTokenizer tok = createStringTokenizer(pathSpec);
while (tok.hasMoreTokens()) {
final String token = tok.nextToken();
parseToken(token);
}
if (!stack.isEmpty()) {
updatePaths();
}
return paths;
}
private void parseToken(final String token) {
if (DELIMINATOR_CONCAT.equals(token)) {
updatePaths();
} else if (DELIMINATOR_OPTION.equals(token)) {
// nothing to do
} else {
stack.add(token);
}
}
private void updatePaths() {
final List<String> originalPaths = new ArrayList<String>(paths);
paths.clear();
while (stack.size() > 0) {
paths.addAll(createNewPaths(originalPaths));
}
}
private List<String> createNewPaths(final List<String> originalPaths) {
final List<String> newPaths = new ArrayList<String>(originalPaths);
addPart(newPaths, stack.remove(0));
addPart(newPaths, DELIMINATOR_CONCAT);
return newPaths;
}
private void addPart(final List<String> paths, final String part) {
for (int i = 0; i < paths.size(); i++) {
paths.set(i, paths.get(i) + part);
}
}
private StringTokenizer createStringTokenizer(final String pathSpec) {
final boolean returnDelimiters = true;
final String delimiters = DELIMINATOR_CONCAT + DELIMINATOR_OPTION;
return new StringTokenizer(pathSpec, delimiters, returnDelimiters);
}
public static void main(final String[] args) {
final PathParser pathParser = new PathParser();
final String input = "element1-element2-element3-element4a|element4b|element4c-element5-element6a|element6b|element6c";
System.out.println("Input");
System.out.println(input);
System.out.println();
final List<String> paths = pathParser.parse(input);
System.out.println("Output");
for (final String path : paths) {
System.out.println(path);
}
}
}
Output:
Input
element1-element2-element3-element4a|element4b-element5-element6a|element6b
Output
element1-element2-element3-element4a-element5-element6a-
element1-element2-element3-element4b-element5-element6a-
element1-element2-element3-element4a-element5-element6b-
element1-element2-element3-element4b-element5-element6b-
This helps to acheive the same..
public class MultiStringSplitter {
public static void main(String arg[]) {
String input = "a-b|c-d|e-f|g-h";
String[] primeTokens = input.split("-");
String[] level2Tokens = null;
String element = "";
String level2element = "";
ArrayList stringList = new ArrayList();
ArrayList level1List = new ArrayList();
ArrayList level2List = new ArrayList();
for (int i = 0; i < primeTokens.length; i++) {
// System.out.print(primeTokens[i]);
if (primeTokens[i].contains("|")) {
level2Tokens = primeTokens[i].split("\\|");
for (int j = 0; j < level2Tokens.length; j++) {
for (int k = 0; k < stringList.size(); k++) {
element = (String) stringList.get(k);
level2element = element + level2Tokens[j];
level2List.add(level2element);
}
}
stringList = new ArrayList();
for (int w = 0; w < level2List.size(); w++) {
stringList.add(level2List.get(w));
}
level2List = new ArrayList();
}
else {
if (stringList.size() > 0) {
for (int z = 0; z < stringList.size(); z++) {
element = (String) stringList.get(z);
element = element + primeTokens[i];
level1List.add(element);
}
stringList = new ArrayList();
for (int w = 0; w < level1List.size(); w++) {
stringList.add(level1List.get(w));
}
level1List = new ArrayList();
}
else {
element = element + primeTokens[i];
if (stringList.size() == 0) {
stringList.add(element);
}
}
}
}
for (int q = 0; q < stringList.size(); q++) {
System.out.println(stringList.get(q));
}
}
}
Input : a-b|c-d|e-f|g-h
Output:
abdfh
acdfh
abefh
acefh
abdgh
acdgh
abegh
acegh