44

I have two generic Dictionaries. Both have the same keys, but their values can be different. I want to compare the 2nd dictionary with the 1st dictionary. If there are differences between their values, I want to store those values in a separate dictionary.

1st Dictionary
------------
key       Value

Barcode   1234566666
Price     20.00


2nd Dictionary
--------------
key       Value

Barcode   1234566666
Price     40.00


3rd Dictionary
--------------
key       Value

Price     40

Can anyone give me the best algorithm to do this? I wrote an algorithm but it has a lot of loops. I am seeking a short and efficient idea, like a solution using LINQ query expressions or LINQ lambda expressions. I am using .NET Framework 3.5 with C#. I found something about the Except() method, but unfortunately I couldn't understand what is happening on that method. It would be great if anyone could explain the suggested algorithm.

Wyck
  • 8,140
  • 4
  • 39
  • 51
Thabo
  • 1,402
  • 2
  • 18
  • 36
  • What do you want to do if a key appears in the first dictionary but not the second, or vice versa? – Jon Skeet Mar 03 '12 at 15:45
  • No...actually keys must be same in name and count.I am checking by iscontains() method before go to algorithm.Thanks in advance. – Thabo Mar 03 '12 at 15:52

13 Answers13

50

If you've already checked that the keys are the same, you can just use:

var dict3 = dict2.Where(entry => dict1[entry.Key] != entry.Value)
                 .ToDictionary(entry => entry.Key, entry => entry.Value);

To explain, this will:

  • Iterate over the key/value pairs in dict2
  • For each entry, look up the value in dict1 and filter out any entries where the two values are the same
  • Form a dictionary from the remaining entries (i.e. the ones where the dict1 value is different) by taking the key and value from each pair just as they appear in dict2.

Note that this avoids relying on the equality of KeyValuePair<TKey, TValue> - it might be okay to rely on that, but personally I find this clearer. (It will also work when you're using a custom equality comparer for the dictionary keys - although you'd need to pass that to ToDictionary, too.)

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
43

try :

dictionary1.OrderBy(kvp => kvp.Key)
           .SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key))
Noctis
  • 11,175
  • 3
  • 40
  • 79
Royi Namir
  • 138,711
  • 129
  • 435
  • 755
  • 1
    Is this compare with values? is this return a collection or boolean. – Thabo Mar 03 '12 at 16:04
  • 1
    I tried several different options with the Dictionary key being a string and this one seemed to be the fastest by far. – Gene S Apr 03 '17 at 20:44
33

to check any difference,

dic1.Count == dic2.Count && !dic1.Except(dic2).Any();

following code return all the different values

dic1.Except(dic2) 
Chamika Sandamal
  • 22,932
  • 5
  • 63
  • 83
  • can you explain this little bit?:) – Thabo Mar 03 '12 at 16:14
  • 2
    @Thabo: The dictionaries are equivalent if they are the same size and there are no elements which are in the first and not in the second. second line directly return all the elements which are in the first and not in the second – Chamika Sandamal Mar 03 '12 at 16:18
  • Where is ".Except( )" coming from? I tried this with an OrderedDictionary and got: Error CS1061 'OrderedDictionary' does not contain a definition for 'Except' and no accessible extension method 'Except' accepting a first argument of type 'OrderedDictionary' could be found (are you missing a using directive or an assembly reference?) – RichardB Jan 27 '20 at 02:29
  • 1
    @RichardB Linq. Add `using System.Linq;` at top of file, and try again. – Jacob R Jul 15 '20 at 08:28
14

You mentioned that both dictionaries have the same keys, so if this assumption is correct, you don't need anything fancy:

        foreach (var key in d1.Keys)
        {
            if (!d1[key].Equals(d2[key]))
            {
                d3.Add(key, d2[key]);
            }
        }

Or am I misunderstanding your problem?

carlosfigueira
  • 82,509
  • 14
  • 130
  • 169
5

Assuming both dictionaries have the same keys, the simplest way is

var result = a.Except(b).ToDictionary(x => x.Key, x => x.Value);

EDIT

Note that a.Except(b) gives a different result from b.Except(a):

a.Except(b): Price     20
b.Except(a): Price     40
Adi Lester
  • 24,307
  • 12
  • 89
  • 107
4

