Determine the unique string from a repeating string in C# - c#

I need to develop an efficient algorithm for determining the unique (repeated) string given a string with repeating content (and only repeating content)...
For example:
"AbcdAbcdAbcdAbcd" => "Abcd"
"Hello" => "Hello"
I'm having some trouble coming up with an algorithm that is fairly efficient; any input would be appreciated.
Clarification: I want the shortest string that, when repeated enough times, is equal to the total string.

private static string FindShortestRepeatingString(string value)
{
if (value == null) throw new ArgumentNullException("value", "The value paramter is null.");
for (int substringLength = 1; substringLength <= value.Length / 2; substringLength++)
if (IsRepeatingStringOfLength(value, substringLength))
return value.Substring(0, substringLength);
return value;
}
private static bool IsRepeatingStringOfLength(string value, int substringLength)
{
if (value.Length % substringLength != 0)
return false;
int instanceCount = value.Length / substringLength;
for (int characterCounter = 0; characterCounter < substringLength; characterCounter++)
{
char currentChar = value[characterCounter];
for (int instanceCounter = 1; instanceCounter < instanceCount; instanceCounter++)
if (value[instanceCounter * substringLength + characterCounter] != currentChar)
return false;
}
return true;
}

Maybe this can work:
static string FindShortestSubstringPeriod(string input)
{
if (string.IsNullOrEmpty(input))
return input;
for (int length = 1; length <= input.Length / 2; ++length)
{
int remainder;
int repetitions = Math.DivRem(input.Length, length, out remainder);
if (remainder != 0)
continue;
string candidate = input.Remove(length);
if (String.Concat(Enumerable.Repeat(candidate, repetitions)) == input)
return candidate;
}
return input;
}

Something like this:
public string ShortestRepeating(string str)
{
for(int len = 1; len <= str.Length/2; len++)
{
if (str.Length % len == 0)
{
sub = str.SubString(0, len);
StringBuilder builder = new StringBuilder(str.Length)
while(builder.Length < str.Length)
builder.Append(sub);
if(str == builder.ToString())
return sub;
}
}
return str;
}
This just starts looking at sub strings starting at the beginning and then repeats them to see if they match. It also skips any that do not have a length that doesn't evenly divide into the original strings length and only goes up to the length / 2 since anything over that cannot be a candidate for repeating.

I'd go with something like this:
private static string FindRepeat(string str)
{
var lengths = Enumerable.Range(1, str.Length - 1)
.Where(len => str.Length % len == 0);
foreach (int len in lengths)
{
bool matched = true;
for (int index = 0; matched && index < str.Length; index += len)
{
for (int i = index; i < index + len; ++i)
{
if (str[i - index] != str[i])
{
matched = false;
break;
}
}
}
if (matched)
return str.Substring(0, len);
}
return str;
}

Try this regular expression:
^(\w*?)\1*$
It captures as few characters as possible where the captured sequence (and only the captured sequence) repeat 0 or more times. You can get the text of the shortest match from the capture afterwards, as per Jacob's answer.

You could use a regular expression with back-references.
Match match = Regex.Match(#"^(.*?)\0*$");
String smallestRepeat = match.Groups[0];

Related

The splitting of a string without using String.Split method does not return correct result

I want to split a string without using the String.Split method.
I found a possible solution here. The code that I use is from the second answer.
This is my code:
public string[] SplitString(string input, char delimiter)
{
List<String> parts = new List<String>();
StringBuilder buff = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (input[i] == delimiter)
{
parts.Add(buff.ToString());
buff.Clear();
}
else
{
buff.Append(input[i]);
}
}
return parts.ToArray();
}
My problem here is that when I try to split a string like this
dog cat car person by " ", the result contains the words without the last one (in this example - person).
If after the last word there is a white space, the result is correct.
I tried to add something like i == input.Length when the for loop is from 0 to i <= input.Length. But the result was still without the last word.
Am I missing something?
Add another parts.Add(buff.ToString()); after exiting the loop - to flush the last word into the collection. You can check the length before doing so or not as commented and explained why by #hvd.
if(buff.Length != 0)
{
parts.Add(buff.ToString());
}
return parts.ToArray();
Another approach, instead of using a StringBuilder would be:
public static string[] SplitString(string input, char delimiter)
{
List<String> parts = new List<String>();
int start = 0;
for(int i = 0; i < input.Length; i++)
{
if(input[i] == delimiter)
{
parts.Add(input.Substring(start, i - start));
start = i + 1;
}
}
parts.Add(input.Substring(start, input.Length - start));
return parts.ToArray();
}
Or use yield return and return IEnumerable<string>:
public static IEnumerable<string> SplitString(string input, char delimiter)
{
int start = 0;
for(int i = 0; i < input.Length; i++)
{
if(input[i] == delimiter)
{
yield return input.Substring(start, i - start);
start = i + 1;
}
}
yield return input.Substring(start, input.Length - start);
}
Here is what you are missing in your code after for loop:
for (int i = 0; i < input.Length; i++)
{
if (input[i] == delimiter)
{
parts.Add(buff.ToString());
buff.Clear();
}
else
{
buff.Append(input[i]);
}
}
// This you need to add
if (!string.IsNullOrEmpty(buff.ToString()))
{
parts.Add(buff.ToString());
}
return parts.ToArray();

