Solved

C# alogirthm help

Posted on 2013-12-12
4
179 Views
Last Modified: 2014-04-17
Hi
I have following algorithm written in Java to determine if a string has all unique characters or not.

Can anyone help me write this same in C# both with hashing and non hashing techniques?

public static boolean isUniqueChars2(String str) {
boolean[] char_set = new boolean[256];
 for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i);
 if (char_set[val]) return false;
char_set[val] = true;
 }
 return true;
 }
0
Comment
Question by:Techsavy
  • 2
4 Comments
 
LVL 20

Expert Comment

by:Daniel Van Der Werken
ID: 39715048
This is how I would do it. It might not be the best or fastest or most efficient, but it works:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IsUniqueChar
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            bool allAreUnique = ContainsAllUniqeCharacters(inputString);

            inputString = "AABCDEFGHIJKLMNOPQRSTUVWXYZ";
            allAreUnique = ContainsAllUniqeCharacters(inputString);
        }

        public static bool ContainsAllUniqeCharacters(string inputString)
        {
            bool allAreUnique = false;
            List<char> charList = new List<char>();
            char[] charArray = inputString.ToCharArray();
            foreach(char c in charArray)
            {
                if (!charList.Contains(c))
                {
                    charList.Add(c);
                }
            }
            if ( charList.Count == inputString.Length)
            {
                allAreUnique = true;
            }
            return allAreUnique;
        }
    }
}

Open in new window

0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 39715325
Of course, hash algorithm is much faster:

        private void button8_Click(object sender, EventArgs e)
        {
            string inputString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            bool allAreUnique = ContainsAllUniqeCharacters(inputString);
            MessageBox.Show(allAreUnique.ToString());

            inputString = "AABCDEFGHIJKLMNOPQRSTUVWXYZ";
            allAreUnique = ContainsAllUniqeCharacters(inputString);
            MessageBox.Show(allAreUnique.ToString());
        }

        private bool ContainsAllUniqeCharacters(string inputString)
        {
            Dictionary<char, int> hash = new Dictionary<char, int>();

            foreach (char ch in inputString.ToCharArray())
            {
                if (hash.ContainsKey(ch))
                {
                    return false;
                }
                else
                {
                    hash.Add(ch, 1);
                }
            }
            return true;
        }

Open in new window

0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 39715683
I like the algorithm you have in the Java. IMO, it would beat anarki's Dictionary algorithm in terms of both memory usage and speed**. The C# version is almost identical:

public static bool isUniqueChars2(String str)
{
    bool[] char_set = new bool[256];

    for (int i = 0; i < str.Length; i++)
    {
        int val = str[i];
        if (char_set[val]) return false;
        char_set[val] = true;
    }

    return true;
}

Open in new window


I'd suggest modifying the array declaration though so that you're not using a hard-coded value for the size:

bool[] char_set = new bool[str.Length];

Open in new window


** You would need to analyze this at runtime, of course.
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 39715737
...it would beat anarki's Dictionary algorithm..

Definitely it will :). I even measured - at least, 10 times :).

The thing is that no one would care. You may do a check like:

if( inputString.Length >256)
   return false;

I.e. any string longer than 256 fails :). If you adjust this number (256)  by control chars it will be even smaller.

Does this matter will it take 20 ms or 2 ms to process then? :)
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

816 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now