You should be able to join them on their keys and select both values. Then you can filter based on whether the values are the same or different. Finally, you can convert the collection to a dictionary with the keys and second values.

  var compared = first.Join( second, f => f.Key, s => s.Key, (f,s) => new { f.Key, FirstValue = f.Value, SecondValue = s.Value } )
                      .Where( j => j.FirstValue != j.SecondValue )
                      .ToDictionary( j => j.Key, j => j.SecondValue );

Using a loop shouldn't be too bad either. I suspect that they would have similar performance characteristics.

  var compared = new Dictionary<string,object>();
  foreach (var kv in first)
  {
      object secondValue;
      if (second.TryGetValue( kv.Key, out secondValue ))
      {
            if (!object.Equals( kv.Value, secondValue ))
            {
                compared.Add( kv.Key, secondValue );
            }
      }
  }
tvanfosson
  • 509,016
  • 97
  • 693
  • 791
4
var diff1 = d1.Except(d2);
var diff2 = d2.Except(d1);
return diff1.Concat(diff2);

Edit: If you sure all keys are same you can do:

var diff = d2.Where(x=>x.Value != d1[x.Key]).ToDictionary(x=>x.Key, x=>x.Value);
Saeed Amiri
  • 21,774
  • 5
  • 43
  • 82
1

In recent C# versions you can try

        public static Dictionary<TK, TV> ValueDiff<TK, TV>(this Dictionary<TK, TV> dictionary,
            Dictionary<TK, TV> otherDictionary)
        {
            IEnumerable<(TK key, TV otherValue)> DiffKey(KeyValuePair<TK, TV> kv)
            {
                var otherValue = otherDictionary[kv.Key];
                if (!Equals(kv.Value, otherValue))
                {
                    yield return (kv.Key, otherValue);
                }
            }

            return dictionary.SelectMany(DiffKey)
                .ToDictionary(t => t.key, t => t.otherValue, dictionary.Comparer);
        }

I am not sure that SelectManyis always the fastest solution, but it is one way to only select the relevant items and generate the resulting entries in the same step. Sadly C# does not support yield return in lambdas and while I could have constructed single or no item collections, I choose to use an inner function.

Oh and as you say that the keys are the same, it may be possible to order them. Then you could use Zip

        public static Dictionary<TK, TV> ValueDiff<TK, TV>(this Dictionary<TK, TV> dictionary,
            Dictionary<TK, TV> otherDictionary)
        {
            return dictionary.OrderBy(kv => kv.Key)
                .Zip(otherDictionary.OrderBy(kv => kv.Key))
                .Where(p => !Equals(p.First.Value, p.Second.Value))
                .ToDictionary(p => p.Second.Key, p => p.Second.Value, dictionary.Comparer);
        }

Personally I would tend not to use Linq, but a simple foreach like carlosfigueira and vanfosson:

        public static Dictionary<TK, TV> ValueDiff2<TK, TV>(this Dictionary<TK, TV> dictionary,
            Dictionary<TK, TV> otherDictionary)
        {
            var result = new Dictionary<TK, TV>(dictionary.Count, dictionary.Comparer);
            foreach (var (key, value) in dictionary)
            {
                var otherValue = otherDictionary[key];
                if (!Equals(value, otherValue))
                {
                    result.Add(key, otherValue);
                }
            }

            return result;
        }
TheConstructor
  • 4,165
  • 1
  • 30
  • 50
0

converting the object to dictionary then following set concept subtract them, result items should be empty in case they are identically.

 public static IDictionary<string, object> ToDictionary(this object source)
    {
        var fields = source.GetType().GetFields(
            BindingFlags.GetField |
            BindingFlags.Public |
            BindingFlags.Instance).ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source) ?? string.Empty
        );

        var properties = source.GetType().GetProperties(
            BindingFlags.GetField |
            BindingFlags.GetProperty |
            BindingFlags.Public |
            BindingFlags.Instance).ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source, null) ?? string.Empty
        );

        return fields.Concat(properties).ToDictionary(key => key.Key, value => value.Value); ;
    }
    public static bool EqualsByValue(this object source, object destination)
    {
        var firstDic = source.ToFlattenDictionary();
        var secondDic = destination.ToFlattenDictionary();
        if (firstDic.Count != secondDic.Count)
            return false;
        if (firstDic.Keys.Except(secondDic.Keys).Any())
            return false;
        if (secondDic.Keys.Except(firstDic.Keys).Any())
            return false;
        return firstDic.All(pair =>
          pair.Value.ToString().Equals(secondDic[pair.Key].ToString())
        );
    }
    public static bool IsAnonymousType(this object instance)
    {

        if (instance == null)
            return false;

        return instance.GetType().Namespace == null;
    }
    public static IDictionary<string, object> ToFlattenDictionary(this object source, string parentPropertyKey = null, IDictionary<string, object> parentPropertyValue = null)
    {
        var propsDic = parentPropertyValue ?? new Dictionary<string, object>();
        foreach (var item in source.ToDictionary())
        {
            var key = string.IsNullOrEmpty(parentPropertyKey) ? item.Key : $"{parentPropertyKey}.{item.Key}";
            if (item.Value.IsAnonymousType())
                return item.Value.ToFlattenDictionary(key, propsDic);
            else
                propsDic.Add(key, item.Value);
        }
        return propsDic;
    }