Latest Codility Time Problems

Just got done with the latest Codility, passed it, but didnt get 100% on it
Here is the spec
A prefix of a string S is any leading contiguous part of S. For example, "c" and "cod" are prefixes of the string "codility". For simplicity, we require prefixes to be non-empty.
The product of prefix P of string S is the number of occurrences of P multiplied by the length of P. More precisely, if prefix P consists of K characters and P occurs exactly T times in S, then the product equals K * T.
For example, S = "abababa" has the following prefixes:
"a", whose product equals 1 * 4 = 4,
"ab", whose product equals 2 * 3 = 6,
"aba", whose product equals 3 * 3 = 9,
"abab", whose product equals 4 * 2 = 8,
"ababa", whose product equals 5 * 2 = 10,
"ababab", whose product equals 6 * 1 = 6,
"abababa", whose product equals 7 * 1 = 7.
The longest prefix is identical to the original string. The goal is to choose such a prefix as maximizes the value of the product. In above example the maximal product is 10.
In this problem we consider only strings that consist of lower-case English letters (a−z).
So basically, it is a string traverse problem. I was able to pass all the validation parts, but I lost on the time. Here is what I wrote
int Solution(string S)
{
int finalCount = 0;
for (int i = 0; i <= S.Length - 1; i++)
{
string prefix = S.Substring(0, i + 1);
int count = 0;
for (int j = 0; j <= S.Length - 1; j++)
{
if (prefix.Length + j <= S.Length)
{
string newStr = S.Substring(j, prefix.Length);
if (newStr == prefix)
{
count++;
}
}
if (j == S.Length - 1)
{
int product = count * prefix.Length;
if (product > finalCount)
{
finalCount = product;
}
}
}
}
return finalCount;
}
I know that the nested loop is killing me, but I cannot think of a way to traverse the "sections" of the string without adding the other loop.
Any help would be appreciated.
Naive brute-force solution takes O(N ** 3) time. Choose length from 1 to N, get a prefix of its length and count occurences by brute-force searching. Сhoosing length takes O(N) time and brute force takes O(N ** 2) time, totally O(N ** 3).
If you use KMP or Z-algo, you can find occurences in O(N) time, so the whole solution will be O(N ** 2) time.
And you can precalc occurences, so it will take O(N) + O(N) = O(N) time solution.
vector<int> z_function(string &S); //z-function, z[0] = S.length()
vector<int> z = z_function(S);
//cnt[i] - count of i-length prefix occurrences of S
for (int i = 0; i < n; ++i)
++cnt[z[i]];
//if cnt[i] is in S, cnt[i - 1] will be in S
int previous = 0;
for (int i = n; i > 0; --i) {
cnt[i] += previous;
previous = cnt[i];
}
Here's the blog post, explaining all O(N ** 3), O(N ** 2), O(N) solutions.
my effort was as follows trying to eliminate unnecessary string compares, i read isaacs blog but it is in c how would this translate to c#, i even went as far as using arrays everywhere to avoid the string immutability factor but there was no improvement
int Rtn = 0;
int len = S.Length;
if (len > 1000000000)
return 1000000000;
for (int i = 1; i <= len; i++)
{
string tofind = S.Substring(0, i);
int tofindlen = tofind.Length;
int occurencies = 0;
for (int ii = 0; ii < len; ii++)
{
int found = FastIndexOf(S, tofind.ToCharArray(), ii);
if (found != -1)
{
if ((found == 0 && tofindlen != 1) || (found >= 0))
{
ii = found;
}
++occurencies ;
}
}
if (occurencies > 0)
{
int total = occurencies * tofindlen;
if (total > Rtn)
{
Rtn = total;
}
}
}
return Rtn;
}
static int FastIndexOf(string source, char[] pattern, int start)
{
if (pattern.Length == 0) return 0;
if (pattern.Length == 1) return source.IndexOf(pattern[0], start);
bool found;
int limit = source.Length - pattern.Length + 1 - start;
if (limit < 1) return -1;
char c0 = pattern[0];
char c1 = pattern[1];
// Find the first occurrence of the first character
int first = source.IndexOf(c0, start, limit);
while ((first != -1) && (first + pattern.Length <= source.Length))
{
if (source[first + 1] != c1)
{
first = source.IndexOf(c0, ++first);
continue;
}
found = true;
for (int j = 2; j < pattern.Length; j++)
if (source[first + j] != pattern[j])
{
found = false;
break;
}
if (found) return first;
first = source.IndexOf(c0, ++first);
}
return -1;
}
I only got a 43... I like my code though! Same script in javascript got 56 for what it's worth.
using System;
class Solution
{
public int solution(string S)
{
int highestCount = 0;
for (var i = S.Length; i > 0; i--)
{
int occurs = 0;
string prefix = S.Substring(0, i);
int tempIndex = S.IndexOf(prefix) + 1;
string tempString = S;
while (tempIndex > 0)
{
tempString = tempString.Substring(tempIndex);
tempIndex = tempString.IndexOf(prefix);
tempIndex++;
occurs++;
}
int product = occurs * prefix.Length;
if ((product) > highestCount)
{
if (highestCount > 1000000000)
return 1000000000;
highestCount = product;
}
}
return highestCount;
}
}
This works better
private int MaxiumValueOfProduct(string input)
{
var positions = new List<int>();
int max = 0;
for (int i = 1; i <= input.Length; i++)
{
var subString = input.Substring(0, i);
int position = 0;
while ((position < input.Length) &&
(position = input.IndexOf(subString, position, StringComparison.OrdinalIgnoreCase)) != -1)
{
positions.Add(position);
++position;
}
var currentMax = subString.Length * positions.Count;
if (currentMax > max) max = currentMax;
positions.Clear();
}
return max;
}

