0

i was working on one issue i am not getting the expected output.

A String array “F1” has got names of Facebook users and their friend association.

For example, if we write: U1,U2 it implies that U1 is a friend of U2. This also implies that U2 is a friend of U1. Write a program which will read “F1” and remove duplicates and write all the unique pairs to “F2”. But, before removing duplicates

Input String => ["U1,U2","U3,U4","U2,U1","U1,U5"]

Output String => ["U1,U2","U1,U5","U3,U4"]

public static void main(String args[]) {

    List test = new ArrayList();
    List<String> list = new ArrayList();
    list.add("U1,U2");
    list.add("U3,U4");
    list.add("U2,U1");
    list.add("U1,U5");
    Collections.sort(list);

    for (String str : list) {
        String i1 = str.substring(0, 2);
        String i2 = str.substring(3, 5);
         System.out.println(i2);
         if (!i1.equals(i2)) {
         test.add(str);
         }
        if (!(str.contains(i1) && str.contains(i2)) || !(str.contains(i2) && str.contains(i1))) {
            System.out.println(str);
        }


    }

}

}

Holger
  • 285,553
  • 42
  • 434
  • 765
wasik khan
  • 11
  • 1
  • 2
  • you can try to split it into arrays, and then sort that array and then check whether it is equal to any of the entries already present. Other thing that you can try out is add the ascii value of all the characters of the string, and then check if the same added up ascii is already present. – Richa Sinha Apr 16 '19 at 11:34
  • You can also try to check if two strings contain the same characters - https://stackoverflow.com/questions/3985328/checking-if-2-strings-contain-the-same-characters – Richa Sinha Apr 16 '19 at 11:37
  • 1
    `i1.equals(i2)` would only be `true` when someone is their own friend. In contrast, `str.contains(i1)` and `str.contains(i2)` are *always* `true` when `i1` and `i2` are substrings of `str`. – Holger Apr 23 '19 at 14:44

9 Answers9

1

This is how it is done ;)

class Program
{
    static void Main(string[] args)
    {
        List<string> test = new List<String>();
        List<String> list = new List<String>();
        List<String> list1 = new List<String>();
        List<String> outputList = new List<String>();
        list.Add("MARY,JOE");
        list.Add("A,B");
        list.Add("B, A");
        list.Add("3");
        list.Add("3");
        list.Add("3,3");
        list.Add("3,3");
        var aa = compareFriends(list);
        Console.ReadLine();
    }

    public static List<string> compareFriends(List<string> allfrndsList)
    {
        var frndsList  = allfrndsList.Distinct().ToList();
        var outputList = new List<string>(frndsList);
        var listCount = frndsList.Count();
        var startIndex = 1;

        foreach (var friend in frndsList)
        {
            friend.Replace(" ","");
            var str = friend.Split(',');
            var i1 = str.FirstOrDefault();
            var i2 = str.LastOrDefault();
            for (var index = startIndex; index < listCount; index++)
            {
                var innerStr = frndsList[index].Replace(" ","").Split(',');
                var temp1 = innerStr.FirstOrDefault();
                var temp2 = innerStr.LastOrDefault();
                if (innerStr.Length != 1 && str.Length!=1)
                {
                    if (i1.Equals(temp2) && i2.Equals(temp1))
                    {
                        outputList.Remove(friend);
                    }
                }
            }
            startIndex++;
        }
        return outputList;
    }
}
0

Make a key of every pair, where the first value is smaller than the second value. ("U1,U2" and "U2,U2" will both result in "U1,U2"). Add these keys to a Set (a set removes duplicates for you). In the end you have a unique set of friend relationships.

Set<String> f2=new HashSet<>();

for (String str : list) {
    String[] users=str.split(",");
    String i1 = users[0];
    String i2 = users[1];
    String key=i1.compareTo(i2)>0?i2+","+i1:i1+","+i2;
    f2.add(key);
}
System.out.println(f2);
Conffusion
  • 4,335
  • 2
  • 16
  • 28
  • Save a string concatenation when the original string does already have the right order: `String key = i1.compareTo(i2) <= 0? str: i2 + "," + i1;` – Holger Apr 23 '19 at 14:47