originalObj.EqualsByValue(messageBody); // will compare values.

source of the code

Mohamed.Abdo
  • 1,716
  • 17
  • 12
0

if you need a full comparison of both (think venn diagram results), there are four discrete outcomes for a given key assuming it is present in at least one of the dictionaries

public enum KeyCompareResult
{
  ValueEqual,
  NotInLeft,
  NotInRight,
  ValueNotEqual,
}

To get all of the keys in a dictionary, use dictionary.Keys. To get the set of keys in either dictionary, use Enumerable.Union, which will combine the sets and filter out duplicates.

Assuming you want some more generic method, you can then write your comparison as

public IEnumerable<KeyValuePair<TKey, KeyCompareResult>> GetDifferences<TKey, TValue>(
    IDictionary<TKey, TValue> leftDict,
    IDictionary<TKey, TValue> rightDict,
    IEqualityComparer<TValue> comparer = null)
{
    var keys = leftDict.Keys.Union(rightDict.Keys);
    comparer ??= EqualityComparer<TValue>.Default;
    return keys.Select(key =>
    {
        if (!leftDict.TryGetValue(key, out var left))
        {
            return KeyValuePair.Create<TKey, KeyCompareResult>(key, KeyCompareResult.NotInLeft);
        }
        else if (!rightDict.TryGetValue(key, out var right))
        {
            return KeyValuePair.Create<TKey, KeyCompareResult>(key, KeyCompareResult.NotInRight);
        }
        else if (!comparer.Equals(left, right))
        {
            return KeyValuePair.Create<TKey, KeyCompareResult>(key, KeyCompareResult.ValueNotEqual);
        }
        else
        {
            return KeyValuePair.Create<TKey, KeyCompareResult>(key, KeyCompareResult.ValueEqual);
        }
    });
}

The left/right distinction isn't obvious unless you are looking at the method call, so, you probably want to select the method results into messages or some other more meaningful data structure

var left = new Dictionary<int, string> { { 1, "one" }, { 2, "two" }, { 4, "four" } };
var right = new Dictionary<int, string> { { 1, "one" }, { 2, "A different value" }, { 3, "three" } };

GetDifferences(left, right, StringComparer.InvariantCulture)
    .Display(); // or however you want to process the data
/*
Key Value
--- -------------
  1 ValueEqual 
  2 ValueNotEqual 
  4 NotInRight 
  3 NotInLeft 
*/
J Scott
  • 248
  • 4
  • 7
0

Serialize the Dictionaries to a string:

var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new OrderedContractResolver() };
var sourceHash = JsonConvert.SerializeObject(dictionary1, jsonSerializerSettings).GetHashCode();
var blobHash = JsonConvert.SerializeObject(dictionary2, jsonSerializerSettings).GetHashCode();

public class OrderedContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        return base.CreateProperties(type, memberSerialization).OrderBy(p => p.PropertyName).ToList();
    }
}

Then compare the HashCodes (or just the json strings). This code forces the parameters to appear in consistent order, so if your dictionaries contain the same values out of order, they should return equal.

This solution avoids the edge case of comparing a dictionary which is a subset to a larger dictionary, which will return equal in many of the other answers. This solution will likely be inefficient for very large dictionaries or if you are making a large number of comparisons - but it is simple.

jlo-gmail
  • 2,743
  • 1
  • 29
  • 50