Find out how long the longest sequence is in a string

I recently had this question in an interview and this is what I came up with. Any feedback?
Find out how long the longest sequence is in a string. For example, in the string "abccdeeeeef" the answer would be 5.
static int LongestSeq(string strPass)
{
int longestSeq = 0;
char[] strChars = strPass.ToCharArray();
int numCurrSeq = 1;
for (int i = 0; i < strChars.Length - 1; i++)
{
if (strChars[i] == strChars[i + 1])
{
numCurrSeq++;
}
else
{
numCurrSeq = 1;
}
if (longestSeq < numCurrSeq)
{
longestSeq = numCurrSeq;
}
}
return longestSeq;
}
This will return 0 for strings of length 1 (when it should return 1).
First comment: you don't need to convert it to a char array. You can index straight into the string.
Second comment: you could easily generalize this to IEnumerable<T> if you wanted to, using foreach and remembering the "current" item.
Third comment: I think the comparison between longestSeq and numCurrSeq would be clearer as:
if (numCurrSeq > longestSeq)
To me that's more natural as I usually have the varying part of the expression first.
Just to add my 2 pence in, here's an alternative using Regex:
string source = "eeabccdeeeeef";
Regex reg = new Regex(#"(\w)\1+");
MatchCollection matches = reg.Matches(source);
int longest = 0;
foreach (System.Text.RegularExpressions.Match match in matches)
{
if (longest < match.Length) longest = match.Length;
}
Due to not reading the question properly in the first place when posting my previous answer, I should probably add in some actual feedback considering that's the question posted by the OP. However, every point I've come up with has been mentioned by Henrik or Job Skeet, so I'll just stress the point Jon Skeet made; you do not have to convert a string to a char array, you can just index a particular point in the string as follows:
char letter = someString[4];
So it should all still work if you replace strChars with strPass.
You can always rember the last character, so you don't need to access the array twice in an iteration.
Inside your loop you can use another loop which iterates as long as the current character is the same as the last character. After this subloop you can place the check if the current numCurrSeq > longestSeq you you don't need this check every iteration but for every subsequence.
I don't really know whatever langauge this is (C#?) so excuse any minor syntactic glitches (I don't know if it's "else if" or "elseif" or "elif" or something else)
static int LongestSeq(string strPass)
{
int longestSeq = 1;
int curSeqStart = 0;
for (int i = 1; i < strPass.Length; i++)
{
if (strPass[i] != strPass[curSeq])
{
curSeqStart = i;
}
else if (i - curSeqStart + 1 > longestSeq)
{
longestSeq = i - curSeqStart + 1;
}
}
return longestSeq;
}
It might be more efficient to do
...
else
{
len = i - curSeqStart + 1
if ( len > longestSeq )
{
longestSeq = len;
}
}
or even just
...
else
{
longestSeq = max(longestSeq, i - curSeqStart + 1)
}
depending on how good your 'max' implementation and compiler are.
I think this works? I don't ussually write recursive methods, I would have totally come up with the posters answer..
public static int recurse(Char last, int seqLength, int currentIndex, int largestSeqLength, string source)
{
if (currentIndex > source.Length)
{
return largestSeqLength;
}
if (source[currentIndex] == last)
{
seqLength++;
if (seqLength > largestSeqLength)
{
largestSeqLength = seqLength;
}
}
else
{
seqLength = 1;
}
return recurse(source[currentIndex], seqLength, currentIndex++, largestSeqLength, source);
}
And another implementation
public static int LongestSeq<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException("source");
int result = 0;
int currentCount = 0;
using (var e = source.GetEnumerator())
{
var lhs = default(T);
if (e.MoveNext())
{
lhs = e.Current;
currentCount = 1;
result = currentCount;
}
while (e.MoveNext())
{
if (lhs.Equals(e.Current))
{
currentCount++;
}
else
{
currentCount = 1;
}
result = Math.Max(currentCount, result);
lhs = e.Current;
}
}
return result;
}
A simple (untested) solution would be:
int GetLongestSequence(string input)
{
char c = 0;
int maxSequenceLength = 0;
int maxSequenceStart = 0;
int curSequenceLength = 0;
int length = input.Length;
for (int i = 0; i < length; ++i)
{
if (input[i] == c)
{
++curSequenceLength;
if (curSequenceLength > maxSequenceLength)
{
maxSequenceLength = curSequenceLength;
maxSequenceStart = i - (curSequenceLength - 1);
}
}
else
{
curSequenceLength = 1;
c = input[i];
}
}
return maxSequenceStart;
}
Or a better structured code (also untested):
private int GetSequenceLength(string input, int start)
{
int i = start;
char c = input[i];
while (input[i] == c) ++i; // Could be written as `while (input[i++] == c);` but i don't recommend that
return (i - start);
}
public int GetLongestSequence(string input)
{
int length = input.Length;
int maxSequenceLength = 0;
int maxSequenceStart = 0;
for (int i = 0; i < length; /* no ++i */)
{
int curSequenceLength = this.GetSequenceLength(input, i);
if (curSequenceLength > maxSequenceLength)
{
maxSequenceLength = curSequenceLength;
maxSequenceStart = i;
}
i += curSequenceLength;
}
return maxSequenceStart;
}
This extension method find the longest sequence of same characters in a string.
public static int GetLongestSequenceOfSameCharacters(this string sequence)
{
var data = new List<char>();
for (int i = 0; i < sequence.Length; i++)
{
if (i > 0 && (sequence[i] == sequence[i - 1]))
{
data.Add(sequence[i]);
}
}
return data.GroupBy(x => x).Max(x => x.Count()) + 1;
}
[TestMethod]
public void TestMethod1()
{
// Arrange
string sequence = "aabbbbccccce";
// Act
int containsSameNumbers = sequence.GetLongestSequenceOfSameCharacters();
// Assert
Assert.IsTrue(containsSameNumbers == 5);
}

