Make class to encapsulate isLong/isDouble Function - c#

i'm trying to make a class that contains 4 functions: isLong, isDouble, stringToLong, and stringToDouble. I am trying to do this without using a TryParse function. Ideally this class would receive a string and return the appropriate type (bool, bool, long, and double) in respective order.
For instance if i enter the number 100000 it returns True (bool) for isLong.
Below is an example of how i did isLong but i am having difficulty trying to do the same for isDouble for receiving decimals and for both stringToLong/stringToDouble.
public static bool isLong(string s)
{
bool ret = true;
int i;
s = s.Trim();
if (s[0] == '-')
{
i = 1;
}
else
{
i = 0;
}
for (; (i < s.Length); i = i + 1)
{
ret = ret && ((s[i] >= '0') && (s[i] <= '9'));
}
return (ret);
}

You could use MinValue and MaxValue properties for check numeric types, for instance you could define a method like this:
public bool IsLong(decimal value)
{
return value >= long.MinValue && value <= long.MaxValue && value == (long)value;
}

Related

How to know if a string length contains a specified amount of capped letters

I'm trying to know if a string contains a length between 5 and 10 and at the same time, 7-10 letters are in upper case. The idea is to detect if a message sent by a user is 70%-100% capped.
This is what I have tried so far:
bool IsMessageUpper(string input)
{
if (input.Length.Equals(5 <= 10) && (input.Take(7).All(c => char.IsLetter(c) && char.IsUpper(c))))
{
return true;
}
else
{
return false;
}
}
You can rewrite your method in this way
bool IsMessageUpper(string input)
{
int x = input.Length;
return x>=7 && x<= 10 && input.Count(char.IsUpper) >= 7;
}
You can also add some safety checks to handle undesidered inputs
bool IsMessageUpper(string input)
{
int x = (input ?? "").Length;
return x>=7 && x<= 10 && input.Count(char.IsUpper) >= 7;
}

Recursion of Palindrome without using auxiliary function?