-1
 public class SentenceCapitalization
{
    public static string SentenceCapitalizations(string str)
    {
        string[] strArray = str.Split(' ');//split words
        string capString = "";
        string capStr = "";
        foreach (string s in strArray)
        {
            if (s.Length > 0 && s != string.Empty)
            {
                capStr = s[0].ToString().ToUpper();
                capString += capStr + s.Remove(0, 1) +" ";
            }
        }
        return capString.TrimEnd();
    }
}
public class Step
{
    public static void Steps(int num)
    {
        for (int row = 1; row <= num; row++)
        {
            string str = "";
            for (int col = 1; col <= num; col++)
            {
                if (row == col || row > col)
                    str += "#";
                else if (row < col)
                    str += " ";

            }
            Console.WriteLine(str);

        }

    }
    public static void RevSteps(int num)
    {
        int count = 0;
        for (int row = 1; row <= num; row++)
        {
            string str = "";
            for (int col = 1; col <= num; col++)
            {
                count = num - row;
                if(col> count)
                {
                    str += "#";
                }
                else 
                    str += " ";

            }
            Console.WriteLine(str);

        }

    }

}
public class Pyramid
{
    public static void PyramidSteps()
    {
        Console.Write("enter number for Pyramid steps: ");
        int num = (int) Math.Round(Convert.ToDecimal(Console.ReadLine()));
        int rows = num;
        int cols = num + (num - 1);
        int emptyLCols, emptyRCols;
        for (int row = 1; row <= rows; row++)
        {
            string str = "";
            emptyLCols = rows - row;
            emptyRCols = rows + row;
            for (int col = 1; col <= cols; col++)
            {
                if(col<=emptyLCols || col>=emptyRCols)
                    str += " ";                    
                else 
                    str += "#";
            }
            Console.WriteLine(str);
        }

    }

}
public class vowels
{
    public static void Vowels()
    {
        Console.Write("enter String: ");
        string vowelStr = Console.ReadLine().ToLower();
        int count = 0;


        for(int i=0; i < vowelStr.Length; i++)
        {
            char c = vowelStr[i];
            if ("aeiou".Contains(c))
            {
                count++;
            }
        }
        Console.WriteLine("total vowels...."+count);
    }

}

public class SpiralMatrix
{
    public static void SpiralMatrixs()
    {
        Console.Write("enter number for SpiralMatrixs: ");
        int num = (int)Math.Round(Convert.ToDecimal(Console.ReadLine()));
        int[,] arr = new int[num,num];

        int startColumn=0, startRow=0, endColumn=num-1, endRow=num-1;
        int counter = 1;
       for(int k=0; (startColumn < endColumn && startRow <= endRow) && k<num; k++)
        {
            for(int i= startColumn; i <= endColumn; i++)
            {
                arr[startRow, i] = counter;
                counter++;
            }
            startRow++;
            for (int i = startRow; i <= endRow; i++)
            {
                arr[i, endColumn] = counter;
                counter++;
            }
            endRow--;
            startColumn++;
            k++;
        }



    }
}