Convert integer to binary in C#

How to convert an integer number into its binary representation?
I'm using this code:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
But it throws an exception:
Could not find any parsable digits
Your example has an integer expressed as a string. Let's say your integer was actually an integer, and you want to take the integer and convert it to a binary string.
int value = 8;
string binary = Convert.ToString(value, 2);
Which returns 1000.
Convert from any classic base to any base in C#
string number = "100";
int fromBase = 16;
int toBase = 10;
string result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
// result == "256"
Supported bases are 2, 8, 10 and 16
Very Simple with no extra code, just input, conversion and output.
using System;
namespace _01.Decimal_to_Binary
{
class DecimalToBinary
{
static void Main(string[] args)
{
Console.Write("Decimal: ");
int decimalNumber = int.Parse(Console.ReadLine());
int remainder;
string result = string.Empty;
while (decimalNumber > 0)
{
remainder = decimalNumber % 2;
decimalNumber /= 2;
result = remainder.ToString() + result;
}
Console.WriteLine("Binary: {0}",result);
}
}
}
http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html
public string DecimalToBinary(string data)
{
string result = string.Empty;
int rem = 0;
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
int num = int.Parse(data);
while (num > 0)
{
rem = num % 2;
num = num / 2;
result = rem.ToString() + result;
}
}
}
catch (Exception ex)
{
error = ex.Message;
}
return result;
}
primitive way:
public string ToBinary(int n)
{
if (n < 2) return n.ToString();
var divisor = n / 2;
var remainder = n % 2;
return ToBinary(divisor) + remainder;
}
Another alternative but also inline solution using Enumerable and LINQ is:
int number = 25;
string binary = Enumerable.Range(0, (int)Math.Log(number, 2) + 1).Aggregate(string.Empty, (collected, bitshifts) => ((number >> bitshifts) & 1 ) + collected);
Convert.ToInt32(string, base) does not do base conversion into your base. It assumes that the string contains a valid number in the indicated base, and converts to base 10.
So you're getting an error because "8" is not a valid digit in base 2.
String str = "1111";
String Ans = Convert.ToInt32(str, 2).ToString();
Will show 15 (1111 base 2 = 15 base 10)
String str = "f000";
String Ans = Convert.ToInt32(str, 16).ToString();
Will show 61440.
static void convertToBinary(int n)
{
Stack<int> stack = new Stack<int>();
stack.Push(n);
// step 1 : Push the element on the stack
while (n > 1)
{
n = n / 2;
stack.Push(n);
}
// step 2 : Pop the element and print the value
foreach(var val in stack)
{
Console.Write(val % 2);
}
}
I know this answer would look similar to most of the answers already here, but I noticed just about none of them uses a for-loop. This code works, and can be considered simple, in the sense it will work without any special functions, like a ToString() with parameters, and is not too long as well. Maybe some prefer for-loops instead of just while-loop, this may be suitable for them.
public static string ByteConvert (int num)
{
int[] p = new int[8];
string pa = "";
for (int ii = 0; ii<= 7;ii = ii +1)
{
p[7-ii] = num%2;
num = num/2;
}
for (int ii = 0;ii <= 7; ii = ii + 1)
{
pa += p[ii].ToString();
}
return pa;
}
using System;
class Program
{
static void Main(string[] args) {
try {
int i = (int) Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n", i, ToBinary(i));
} catch(Exception e) {
Console.WriteLine("\n{0}\n", e.Message);
}
}
public static string ToBinary(Int64 Decimal) {
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0) {
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}
This function will convert integer to binary in C#:
public static string ToBinary(int N)
{
int d = N;
int q = -1;
int r = -1;
string binNumber = string.Empty;
while (q != 1)
{
r = d % 2;
q = d / 2;
d = q;
binNumber = r.ToString() + binNumber;
}
binNumber = q.ToString() + binNumber;
return binNumber;
}
class Program
{
static void Main(string[] args)
{
var #decimal = 42;
var binaryVal = ToBinary(#decimal, 2);
var binary = "101010";
var decimalVal = ToDecimal(binary, 2);
Console.WriteLine("Binary value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 6;
binaryVal = ToBinary(#decimal, 3);
binary = "20";
decimalVal = ToDecimal(binary, 3);
Console.WriteLine("Base3 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 47;
binaryVal = ToBinary(#decimal, 4);
binary = "233";
decimalVal = ToDecimal(binary, 4);
Console.WriteLine("Base4 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 99;
binaryVal = ToBinary(#decimal, 5);
binary = "344";
decimalVal = ToDecimal(binary, 5);
Console.WriteLine("Base5 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
Console.WriteLine();
#decimal = 16;
binaryVal = ToBinary(#decimal, 11);
binary = "b";
decimalVal = ToDecimal(binary, 11);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("Uh oh.. this aint right :( ... but let's cheat :P");
Console.WriteLine();
#decimal = 11;
binaryVal = Convert.ToString(#decimal, 16);
binary = "b";
decimalVal = Convert.ToInt32(binary, 16);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.ReadLine();
}
static string ToBinary(decimal number, int #base)
{
var round = 0;
var reverseBinary = string.Empty;
while (number > 0)
{
var remainder = number % #base;
reverseBinary += remainder;
round = (int)(number / #base);
number = round;
}
var binaryArray = reverseBinary.ToCharArray();
Array.Reverse(binaryArray);
var binary = new string(binaryArray);
return binary;
}
static double ToDecimal(string binary, int #base)
{
var val = 0d;
if (!binary.All(char.IsNumber))
return 0d;
for (int i = 0; i < binary.Length; i++)
{
var #char = Convert.ToDouble(binary[i].ToString());
var pow = (binary.Length - 1) - i;
val += Math.Pow(#base, pow) * #char;
}
return val;
}
}
Learning sources:
Everything you need to know about binary
including algorithm to convert decimal to binary
class Program{
static void Main(string[] args){
try{
int i = (int)Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));
}catch(Exception e){
Console.WriteLine("\n{0}\n",e.Message);
}
}//end Main
public static string ToBinary(Int64 Decimal)
{
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
// The algoritm gives us the binary number in reverse order (mirrored)
// We store it in an array so that we can reverse it back to normal
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}//end class Program
BCL provided Convert.ToString(n, 2) is good, but in case you need an alternate implementation which is few ticks faster than BCL provided one.
Following custom implementation works for all integers(-ve and +ve).
Original source taken from https://davidsekar.com/algorithms/csharp-program-to-convert-decimal-to-binary
static string ToBinary(int n)
{
int j = 0;
char[] output = new char[32];
if (n == 0)
output[j++] = '0';
else
{
int checkBit = 1 << 30;
bool skipInitialZeros = true;
// Check the sign bit separately, as 1<<31 will cause
// +ve integer overflow
if ((n & int.MinValue) == int.MinValue)
{
output[j++] = '1';
skipInitialZeros = false;
}
for (int i = 0; i < 31; i++, checkBit >>= 1)
{
if ((n & checkBit) == 0)
{
if (skipInitialZeros)
continue;
else
output[j++] = '0';
}
else
{
skipInitialZeros = false;
output[j++] = '1';
}
}
}
return new string(output, 0, j);
}
Above code is my implementation. So, I'm eager to hear any feedback :)
// I use this function
public static string ToBinary(long number)
{
string digit = Convert.ToString(number % 2);
if (number >= 2)
{
long remaining = number / 2;
string remainingString = ToBinary(remaining);
return remainingString + digit;
}
return digit;
}
static void Main(string[] args)
{
Console.WriteLine("Enter number for converting to binary numerical system!");
int num = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[16];
//for positive integers
if (num > 0)
{
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
Console.Write(arr[y]);
}
Console.ReadLine();
}
//for negative integers
else if (num < 0)
{
num = (num + 1) * -1;
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
if (arr[y] != 0)
{
arr[y] = 0;
}
else
{
arr[y] = 1;
}
Console.Write(arr[y]);
}
Console.ReadLine();
}
}
This might be helpful if you want a concise function that you can call from your main method, inside your class. You may still need to call int.Parse(toBinary(someint)) if you require a number instead of a string but I find this method work pretty well. Additionally, this can be adjusted to use a for loop instead of a do-while if you'd prefer.
public static string toBinary(int base10)
{
string binary = "";
do {
binary = (base10 % 2) + binary;
base10 /= 2;
}
while (base10 > 0);
return binary;
}
toBinary(10) returns the string "1010".
I came across this problem in a coding challenge where you have to convert 32 digit decimal to binary and find the possible combination of the substring.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
int numberofinputs = int.Parse(Console.ReadLine());
List<BigInteger> inputdecimal = new List<BigInteger>();
List<string> outputBinary = new List<string>();
for (int i = 0; i < numberofinputs; i++)
{
inputdecimal.Add(BigInteger.Parse(Console.ReadLine(), CultureInfo.InvariantCulture));
}
//processing begins
foreach (var n in inputdecimal)
{
string binary = (binaryconveter(n));
subString(binary, binary.Length);
}
foreach (var item in outputBinary)
{
Console.WriteLine(item);
}
string binaryconveter(BigInteger n)
{
int i;
StringBuilder output = new StringBuilder();
for (i = 0; n > 0; i++)
{
output = output.Append(n % 2);
n = n / 2;
}
return output.ToString();
}
void subString(string str, int n)
{
int zeroodds = 0;
int oneodds = 0;
for (int len = 1; len <= n; len++)
{
for (int i = 0; i <= n - len; i++)
{
int j = i + len - 1;
string substring = "";
for (int k = i; k <= j; k++)
{
substring = String.Concat(substring, str[k]);
}
var resultofstringanalysis = stringanalysis(substring);
if (resultofstringanalysis.Equals("both are odd"))
{
++zeroodds;
++oneodds;
}
else if (resultofstringanalysis.Equals("zeroes are odd"))
{
++zeroodds;
}
else if (resultofstringanalysis.Equals("ones are odd"))
{
++oneodds;
}
}
}
string outputtest = String.Concat(zeroodds.ToString(), ' ', oneodds.ToString());
outputBinary.Add(outputtest);
}
string stringanalysis(string str)
{
int n = str.Length;
int nofZeros = 0;
int nofOnes = 0;
for (int i = 0; i < n; i++)
{
if (str[i] == '0')
{
++nofZeros;
}
if (str[i] == '1')
{
++nofOnes;
}
}
if ((nofZeros != 0 && nofZeros % 2 != 0) && (nofOnes != 0 && nofOnes % 2 != 0))
{
return "both are odd";
}
else if (nofZeros != 0 && nofZeros % 2 != 0)
{
return "zeroes are odd";
}
else if (nofOnes != 0 && nofOnes % 2 != 0)
{
return "ones are odd";
}
else
{
return "nothing";
}
}
Console.ReadKey();
}
}
}
int x=550;
string s=" ";
string y=" ";
while (x>0)
{
s += x%2;
x=x/2;
}
Console.WriteLine(Reverse(s));
}
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
This was a interesting read i was looking for a quick copy paste.
I knew i had done this before long ago with bitmath differently.
Here was my take on it.
// i had this as a extension method in a static class (this int inValue);
public static string ToBinaryString(int inValue)
{
string result = "";
for (int bitIndexToTest = 0; bitIndexToTest < 32; bitIndexToTest++)
result += ((inValue & (1 << (bitIndexToTest))) > 0) ? '1' : '0';
return result;
}
You could stick spacing in there with a bit of modulos in the loop.
// little bit of spacing
if (((bitIndexToTest + 1) % spaceEvery) == 0)
result += ' ';
You could probably use or pass in a stringbuilder and append or index directly to avoid deallocations and also get around the use of += this way;
var b = Convert.ToString(i,2).PadLeft(32,'0').ToCharArray().Reverse().ToArray();
Just one line for 8 bit
Console.WriteLine(Convert.ToString(n, 2).PadLeft(8, '0'));
where n is the number

Split String into smaller Strings by length variable

I'd like to break apart a String by a certain length variable.
It needs to bounds check so as not explode when the last section of string is not as long as or longer than the length. Looking for the most succinct (yet understandable) version.
Example:
string x = "AAABBBCC";
string[] arr = x.SplitByLength(3);
// arr[0] -> "AAA";
// arr[1] -> "BBB";
// arr[2] -> "CC"
You need to use a loop:
public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
for (int index = 0; index < str.Length; index += maxLength) {
yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
}
}
Alternative:
public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
int index = 0;
while(true) {
if (index + maxLength >= str.Length) {
yield return str.Substring(index);
yield break;
}
yield return str.Substring(index, maxLength);
index += maxLength;
}
}
2nd alternative: (For those who can't stand while(true))
public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
int index = 0;
while(index + maxLength < str.Length) {
yield return str.Substring(index, maxLength);
index += maxLength;
}
yield return str.Substring(index);
}
Easy to understand version:
string x = "AAABBBCC";
List<string> a = new List<string>();
for (int i = 0; i < x.Length; i += 3)
{
if((i + 3) < x.Length)
a.Add(x.Substring(i, 3));
else
a.Add(x.Substring(i));
}
Though preferably the 3 should be a nice const.
It's not particularly succinct, but I might use an extension method like this:
public static IEnumerable<string> SplitByLength(this string s, int length)
{
for (int i = 0; i < s.Length; i += length)
{
if (i + length <= s.Length)
{
yield return s.Substring(i, length);
}
else
{
yield return s.Substring(i);
}
}
}
Note that I return an IEnumerable<string>, not an array. If you want to convert the result to an array, use ToArray:
string[] arr = x.SplitByLength(3).ToArray();
My solution:
public static string[] SplitToChunks(this string source, int maxLength)
{
return source
.Where((x, i) => i % maxLength == 0)
.Select(
(x, i) => new string(source
.Skip(i * maxLength)
.Take(maxLength)
.ToArray()))
.ToArray();
}
I actually rather use List<string> instead of string[].
Here's what I'd do:
public static IEnumerable<string> EnumerateByLength(this string text, int length) {
int index = 0;
while (index < text.Length) {
int charCount = Math.Min(length, text.Length - index);
yield return text.Substring(index, charCount);
index += length;
}
}
This method would provide deferred execution (which doesn't really matter on an immutable class like string, but it's worth noting).
Then if you wanted a method to populate an array for you, you could have:
public static string[] SplitByLength(this string text, int length) {
return text.EnumerateByLength(length).ToArray();
}
The reason I would go with the name EnumerateByLength rather then SplitByLength for the "core" method is that string.Split returns a string[], so in my mind there's precedence for methods whose names start with Split to return arrays.
That's just me, though.
Using Batch from MoreLinq, on .Net 4.0:
public static IEnumerable<string> SplitByLength(this string str, int length)
{
return str.Batch(length, String.Concat);
}
On 3.5 Concat need an array, so we can use Concat with ToArray or, new String:
public static IEnumerable<string> SplitByLength(this string str, int length)
{
return str.Batch(length, chars => new String(chars.ToArray()));
}
It may be a bit unintuitive to look at a string as a collection of characters, so string manipulation might be proffered.
Yet another slight variant (classic but simple and pragmatic):
class Program
{
static void Main(string[] args) {
string msg = "AAABBBCC";
string[] test = msg.SplitByLength(3);
}
}
public static class SplitStringByLength
{
public static string[] SplitByLength(this string inputString, int segmentSize) {
List<string> segments = new List<string>();
int wholeSegmentCount = inputString.Length / segmentSize;
int i;
for (i = 0; i < wholeSegmentCount; i++) {
segments.Add(inputString.Substring(i * segmentSize, segmentSize));
}
if (inputString.Length % segmentSize != 0) {
segments.Add(inputString.Substring(i * segmentSize, inputString.Length - i * segmentSize));
}
return segments.ToArray();
}
}
UPD: Using some Linq to make it actually succinct
static IEnumerable EnumerateByLength(string str, int len)
{
Match m = (new Regex(string.Format("^(.{{1,{0}}})*$", len))).Match(str);
if (m.Groups.Count &lt= 1)
return Empty;
return (from Capture c in m.Groups[1].Captures select c.Value);
}
Initial version:
static string[] Empty = new string [] {};
static string[] SplitByLength(string str, int len)
{
Regex r = new Regex(string.Format("^(.{{1,{0}}})*$",len));
Match m = r.Match(str);
if(m.Groups.Count &lt= 1)
return Empty;
string [] result = new string[m.Groups[1].Captures.Count];
int ix = 0;
foreach(Capture c in m.Groups[1].Captures)
{
result[ix++] = c.Value;
}
return result;
}
private string[] SplitByLength(string s, int d)
{
List<string> stringList = new List<string>();
if (s.Length <= d) stringList.Add(s);
else
{
int x = 0;
for (; (x + d) < s.Length; x += d)
{
stringList.Add(s.Substring(x, d));
}
stringList.Add(s.Substring(x));
}
return stringList.ToArray();
}
private void button2_Click(object sender, EventArgs e)
{
string s = "AAABBBCCC";
string[] a = SplitByLenght(s,3);
}
private string[] SplitByLenght(string s, int split)
{
//Like using List because I can just add to it
List<string> list = new List<string>();
// Integer Division
int TimesThroughTheLoop = s.Length/split;
for (int i = 0; i < TimesThroughTheLoop; i++)
{
list.Add(s.Substring(i * split, split));
}
// Pickup the end of the string
if (TimesThroughTheLoop * split != s.Length)
{
list.Add(s.Substring(TimesThroughTheLoop * split));
}
return list.ToArray();
}
I had the strange scenario where I had segmented a string, then rearranged the segments (i.e. reversed) before concatenating them, and then I later needed to reverse the segmentation. Here's an update to the accepted answer by #SLaks:
/// <summary>
/// Split the given string into equally-sized segments (possibly with a 'remainder' if uneven division). Optionally return the 'remainder' first.
/// </summary>
/// <param name="str">source string</param>
/// <param name="maxLength">size of each segment (except the remainder, which will be less)</param>
/// <param name="remainderFirst">if dividing <paramref name="str"/> into segments would result in a chunk smaller than <paramref name="maxLength"/> left at the end, instead take it from the beginning</param>
/// <returns>list of segments within <paramref name="str"/></returns>
/// <remarks>Original method at https://stackoverflow.com/questions/3008718/split-string-into-smaller-strings-by-length-variable </remarks>
private static IEnumerable<string> ToSegments(string str, int maxLength, bool remainderFirst = false) {
// note: `maxLength == 0` would not only not make sense, but would result in an infinite loop
if(maxLength < 1) throw new ArgumentOutOfRangeException("maxLength", maxLength, "Should be greater than 0");
// correct for the infinite loop caused by a nonsensical request of `remainderFirst == true` and no remainder (`maxLength==1` or even division)
if( remainderFirst && str.Length % maxLength == 0 ) remainderFirst = false;
var index = 0;
// note that we want to stop BEFORE we reach the end
// because if it's exact we'll end up with an
// empty segment
while (index + maxLength < str.Length)
{
// do we want the 'final chunk' first or at the end?
if( remainderFirst && index == 0 ) {
// figure out remainder size
var remainder = str.Length % maxLength;
yield return str.Substring(index, remainder);
index += remainder;
}
// normal stepthrough
else {
yield return str.Substring(index, maxLength);
index += maxLength;
}
}
yield return str.Substring(index);
}//--- fn ToSegments
(I also corrected a bug in the original while version resulting in empty segment if maxLength==1)
I have a recursive solution:
public List<string> SplitArray(string item, int size)
{
if (item.Length <= size) return new List<string> { item };
var temp = new List<string> { item.Substring(0,size) };
temp.AddRange(SplitArray(item.Substring(size), size));
return temp;
}
Thoug, it does not returns a IEnumerable but a List

Categories

Resources