I've written a recursion that checks if a string is a palindrome :
public static bool IsPalindrome(string value)
{
if ( value == null )
return false;
if ( value.Length == 0 )
return true;
return isPalindrome(value, 0, value.Length - 1);
}
private static bool isPalindrome(string value, int startChar, int endChar)
{
if ( value[startChar] != value[endChar] )
return false;
if ( startChar >= endChar )
return true;
return isPalindrome(value, startChar + 1, endChar - 1);
}
However I tried to find a way to do the same algorithm without using an auxiliary method that does the recursion (isPalindrome(.. , .. , ..)) however I still need the call of isPalindrome(...) .
How can I combine the two functions into one , where the recursion algorithm wouldn't make a call to any additional functions ?
Would replacing the separate method with an anonymous one be acceptable:
public static bool IsPalindrome(string value)
{
if (value == null)
return false;
if (value.Length == 0)
return true;
Func<string, int, int, bool> ip = null;
ip = (v, sc, ec) =>
{
if (v[sc] != v[ec])
return false;
if (sc >= ec)
return true;
return ip(v, sc + 1, ec - 1);
};
return ip(value, 0, value.Length - 1);
}
Here:
public static bool IsPalindrome(string value)
{
if ( value == null )
return false;
if ( value.Length <= 1 )
return true;
if ( value[0] != value[value.Length - 1] )
return false;
return IsPalindrome(value.Substring(1,value.Length - 2));
}
Performance would suck though... because this allocates n/2 strings...
You could do something a little smarter with an array window wrapper... But i don't recall .Net having those built in...
Option 2 :
public static bool IsPalindrome(IEnumerable<char> value)
{
if (value == null)
return false;
if (value.Count() <= 1)
return true;
if (value.First() != value.Last())
return false;
return IsPalindrome(value.Skip(1).Take(value.Count() - 1));
}
This has some hope of better performance... depending on how LINQ does specializations...
Tested the second one, and its dreadfully slow....
How about using a while-loop:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(IsPalindrome("TEST"));
Console.WriteLine(IsPalindrome("TESTSET"));
}
public static bool IsPalindrome(string value)
{
if ( value == null )
return false;
if ( value.Length == 0 )
return true;
int startChar = 0;
int endChar = value.Length - 1;
while(value[startChar] == value[endChar] && startChar < endChar)
{
startChar++;
endChar--;
if(startChar >= endChar) return true;
}
return false;
}
}
Output:
False
True
I like your recursive solution much more though.
EDIT
Or... you could do it with one statement:
public static bool IsPalindrome(string value)
{
if ( value == null )
return false;
return value == new String(value.ToCharArray().Reverse().ToArray());
}
EDIT
And another solution using a for-loop. It is similar to doing a reverse and then compare.
public static bool IsPalindrome(string value)
{
if ( value == null )
return false;
for(int i = 0, j = value.Length - 1; i < j; i++, j--) {
if(value[i] != value[j]) return false;
}
return true;
}
I would suggest something like this:
public static bool IsPalindrome(string value)
{
if ( value == null )
return false;
if ( value.Length == 0 )
return true;
int i=0;
bool _cont = true;
while(_cont){
if ( value[startChar+i] != value[endChar-i] ){
_cont = false;
return false;
if ( (startChar+i) >= (endChar-i) ){
i++;
}
else{
_cont = false;
return true;
}
}
}

c# console application program for palindrome string

public static int isPalindrome(char[] String)
{
if (String.Length == 0 || String.Length == 1)
return 1;
if (String[0] != String[String.Length - 1])
return 0;
return Convert.ToUInt32(isPalindrome(String);
}
I am not able to make it as instance method i am getting problems so please help me how to make it as dynamic
This should work:
public static int isPalindrome(char[] String)
{
string smallerString = String.ToString().Substring(1, String.Length - 1);
if (String.Length == 0 || String.Length == 1)
return 1;
if (String[0] != String[String.Length - 1])
return 0;
return Convert.ToInt32(isPalindrome(smallerString.ToCharArray()));
}
Without changing your types and return values
public static int isPalindrome(char[] str)
{
if (str.Length == 0 || str.Length == 1)
return 1;
if (str[0] != str[str.Length - 1])
return 0;
return isPalindrome(str.Skip(1).Take(str.Length-2).ToArray());
}
You are passing the same value to isPalindrome again and again. You can try something like the following (note I've used string in the example below):
private static bool isPalindrome(string s)
{
if(s.Length == 1 || s.Length == 0)
return true;
if(s[0] != s[s.Length -1])
return false;
return isPalindrome(s.SubsString(1, s.Length -2));
}
I think it could be very easy implemented.
public static bool IsPalindrome(String text)
{
if(string.IsNullOrWhiteSpace(text))
return false;
char[] arr = text.ToCharArray();
Array.Reverse(arr);
var reversedText = new string(arr);
return string.Equals(text, reversedText, StringComparison.OrdinalIgnoreCase);
}

Difference between int CompareTo method and ordinary If condition?

I have tried the comparison for two integer values by using two types
Type 1 :
int val1 = 1;
int val2 = 2;
var returnValue = val1.CompareTo(val2);//-1 for First int is smaller.
varreturnValue = val2.CompareTo(val1);// 1 for First int is larger
varreturnValue = val1.CompareTo(val1);//0 for Ints are equal.
If(varreturnValue ==1)
{
//Success
}
else
{
//Failure
}
Type 2:
int val1 = 1;
int val2 = 2;
if (val1 < val2)
{
//return -1 //Failure
}
else if (val2 < val1)
{
//return 2 //Success
}
else
{
// return 0 // Same
}
What is the difference these methods?
Which one(type) is better for standard coding .. ?
Any difference for performance in the types ?
When I take a peek at the internals of int's CompareTo() method (using ReSharper), I see this:
public int CompareTo(int value)
{
if (this < value)
return -1;
return this > value ? 1 : 0;
}
So it would appear, in the case of an int anyway, that the CompareTo() function is doing exactly what your second example does.
If we remove the ternary operator, it looks identical to your example:
public int CompareTo(int value)
{
if (this < value)
return -1;
if (this > value)
return -1;
return 0;
}
In my opinion, the CompareTo method is good in case you need to separate the logic that checks for equality and another logic that uses the result from the comparison. In your example, when you do your code like:
int val1 = 1;
int val2 = 2;
if (val1 < val2)
{
//return -1 //Failure
}
else if (val2 < val1)
{
//return 2 //Success
}
else
{
// return 0 // Same
}
You cannot return to another function the comparison result. Here is the code extracted from msdn:
enum Comparison {
LessThan=-1, Equal=0, GreaterThan=1};
public class ValueComparison
{
public static void Main()
{
int mainValue = 16325;
int zeroValue = 0;
int negativeValue = -1934;
int positiveValue = 903624;
int sameValue = 16325;
Console.WriteLine("Comparing {0} and {1}: {2} ({3}).",
mainValue, zeroValue,
mainValue.CompareTo(zeroValue),
(Comparison) mainValue.CompareTo(zeroValue));
}
}
In this case, the comparison result is represented as an enum and can be passed between functions.
Another case is you could even serialize the comparison result over the wire as a numeric value (-1,0,1) (return value of an ajax call, for example)
There may be not much thing to do with numeric comparison like this, but as noted by Patryk Ćwiek in his comment. CompareTo may be used via interface, which can be implemented by other datatypes including your custom ones.

Conditional expression algebra in C#

I am working on a small part of a matching system that uses boolean conditional expressions.
These conditional expressions are contrained to a single variable and a single operator (with an edge case of an Inclusive Between).
I am interested in:
Equal To "="
Greater than ">"
Greater Than Or Equal To ">="
Less Than "<"
Less Than Or Equal To "<="
Inclusive Between ">= AND <="
I have a requirement to compare two conditional expressions and evaluate:
1) Is there an overlap of possible values?
Does "X > 1000" overlap with "X > 999"? Yes.
2) If there is an overlap, return the overlap:
The overlap of "X > 1000" with "X > 999" is "X > 1000"
3) Is a conditional expression constrained by another?
"X < 999" is constrained by "X < 1000" ; "X < 1001" is not constrained by "X < 1000"
What I have done so far is build up a truth table of all possible combinations and return the results, but I was wondering if there was an easier way to calculate these?
Any Theory / Reference material / C# libraries out there?
I haven't heard of any, but you can easily do without them if you represent the constraints as intervals:
x > 1000 becomes (1000, double.Infinity)
x == 1000 becomes [1000, 1000]
etc.
This way you need only one class
class Constraint
{
double Lower; bool isLowerStrict;
double Upper; bool isUpperStrict;
bool isIn(double d)
{
return (isLowerStrict ? Lower < d : Lower <= d) &&
(isUpperStrict ? Upper > d : Upper >= d);
}
Constraint intersect(Constraint other)
{
Constraint result = new Constraint();
if (Lower > other.Lower)
{
result.Lower = Lower;
result.isLowerStrict = isLowerStrict;
}
else if (Lower < other.Lower)
{
result.Lower = other.Lower;
result.isLowerStrict = other.isLowerStrict;
}
else
{
result.Lower = Lower;
result.IsLowerStrict = isLowerStrict || other.isLowerStrict;
}
// the same for upper
return result;
}
public bool isEmpty()
{
if (Lower > Upper) return true;
if (Lower == Upper && (isLowerStrict || isUpperStrict)) return true;
return false;
}
public bool Equals(Constraint other)
{
if (isEmpty()) return other.isEmpty();
return (Lower == other.Lower) && (Upper = other.Upper) &&
(isLowerStrict == other.IsLowerStrict) &&
(isUpperStrict == other.isUpperStrict);
}
// construction:
static Constraint GreaterThan(double d)
{
return new Constraint()
{
Lower = d,
isLowerStrict = true,
Upper = double.PositiveInfinity,
isUpperStrict = false
};
}
static Constraint IsEqualTo(double d)
{
return new Constraint()
{
Lower = d,
isLowerStrict = false,
Upper = d,
isUpperStrict = false
};
}
// etc.
}
With this code, you can answer the questions:
1) overlap: a.Intersect(b).isEmpty()
2) intersect: a.Intersect(b)
3) constrain: a.Intersect(b).Equals(a)
EDIT:
As #CodeInChaos suggests, you should consider replacing double with decimal. Mind that decimal lacks infinite values, so you should use decimal.MaxValue and decimal.MinValue instead.
I had written some sample code fast. Hope it makes sense:
enum SygnType
{
More, Less, Equal
}
public class Representation
{
public SignType sign;
public int value;
}
public class Range
{
public bool infinityNegative;
public bool infinityPositive;
public int minValue;
public int maxValue;
public Range(List<Representation> values)
{
infinityNegative=true;
infinityPositive=true;
foreach(var value in values)
{
if (value.sign==SignType.More)
{
infinityNegative=false;
if (value>minValue)
minValue=value;
}
else if (value.sign==SignType.Less)
{
infinityPositive=false;
if (value<maxValue)
maxValue=value;
}
else if (value.sign==SignType.Equal)
{
infinityPositive=infinityNegative=false;
minValue=maxValue=value;
break;
}
}
}
public bool Overlaps(Range checkRange)
{
if (checkRange.infinityPositive)
return CompareUpperLevelValue(checkRange); //this method should compare upper value overlapping
else if (checkRange.infinityNegative)
return CompareLowerLevelValue(checkRange); //this method should compare lower value overlapping
else
return CompareInterval(checkRange); //this method should compare interval
}
public bool CompareUpperLevelValue(Range checkRange)
{
if (checkRange.maxValue<maxValue)
return true;
else
return false
}
public bool CompareLowerLevelValue(Range checkRange)
{
if (checkRange.minValue>minValue)
return true;
else
return false
}
public bool CompareInterval(Range checkRange)
{
if ((checkRange.minValue>minValue)&&(checkRange.maxValue<maxValue))
return true;
else
return false;
}
}

Categories