public class Sorting
{
    public static int RecFactorials(int num)
    {
        if (num == 0)
            return 1;
        else
            return num * RecFactorials(num - 1);
    }
    public static int[] BubbleSort(int[] array)
    {
        for(int partIndex=array.Length-1; partIndex > 0; partIndex--)
        {
            for(int i=0; i < partIndex; i++)
            {
                if(array[i]> array[i + 1])
                {
                    Swap(array, i, i + 1);
                }
            }                
        }
        return array;
    }
    public static int[] SelectionSort(int[] array)
    {
        for (int partIndex = array.Length - 1; partIndex > 0; partIndex--)
        {
            int largeIndexAt = 0;
            for(int i = 1; i <= partIndex; i++)
            {
                if (array[i] > array[largeIndexAt])
                {
                    largeIndexAt = i;
                }

            }
            Swap(array, largeIndexAt, partIndex);
        }
        return array;
    }
    public static int[] InsertionSort(int[] array)
    {
        for (int partIndex = 0; partIndex < array.Length ; partIndex++)
        {
            int currUnsort = array[partIndex];
            int i = 0;
            for ( i = partIndex; i >0 && array[i-1] > currUnsort; i--)
            {
                array[i] = array[i - 1];

            }
            array[i] = currUnsort;
        }
        return array;
    }
    public static void Swap(int[] arr, int i, int j)
    {
        int arrPre = arr[j];
        arr[j] = arr[i];
        arr[i] = arrPre; 
    }
}
public class Lists
{
    public static void SortList()
    {
        List<int> lsArray = new List<int>();
        for(int i=0; i < 16; i++)
        {
            lsArray.Add(i);
            LogList(lsArray);
        }
        LogList(lsArray);

        for(int i=10; i>0; i--)
        {
            lsArray.RemoveAt(i-1);
            LogList(lsArray);
        }
        lsArray.TrimExcess();
        LogList(lsArray);
        Console.ReadLine();
    }
    public static void LogList(List<int> ls)
    {
        Console.WriteLine("count: {0}, Capacity:{1}", ls.Count, ls.Capacity);
    }
    public static void ApiMembers()
    {
        var list = new List<int>() { 1, 0, 5, 3, 4 };
        list.Sort();

        int binarySearch = list.BinarySearch(5);

        list.Reverse();

        ReadOnlyCollection<int> readonlylist = list.AsReadOnly();

        readonlylist.Reverse();
        int count=list.Count();
        var listCustomers = new List<Customer>
        {
            new Customer{BirthDate=new DateTime(1988,08,12), Name="name1"},
            new Customer{BirthDate=new DateTime(1978,08,04), Name="name2"},
            new Customer{BirthDate=new DateTime(1978,09,04), Name="name3"},
            new Customer{BirthDate=new DateTime(1988,08,12), Name="name1"},
            new Customer{BirthDate=new DateTime(1998,08,12), Name="name1"},
            new Customer{BirthDate=new DateTime(1888,08,12), Name="name1"}
        };

        listCustomers.Sort((left, right) =>
        {
            if (left.BirthDate > right.BirthDate)
                return 1;
            if (right.BirthDate > left.BirthDate)
                return -1;
            return 0;
        });

    }
}
public class Customer
{
    public DateTime BirthDate;
    public string Name;
}

public class SingleLinkedList<T>
{
    public Node<T> Head { get; private set; }
    public Node<T> Tail { get; private set; }
    public int Count { get; private set; }
    private bool IsEmpty => Count == 0;
    public void AddFirst(T value)
    {
        AddFirst(new Node<T>(value));
    }

    private void AddFirst(Node<T> linkedListNode)
    {
        //save off the current head
        Node<T> tmp = Head;
        Head = linkedListNode;
        Head.Next = tmp;
        Count++;
        if(Count==1)
        { Tail = Head; }
    }

    public void RemoveFirst()
    {
        if(IsEmpty)
        {
            throw new InvalidOperationException();
        }
        Head = Head.Next;
        if (Count == 1)
            Tail = null;
        Count--;
    }
    public void RemoveLast()
    {
        if (IsEmpty)
        {
            throw new InvalidOperationException();
        }
        if(Count==1)
        {
            Head = Tail = null;
        }
        else
        {
            //find the penultimate node
            var current = Head;
            while (current.Next != Tail)
            {
                current = current.Next;

            }
            current.Next = null;
            Tail = current;
        }
        Count--;
    }
    public void AddLast(T value)
    {
        AddLast(new Node<T>(value));

    }

    private void AddLast(Node<T> node)
    {
        if (IsEmpty)
        {
            Head = node;
            Tail = node;
        }
        else
        {
            Tail.Next = node;
            Tail = node;
        }
        Tail = node;
        Count++;
    }

}
public class Node<T>
{

    public T Value { get; set; }
    public Node<T> Next { get; set; }

    public Node(T value)
    {
        this.Value = value;
    }



}
 public static void RevSteps(int num)
    {
        int count = 0;
        for (int row = 1; row <= num; row++)
        {
            string str = "";
            for (int col = 1; col <= num; col++)
            {
                count = num - row;
                if(col> count)
                {
                    str += "#";
                }
                else 
                    str += " ";

            }
            Console.WriteLine(str);

        }

    }
    public static void plusMinus()
    {
        int n = Convert.ToInt32(Console.ReadLine());

        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp))
        ;
        plusMinus(arr);
    }
    static void plusMinus(int[] arr)
    {
        int count = arr.Length;
        decimal pC = 0, bC = 0, zC = 0;
        for (int i = 0; i < count; i++)
        {
            if (arr[i] > 0)
            {//positive
                pC++;
            }
            else if (arr[i] < 0)
            {
                bC++;
            }
            else if (arr[i] == 0)
            {
                zC++;
            }

        }
        Console.WriteLine((pC / count).ToString("N6"));
        Console.WriteLine((bC / count).ToString("N6"));
        Console.WriteLine((zC / count).ToString("N6"));

    }