0
    List test = new ArrayList();
    List<String> list = new ArrayList();
    list.add("JOE,MARY");
    list.add("A,B");
    Set<String> f2 = new HashSet<>();

    for (String str : list) {
        String[] users = str.split(",");
        String i1 = users[0];
        String i2 = users[1];
        String key = i1.compareTo(i2) > 0 ? i2 + "," + i1 : i1 + "," + i2;
        f2.add(key);
    }
    Iterator val = f2.iterator();
    while (val.hasNext()) {
        test.add(val.next());
    }
    Collections.sort(test);
    System.out.println("test" + test);
0

In C#:

class Program
{
    static void Main(string[] args)
    {
        List<string> list1 = new List<string>();

        list1.Add("U1,U2");
        list1.Add("U3,U4");
        list1.Add("U2,U1");
        list1.Add("U1,U5");

        List<string> list2 = new List<string>();

        foreach (string s in list1)
        {
            var list3 = s.Split(',');
            Array.Sort(list3);
            list2.Add(list3.FirstOrDefault() + ',' + list3.LastOrDefault());

        }

        list2.Sort();
        var list4 = list2.Distinct().ToList();

        Console.WriteLine("Input string:");
        foreach (string s in list1)
            Console.WriteLine(s);

        Console.WriteLine("\nOutput string:");
        foreach (string s in list4)
            Console.WriteLine(s);
        Console.Read();
    }
}
0

We can look at it as an undirected graph You have to remove duplicate paths Since it's undirected, "U1, U2" and "U2, U1" are the same path Therefore, if path U1, U2 already exist, then U2, U1 is duplicate, so remove it.

Any of the suggestions in the comments will yield a viable solution

Funwie
  • 91
  • 4
0
In Python :


f1 = [("U1", "U2"), ("U3", "U4"), ("U1", "U5"), ("U2", "U1"), ("U3", "U4")]

nw_lst = []

f1 = list(set(filter(lambda x: x[0] != x[1], f1)))

for i in f1:
    val1 = int(i[0][1]) + int(i[1][1])
    for j in range(f1.index(i) + 1, len(f1)):
        val2 = int(f1[j][0][1]) + int(f1[j][1][1])
        if val1 == val2:
            nw_lst.append(f1[j])

f2 = set(f1).difference(set(nw_lst))

for i in f2:
    print(f"{i[0]} , {i[1]}")
0

The below solution is written in JavaScript.

// Insert Multidimensional Array
arr = [["U1","U2"], ["U3","U4"], ["U1","U5"], ["U1","U2"], ["U3","U4"]];

function friendsArrRemover(arr) {
    var a = [];
    var itemsFoundArr = {};
    for(var i = 0, l = arr.length; i < l; i++) {
        var stringified = JSON.stringify(arr[i]);
        if(itemsFoundArr[stringified]) { continue; }
        a.push(arr[i]);
        itemsFoundArr[stringified] = true;
    }
    return a;
}

friendsArrRemover(arr);
JSG
  • 1,303
  • 2
  • 8
  • 13
0
public class Main
{
    public static void main(String[] args) {
        
        String a = "ABC";
        String b = "BC";
        String op1="";
        String op2="";
        for (int i = 0; i < a.length(); i++) {
            if(!b.contains(""+a.charAt(i))){
                op1+=a.charAt(i);
            }
        }
         for (int i = 0; i < b.length(); i++) {
            if(!a.contains(""+b.charAt(i))){
                op2+=b.charAt(i);
            }
        }
        System.out.println(op1);
                System.out.println(op2);
    }
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
-1
Below is the answer to remove the duplicate pair from list using C#. 

protected void Page_Load(object sender, EventArgs e)
{            
   List<string> list = new List<string>();
   list.Add("U1,U2");
   list.Add("U3,U4");
   list.Add("U2,U1");
   list.Add("U1,U5");
   var result=compareFriends(list);
   foreach (string value in result)
   {
     Response.Write(value + "");
    }
}
public static List<string> compareFriends(List<string> frndsList)
{
  List<string> F2 = new List<string>();
  frndsList.Sort();
  foreach (string str in frndsList)
  {
     string s1 = str.Substring(0, 2);
     string s2 = str.Substring(3, 2);

     string key;
     if (s1.CompareTo(s2)>0)
     {
        key = s2 + "," + s1;
     }
     else
     {
        key = s1 + "," + s2;
     }
     F2.Add(key);

     }
     var result = F2.Distinct();            
     return result.ToList();
}