Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise OR on strings for large strings in c#

I have two strings(with 1's and 0's) of equal lengths(<=500) and would like to apply Logical OR on these strings.

How should i approach on this. I'm working with c#.

When i consider the obvious solution, reading each char and applying OR | on them, I have to deal with apx, 250000 strings each with 500 length. this would kill my performance.

Performance is my main concern.

Thanks in advance!

like image 568
BetterLateThanNever Avatar asked Mar 06 '16 12:03

BetterLateThanNever


2 Answers

This is fastest way:

string x="";
string y="";
StringBuilder sb = new StringBuilder(x.Length);
for (int i = 0; i < x.Length;i++ )
{
    sb.Append(x[i] == '1' || y[i] == '1' ? '1' : '0');
}
string result = sb.ToString();
like image 168
Thanh Nguyen Avatar answered Oct 13 '22 01:10

Thanh Nguyen


Since it was mentioned that speed is a big factor, it would be best to use bit-wise operations.

Take a look at an ASCII table:

  • The character '0' is 0x30, or 00110000 in binary.
  • The character '1' is 0x31, or 00110001 in binary.

Only the last bit of the character is different. As such - we can safely say that performing a bitwise OR on the characters themselves will produce the correct character.

Another important thing we can do is do to optimize speed is to use a StringBuilder, initialized to the initial capacity of our string. Or even better: we can reuse our StringBuilder for multiple operations, although we have to ensure the StringBuilder has enough capacity.

With those optimizations considered, we can make this method:

string BinaryStringBitwiseOR(string a, string b, StringBuilder stringBuilder = null)
{
    if (a.Length != b.Length)
    {
        throw new ArgumentException("The length of given string parameters didn't match");
    }

    if (stringBuilder == null)
    {
        stringBuilder = new StringBuilder(a.Length);
    }
    else
    {
        stringBuilder.Clear().EnsureCapacity(a.Length);
    }

    for (int i = 0; i < a.Length; i++)
    {
        stringBuilder.Append((char)(a[i] | b[i]));
    }
    return stringBuilder.ToString();
}

Note that this will work for all bit-wise operations you would like to perform on your strings, you only have to modify the | operator.

like image 22
Gediminas Masaitis Avatar answered Oct 13 '22 03:10

Gediminas Masaitis