raj
  • 1
-2
 using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text.RegularExpressions;
 namespace algorithms
{
    public class Program
    {
        public static void Main(string[] args)
        {
            callAnnagrams();
            //callArrayChunkingStr();
            //callFizzBussStr();
            //callMaxChars();
            //callRevNumber();
            //string value = "Acheck";
            //Console.WriteLine("value" + value.IsStartWithA());
            //callPalindromeStringMethods();
            //callRevStringMethods();

        }
        public static void callRevStringMethods()
        {
            Console.WriteLine("Hello World!");
            string revString = RevStrings.RevString("You cannot convert an array of strings to an array of characters by just calling a method like ToCharArray");
            Console.WriteLine("reverse string " + revString);

            string revString2 = RevStrings.RevString2("You cannot convert an array of strings to an array of characters by just calling a method like ToCharArray");
            Console.WriteLine("reverse string2 " + revString2);

            string revString3 = RevStrings.RevString3("You cannot convert an array of strings to an array of characters by just calling a method like ToCharArray");
            Console.WriteLine("reverse string3 " + revString3);

            string revString4 = RevStrings.RevString4("You cannot convert an array of strings to an array of characters by just calling a method like ToCharArray");
            Console.WriteLine("reverse string4 " + revString4);

        }
        public static void callPalindromeStringMethods()
        {
            Console.WriteLine("Hello World!");
            bool blPalindrome = Palindrome.PalindromeString("abba");
            Console.WriteLine("string is Palindrome" + blPalindrome);
            bool blPalindrome1 = Palindrome.PalindromeString("dfasdf");
            Console.WriteLine("string is Palindrome" + blPalindrome1);
        }

        public static void callRevNumber()
        {

            Console.WriteLine("reversed -1123.567 value" + RevNumbers.RevNumber3(-1123.567));
            Console.WriteLine("reversed 1123.567 value" + RevNumbers.RevNumber3(1123.567));
            Console.WriteLine("reversed -1123.567" + RevNumbers.RevNumber2(-1123.567));
            Console.WriteLine("reversed 234 value" + RevNumbers.RevNumber(234));
            Console.WriteLine("reversed -234 value" + RevNumbers.RevNumber(-234));           

        }

        public static void callMaxChars()
        {
            //MaxChar.MaxCharsWithASCII("rwersfsdfsdfsdf");
            //MaxChar.MaxCharsWithASCII("testtestttettssssssssssstest");
            MaxChar.MaxCharsWithDictionary("testtestttettssssssssssstest");

        }
        public static void callFizzBussStr()
        {
            FizzBuss.FizzBussStr();
        }
        public static void callArrayChunkingStr()
        {
            int[] numArray = new int[] { 1, 3, 5, 6, 7, 8, 8,9 };
            ArrayList anum=new ArrayList { 'a','b','c','d','e' };
            ArrayChunking.ArrayChunkingStr2(anum, 3);
            Console.WriteLine();
            anum = new ArrayList { 1, 2, 3, 4, 5, 6, 7, 8,9 };
            ArrayChunking.ArrayChunkingStr2(anum, 2);
            Console.WriteLine();
            numArray = new int[] { 1, 2, 3, 4, 5 };
            ArrayChunking.ArrayChunkingStr(numArray, 10);
        }
        public static void callAnnagrams()
        {
            Annagram.Annagrams("this is a valid string ", "sa i hits daliv gnirts");
            Annagram.Annagrams("this is a valid string ", "ssdfasdfad dsfasdf453 $ ,fgdaliv gnirts");
            Annagram.Annagrams("string $ ONE ,", "snigtr # neo");

        }
    }
    public static class StringMethods
    {
        public static bool IsStartWithA(this string s)
        {
            return s.StartsWith('A');
        }
    }
    public class RevStrings
    {
        public static string RevString(string str)
        {
            var charArry = str.ToCharArray();
            Array.Reverse(charArry);
            return new string(charArry);
        }
        public static string RevString2(string str)
        {
            string revString = "";
            foreach( char c in str)
            {
                revString = c + revString;
            }

            return revString;
        }

        //no change to the order of the words
        public static string RevString3(string str)
        {
            string[] strArray = str.Split(' ');

            string revString = "";
            foreach (string s in strArray)
            {
                var charArray = s.ToCharArray();
                Array.Reverse(charArray);

                string reString = (strArray.Length > 1) ? new string(charArray) +" " : new string(charArray) + string.Empty;
                revString +=  reString;

            }

            return revString;
        }
        public static string RevString4(string str)
        {
            string[] strArray = str.Split(' ');

            string revString = "";
            foreach (string s in strArray)
            {
                string revWord = "";
                foreach(char c in s)
                {
                    revWord = c + revWord;
                }
                revString += revWord + " ";
            }

            return revString;
        }

    }

    public class Palindrome
    {
        public static bool PalindromeString(string str)
        {
            if (RevStrings.RevString3(str).ToUpper() == str.ToUpper())
                return true;
            else
                return false;
        }
    }

    public class RevNumbers
    {
        public static int RevNumber(int number)
        {
            string revStringNumber = RevStrings.RevString2(number.ToString().Replace("-", ""));

            Int32 num = Int32.Parse(revStringNumber) * Math.Sign(number);
            return num;
        }
        public static double RevNumber2(double number)
        {         
            string revStringNumber = RevStrings.RevString2(number.ToString().Replace("-", ""));
            double num = Convert.ToDouble(revStringNumber) * Math.Sign(number); 

            return num;
        }
        public static double RevNumber3(double number)
        {
            string[] strArray = number.ToString().Replace("-", "").Split('.');
            string revString = "";
            int i = 0;

            foreach (string s in strArray)
            {
                var charArray = s.ToCharArray();
                Array.Reverse(charArray);
                string reString = new string(charArray);
                if (i + 1 < strArray.Length && strArray[i].Length > 0)
                    revString += reString + ".";
                else
                    revString += reString;
                i++;
            }
            double num = Convert.ToDouble(revString.ToString().Replace("-", "")) * Math.Sign(number);

            return num;


        }


    }

    public class MaxChar
    {
        public static void MaxCharsWithASCII(string str)
        {
            int i = 0, l, max;
            int ascii;
            l = str.Length;
            int[] ch_freq = new int[255];

            for (i = 0; i < 255; i++)
            {
                ch_freq[i] = 0;
            }

            i = 0;
            while(i<l)
            {
                ascii = (int)str[i];
                ch_freq[ascii] += 1;

                i++;
            }

            max = 0;
            for(i=0; i<255; i++)
            {
                if (i != 32)
                {
                    if (ch_freq[i] > ch_freq[max])
                        max = i;
                }
            }
            Console.Write("The Highest frequency of character '{0}' is appearing for number of times : {1} \n\n", (char)max, ch_freq[max]);

        }
        public static void MaxCharsWithDictionary(string str)
        {
            int i = 0, l, max;
            l = str.Length;
            Dictionary<int, int> char_freq = new Dictionary<int, int>();

            i = 0;
            while (i < l)
            {
                if(!(char_freq.ContainsKey((int)str[i])))
                    char_freq.Add((int)str[i], 1);               
                else
                    char_freq[(int)str[i]]= char_freq[str[i]]+1;
                i++;
            }

            max = 0;
            for (i = 0; i < char_freq.Count; i++)
            {

                    if (char_freq[str[i]] > char_freq[str[max]])
                        max = i;

            }
            Console.Write("The Highest frequency of character '{0}' is appearing for number of times : {1} \n\n",(char)str[max], char_freq[str[max]]);

        }
        public static Dictionary<int,int> MaxCharsWithReturnDictionary(string str)
        {
            int i = 0, l, max;
            l = str.Length;
            Dictionary<int, int> char_freq = new Dictionary<int, int>();

            i = 0;
            while (i < l)
            {
                if (!(char_freq.ContainsKey((int)str[i])))
                    char_freq.Add((int)str[i], 1);
                else
                    char_freq[(int)str[i]] = char_freq[str[i]] + 1;
                i++;
            }

            max = 0;
            for (i = 0; i < char_freq.Count; i++)
            {

                if (char_freq[str[i]] > char_freq[str[max]])
                    max = i;

            }
            return char_freq;
        }

    }

    public class FizzBuss
    {
        public static void FizzBussStr()
        {
            double num =Convert.ToDouble(Console.ReadLine());
            for (int i = 1; i <= num; i++)
            {
                if ((i % 3 == 0) && (i % 5 == 0)) //by both
                    Console.WriteLine("FizzBuzz");
                else if (i % 3 == 0)  //by 3
                    Console.WriteLine("Fizz");
                else if( i % 5 == 0) //by 5
                    Console.WriteLine("Buzz");
                else Console.WriteLine(i);
            }

        }
    }

    public class ArrayChunking
    {
        public static ArrayList ArrayChunkingStr2(ArrayList intArray, int chunk)
        {
            ArrayList arrList = new ArrayList();

            int len = intArray.Count;
            int div = len / chunk;
            int howManyChunks = (len % chunk) > 0 ? div + 1 : div;
            int chkInc = 0;
            for (int chkk = 0; chkk < howManyChunks; chkk++)
            {
                ArrayList arr = new ArrayList();
                for (int i = 0; i < chunk; i++)
                {
                    if ((i + chkInc) < len)
                    {
                        arr.Insert(i, intArray[i + chkInc]);
                    }
                }
                chkInc += chunk;
                arrList.Add(arr);
            }

            if (howManyChunks > 0)
            {
                //Console.Write("[");
                string disarr = "[";
                for (int j = 0; j < howManyChunks; j++)
                {
                    //Console.Write("[");
                    disarr += "[";

                    ArrayList x = (ArrayList)arrList[j];
                    string dis = "";
                    for (int i = 0; i < x.Count; i++)
                    {
                        dis += x[i].ToString() + ",";
                    }
                    dis = dis.TrimEnd(',');
                    disarr += dis + "],";
                    //Console.Write(disarr);
                }
                disarr = disarr.TrimEnd(',');
                //Console.Write("]");
                disarr += "]";
                Console.Write(disarr);
            }
            return arrList;
        }
        public static ArrayList ArrayChunkingStr(int[] intArray,int chunk)
        {
            ArrayList arrList = new ArrayList();

            int len = intArray.Length;
            int div = len / chunk;
            int howManyChunks = (len % chunk) > 0 ? div + 1: div;
            int chkInc = 0;
            for(int chkk=0; chkk < howManyChunks; chkk++)
            {
                ArrayList arr = new ArrayList();
                for (int i = 0; i < chunk; i++)
                {
                    if ((i + chkInc) < len)
                    {
                        arr.Insert(i,intArray[i + chkInc]);
                    }
                }
                chkInc += chunk;
                arrList.Add(arr);
            }

            if (howManyChunks > 0)
            {
                //Console.Write("[");
                string disarr = "[";
                for (int j = 0; j < howManyChunks; j++)
                {
                    //Console.Write("[");
                    disarr += "[";

                    ArrayList x = (ArrayList)arrList[j];
                    string dis = "";
                    for (int i = 0; i < x.Count; i++)
                    {
                        dis += x[i].ToString() + ",";
                    }
                    dis = dis.TrimEnd(',');
                    disarr += dis + "],";
                    //Console.Write(disarr);
                }
                disarr = disarr.TrimEnd(',');
                //Console.Write("]");
                disarr += "]";
                Console.Write(disarr);
            }
            return arrList;
        }
    }

    public class Annagram
    {
        public static bool Annagrams(string str1, string str2)
        {

            str1 = Regex.Replace(str1.ToLower(), "[^a-zA-Z0-9]+", "", RegexOptions.Compiled);
            str2 = Regex.Replace(str2.ToLower(), "[^a-zA-Z0-9]+", "", RegexOptions.Compiled);

            Dictionary<int, int> str1Dic = MaxChar.MaxCharsWithReturnDictionary(str1.ToLower());

            Dictionary<int, int> str2Dic = MaxChar.MaxCharsWithReturnDictionary(str2.ToLower());
            if (str1Dic.Count != str2Dic.Count)
            {
                Console.WriteLine("strings are not annagrams");
                return false;
            }
            else
            {
                if (!(str1Dic.Keys.All(str2Dic.ContainsKey)))
                {
                    Console.WriteLine("strings are not annagrams");
                    return false;
                }
                else
                {
                    var dict3 = str2Dic.Where(entry => str1Dic[entry.Key] != entry.Value)
                            .ToDictionary(entry => entry.Key, entry => entry.Value);
                    if (dict3.Count > 0)
                    {
                        Console.WriteLine("strings are not annagrams");
                        return false;
                    }
                    else
                    {
                        Console.WriteLine("strings are  annagrams");
                        return true;
                    }
                }


            }

        }
    }
}
Kevin
  • 14,269
  • 7
  • 44
  • 64
raj
  • 1