I want to have a number (let's say i) whose range is between 0 to 26 so that when the number is 26 and it is incremented by 1 (say i++) the value returns to 0 (i.e. the value is circular).
Is there such a thing in c#? What is it called? If not then how would I implement this in code (overloaded operators are accepted).
Make a property that limits the value:
private int _value;
public int Value {
get { return _value; }
set { _value = value % 27; }
}
Now when you increase the property the setter will limit the value.
Example:
Value = 25;
Value++; // Value is now 26
Value++; // Value is now 0
Value++; // Value is now 1
You can try this:
int result = number % 27;
Use modulus operator (%)
var x = 0;
x = (x+1) % 27;
if you want it to go 0,1,2,3, ..... 24,25,26, 0, 1, 2, 3, ...
use modulus 27
I don't know of any sort of 'boundaries' or rules, you can "set" for an int in the way you want. I'd suggest creating an if statement, or two, to control it. `
if( i <= 26 & i >= 0)
{ ..do something..}
else i = 0;
Something like this should accomplish what you ask:
class CircularInt
{
public int value;
public static CircularInt operator ++(CircularInt c)
{
if (c.value >= 26)
c.value = 0;
else
c.value++;
return c;
}
}
Then use it:
CircularInt cInt = new CircularInt();
cInt++;
Console.WriteLine(cInt.value);
Another option is to define your own immutable type.
public struct Value27
{
private readonly int val;
private readonly bool isDef;
private Value27(int value)
{
while (value < 0) value += 27;
val = value % 27;
isDef = true;
}
public static Value27 Make(int value)
{ return new Value27(value); }
public bool HasValue { get { return isDef; } }
public int Value { get { return val; } }
public static Value27 operator +(Value27 curValue)
{ return Make(curValue.Value + 1); }
public static Value27 operator -(Value27 curValue)
{ return Make(curValue.Value + 26); }
public static implicit operator Value27(int bValue)
{ return Make(bValue); }
public static implicit operator int (Value27 value)
{ return value.Value; }
}
Related
I am extremely new to C# and am still trying to wrap my head around some of its core concepts.First time posting a question to StackOverflow.
So this is what I need help with:
Make a property for: private string array; : so that:
"Each element of an array needs to be >=0 and <=10"
Should I run it through for, and then set array=value for each element or what?
This is what I did:
private string array;
public int[] Array
{
get { return array; } //-is this part good for the task?
set
{
//what do I do here to make sure the elements are withing the
//given interval?
}
}
See if this is what you need (Demo):
public class myClass
{
private int[] _Array = new int[10];
public int this[int index]
{
get { return _Array[index]; }
set
{
if (value >= 0 && value <= 10)
_Array[index] = value;
}
}
}
public class Program
{
public static void Main(string[] args)
{
myClass m = new myClass();
m[0] = 1;
m[1] = 12;
Console.WriteLine(m[0]); // outputs 1
Console.WriteLine(m[1]); // outputs default value 0
}
}
You are looking for something like this
private int[] _privateArray;
public int[] PublicArray
{
get
{
return _privateArray;
}
set
{
foreach (int val in value)
{
if (val < 0 || val > 10) throw new ArgumentOutOfRangeException();
}
// if you get to here you can set value
_privateArray = (int[])value.Clone();
}
}
please note private property and public property must be same type
I was attempting to solve the running median problem (on hackerrank) using a sorted set. Only it's elements don't appear properly sorted.
See it in action here: http://rextester.com/NGBN25779
public class RunningMedian{
List<int> list = new List<int>();
SortedSet<int> sorted = new SortedSet<int>();
public void Add(int num){
list.Add(num);
sorted.Add(num);
}
public double MedianNotWorking(){
return GetMedian(sorted.ToArray());
}
public double MedianWorking(){
int[] arr = list.ToArray();
Array.Sort(arr);
return GetMedian(arr);
}
public double GetMedian(int[] arr){
int idx = list.Count / 2;
if(arr.Length % 2 == 0){
return (double)((double)(arr[idx] + arr[idx-1]) / 2);
}else{
return arr[idx];
}
}
}
static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
int[] a = new int[n];
RunningMedian heap = new RunningMedian();
for(int i = 0; i < n; i++){
a[i] = Convert.ToInt32(Console.ReadLine());
heap.Add(a[i]);
//double median = heap.GetMedian();
double median = heap.MedianNotWorking();
Console.WriteLine(median.ToString("F1"));
}
}
For the most part the sorted set does work. However at larger input sizes it begins to give wrong answers. It may not be the optimal solution to the problem but I'm curious as to why it fails at all. C# doesn't have a min-heap / priority queue so why can't sorted sets be used as a substitute?
*Edited to include full code from hackerrank.
Here is an input file.
Input
http://textuploader.com/dovni
Expected
http://textuploader.com/dovnb
Output
http://textuploader.com/dovwj
Conflicts appear near the end
Expected
(Skipping 1-364)
54240.0
54576.5
54913.0
54576.5
54240.0
Results
(Skipping 1-364)
54240.0
54576.5
54913.0
54963.0
54576.5
SortedSet collections contain by definition only unique values. However your input file contains the number 21794 twice, which means that the second 21794 entry doesn't get added to your SortedSet. So your sorted set will contain fewer values than your list and your whole algorithm doesn't work anymore.
In general, this could be achieved by definition of new IComparator behavior for the SortedSet comparison. For the min priority queue it would be smth like this:
public class PriorityQueue<K,V> where K : IComparable
where V : IComparable
{
private SortedSet<Node<K,V>> _set;
private readonly int _amount;
public PriorityQueue(int amount)
{
_set = new SortedSet<Node<K,V>>(new PriorityComparer<K,V>());
_amount = amount;
}
public void Add(Node<K,V> value)
{
if (_amount > _set.Count)
_set.Add(value);
else
{
if (_set.Max.Val.CompareTo(value.Val) == 1)
{
_set.Remove(_set.Max);
_set.Add(value);
}
}
}
public Node<K,V> ExtractMax()
{
var max = _set.Max;
_set.Remove(max);
return max;
}
public Node<K,V> ExtractMin()
{
var min = _set.Min;
_set.Remove(min);
return min;
}
public bool IsEmpty => _set.Count == 0;
}
public struct Node<K,V> where K : IComparable
where V : IComparable
{
public K Key;
public V Val;
public Node(K key, V val)
{
Val = val;
Key = key;
}
}
public class PriorityComparer<K,V> : IComparer<Node<K,V>> where K: IComparable
where V: IComparable
{
public int Compare(Node<K,V> i, Node<K,V> y)
{
var compareresult = i.Val.CompareTo(y.Val);
if (compareresult == 0)
return i.Key.CompareTo(y.Key);
return compareresult;
}
}
Is there a way in C# to use maxvalue when an int would be out of range.
For my purposes I can't use a long.
Example
int a = 842673832;
int b = 2131231321;
int t = a * b;
//if t out of range, t = Int32.MinValue;
You would need to test it before hand or create a very special kind of integer (like CheckedInt in the link).
Option A
To test it before hand, you need a data type which can handle big integer value (say, long):
long t = (long)a * b;
int r = t > int.MaxValue ? int.MaxValue : t < int.MinValue ? : int.MinValue : (int)t;
Option B
To use the special kind of integer, you may need to overload the basic operators too.
In the example in the link, the exception is thrown, but you could change the exception into implementing int.MaxValue or int.MinValue, something like this:
public struct CheckedInt {
private int Value { get; set; }
public CheckedInt(int value)
: this() {
Value = value;
}
public static implicit operator CheckedInt(int me) {
return new CheckedInt(me);
}
public static CheckedInt operator +(CheckedInt lhs, CheckedInt rhs) {
double testResult = (double)lhs.Value + (double)rhs.Value;
if (testResult > int.MaxValue)
return int.MaxValue;
if (testResult < int.MinValue)
return int.MinValue;
return new CheckedInt(lhs.Value + rhs.Value); //note that direct lhs+rhs will cause StackOverflow
}
public static CheckedInt operator -(CheckedInt lhs, CheckedInt rhs) {
double testResult = (double)lhs.Value - (double)rhs.Value;
if (testResult > int.MaxValue)
return int.MaxValue;
if (testResult < int.MinValue)
return int.MinValue;
return new CheckedInt(lhs.Value - rhs.Value); //note that direct lhs-rhs will cause StackOverflow
}
public static CheckedInt operator *(CheckedInt lhs, CheckedInt rhs) {
double testResult = (double)lhs.Value * (double)rhs.Value;
if (testResult > int.MaxValue)
return int.MaxValue;
if (testResult < int.MinValue)
return int.MinValue;
return new CheckedInt(lhs.Value * rhs.Value); //note that direct lhs*rhs will cause StackOverflow
}
public static CheckedInt operator /(CheckedInt lhs, CheckedInt rhs) {
double testResult = (double)lhs.Value / (double)rhs.Value;
if (testResult > int.MaxValue)
return int.MaxValue;
if (testResult < int.MinValue)
return int.MinValue;
return new CheckedInt(lhs.Value / rhs.Value); //note that direct lhs-rhs will cause StackOverflow
}
//Add any other overload that you want
public override string ToString() { //example
return Value.ToString();
}
public bool Equals(CheckedInt otherInt) { //example
return Value == otherInt.Value;
}
}
You can try this by enabling overflow checking
int t;
try
{
int a = 842673832;
int b = 2131231321;
t = checked(a * b);
}
catch (System.OverflowException e)
{
t = Int32.MaxValue;
}
If you want t to be an int and not a larger type like Ian's answer, you can catch at OverflowException and set t to MaxValue. Make sure to wrap the section in a checked keyword to allow overflow checking.
int t = 0;
checked {
try
{
int a = 842673832;
int b = 2131231321;
t = a * b;
}
catch (OverflowException)
{
t = int.MaxValue;
}
}
How would i create a type that works with integers, supports at least addition substraction division and multiplication and guarantees and integer number IF the operation leads to an integer (otherwise throw).
For example i'd like to be able to do something like:
Precise A = 10;
A.Divide(3);
A.GetNumber(); // This would throw an exception as 10/3 isn't an int.
A.Multiply(6);
int result = A.GetNumber; // I want result to be = to 20, not to a floating point type that would round to 2 or be very close like 1.9999999999999999999999998992
I realise this is a odd use case but i do have this need (performing a sequence of operations, which in floating point could be missrepresented, but are guaranteed to end up as a valid int).
Because we can't know that 10 / 3 will eventually result in a precise integer answer until after the * 6 we have to defer it until then with a promise:
public sealed class Precise
{
private interface IOperation
{
int Calculate(int value);
IOperation Combine(IOperation next);
}
private sealed class NoOp : IOperation
{
public static NoOp Instance = new NoOp();
public int Calculate(int value)
{
return value;
}
public IOperation Combine(IOperation next)
{
return next;
}
}
private sealed class Combo : IOperation
{
private readonly IOperation _first;
private readonly IOperation _second;
public Combo(IOperation first, IOperation second)
{
_first = first;
_second = second;
}
public int Calculate(int value)
{
return _second.Calculate(_first.Calculate(value));
}
public IOperation Combine(IOperation next)
{
return new Combo(_first, _second.Combine(next));
}
}
private sealed class Mult : IOperation
{
private readonly int _multiplicand;
public Mult(int multiplicand)
{
_multiplicand = multiplicand;
}
public int Calculate(int value)
{
return value * _multiplicand;
}
public int Multiplicand
{
get { return _multiplicand; }
}
public IOperation Combine(IOperation next)
{
var nextMult = next as Mult;
if(nextMult != null)
return new Mult(_multiplicand * nextMult._multiplicand);
var nextDiv = next as Div;
if(nextDiv != null)
{
int divisor = nextDiv.Divisor;
if(divisor == _multiplicand)
return NoOp.Instance;//multiplcation by 1
if(divisor > _multiplicand)
{
if(divisor % _multiplicand == 0)
return new Div(divisor / _multiplicand);
}
if(_multiplicand % divisor == 0)
return new Mult(_multiplicand / divisor);
}
return new Combo(this, next);
}
}
private sealed class Div : IOperation
{
private readonly int _divisor;
public Div(int divisor)
{
_divisor = divisor;
}
public int Divisor
{
get { return _divisor; }
}
public int Calculate(int value)
{
int ret = value / _divisor;
if(value != ret * _divisor)
throw new InvalidOperationException("Imprecise division");
return ret;
}
public IOperation Combine(IOperation next)
{
var nextDiv = next as Div;
if(nextDiv != null)
return new Div(_divisor * nextDiv._divisor);
var nextMult = next as Mult;
if(nextMult != null)
{
var multiplicand = nextMult.Multiplicand;
if(multiplicand == _divisor)
return NoOp.Instance;
if(multiplicand > _divisor)
{
if(multiplicand % _divisor == 0)
return new Mult(multiplicand / _divisor);
}
else if(_divisor % multiplicand == 0)
return new Div(multiplicand / _divisor);
}
return new Combo(this, next);
}
}
private sealed class Plus : IOperation
{
private readonly int _addend;
public Plus(int addend)
{
_addend = addend;
}
public int Calculate(int value)
{
return value + _addend;
}
public IOperation Combine(IOperation next)
{
var nextPlus = next as Plus;
if(nextPlus != null)
{
int newAdd = _addend + nextPlus._addend;
return newAdd == 0 ? (IOperation)NoOp.Instance : new Plus(newAdd);
}
return new Combo(this, next);
}
}
private readonly int _value;
private readonly IOperation _operation;
public static readonly Precise Zero = new Precise(0);
private Precise(int value, IOperation operation)
{
_value = value;
_operation = operation;
}
public Precise(int value)
: this(value, NoOp.Instance)
{
}
public int GetNumber()
{
return _operation.Calculate(_value);
}
public static explicit operator int(Precise value)
{
return value.GetNumber();
}
public static implicit operator Precise(int value)
{
return new Precise(value);
}
public override string ToString()
{
return GetNumber().ToString();
}
public Precise Multiply(int multiplicand)
{
if(multiplicand == 0)
return Zero;
return new Precise(_value, _operation.Combine(new Mult(multiplicand)));
}
public static Precise operator * (Precise precise, int value)
{
return precise.Multiply(value);
}
public Precise Divide(int divisor)
{
return new Precise(_value, _operation.Combine(new Div(divisor)));
}
public static Precise operator / (Precise precise, int value)
{
return precise.Divide(value);
}
public Precise Add(int addend)
{
return new Precise(_value, _operation.Combine(new Plus(addend)));
}
public Precise Subtract(int minuend)
{
return Add(-minuend);
}
public static Precise operator + (Precise precise, int value)
{
return precise.Add(value);
}
public static Precise operator - (Precise precise, int value)
{
return precise.Subtract(value);
}
}
Here each Precise has both an integer value and an operation that will be performed on it. Further operations produce a new Precise (doing this sort of thing as a mutable is crazy) with a new operation but when possible those operations are combined into a single simpler operation. Hence "divide by three then multiply by six" becomes "multiply by two".
We can test this thus:
public static void Main(string[] args)
{
Precise A = 10;
A /= 3;
try
{
var test = (int)A;
}
catch(InvalidOperationException)
{
Console.Error.WriteLine("Invalid operation attempted");
}
A *= 6;
int result = (int)A;
Console.WriteLine(result);
// Let's do 10 / 5 * 2 = 4 because it works but can't be pre-combined:
Console.WriteLine(new Precise(10) / 5 * 2);
// Let's do 10 / 5 * 2 - 6 + 4 == 2 to mix in addition and subtraction:
Console.WriteLine(new Precise(10) / 5 * 2 - 6 + 4);
Console.Read();
}
A good solution would also deal well with operations done where the LHS was an integer and the RHS a Precise and where both where a Precise; left as an exercise for the reader ;)
Sadly we have to get much more complicated to handle (10 / 3 + 1) * 3, with the improvement having to be made in the Combine implementations.
Edit: Musing a bit further on the issues of doing the above well enough to catch at least most of the edge cases, I think it should start with only dealing with operations between two Precise objects, because going int -> Precise is trivial and can easily be put on top, but going Precise -> int requires a call to the calculation, perhaps too early. I'd also make the operations the key thing acted upon (have the operation store one or two objects which in turn contain an operation or a value). Then if you started with a representation of the sum (10 / 3) + 5 and multiplied it by 6 it's easier to turn that into (10 * (6 / 3)) + (5 * 6) which upon final calculation can give the precise result 50 rather than fail because it hits the imprecise 10 / 3.
If you don't allow arbitrary precision rationals, it seems that you are asking the impossible without more constraints.
Take 1 and divide it by 65537 twice, then multiply by 65537 twice to retrieve 1: this can't fit in 32 bits integers.
Then round final answer using Math.Round().
I would use a decimal for the result of operation and on the GetNumber check on the .ToString if there is a "." If yes I throw an Exception, if not I convert it to an int.
Does exist to make short code which i can replace if() argument for example:
int x = 1; // x can be 1,2,3 etc.
if(x==1 || x==3 || x==12)
{
//do something..
}
I don't want to repeat x==1, x==3, etc. just compare numbers to x.
You can have the possible numbers in an array and then compare it like:
int x = 1;
int[] compareArray = new[] { 1, 3, 12, 33 };
if (compareArray.Contains(x))
{
//condition met
}
Or you can use Enumerable.Any like:
if (compareArray.Any(r=> r == x))
You can do it fairly succinctly with a switch statement:
int x= 1;
switch (x)
{
case 1:
case 2:
case 3:
case 4:
Console.WriteLine("x is either 1, 2, 3, or 4");
break
default:
Console.WriteLine("x is not 1, 2, 3, or 4");
break;
}
Late to the party, and I would definitely, definitely suggest that one use a simple solution such as Habib's answer (and even simplifying it with extension methods). That said, I was curious if it were possible to achieve a minimal syntax along the lines of what Tagon may have been looking for. That is, would it be possible to have something like:
int x = 1;
if(x == 1 || 3 || 12 || 33)
{
}
I suspect there is unneeded verbosity with some of the operators I used here (and certainly some best-practices violations), but something like this is possible with operator overloads. The resulting syntax is:
IntComparer x = 1; //notice the usage of IntComparer instead of int
if(x == 1 || 3 || 12 || 33)
{
}
First I have a kind of "entry point" into the comparison:
public class IntComparer
{
public int Value { get; private set; }
public IntComparer(int value)
{
this.Value = value;
}
public static implicit operator IntComparer(int value)
{
return new IntComparer(value);
}
public static BoolComparer operator ==(IntComparer comparer, int value)
{
return new BoolComparer(comparer.Value, comparer.Value == value);
}
public static BoolComparer operator !=(IntComparer comparer, int value)
{
return new BoolComparer(comparer.Value, comparer.Value != value);
}
}
This satisfies the initial x == 1 check. From here on, it switches to a new type BoolComparer:
public class BoolComparer
{
public int Value { get; private set; }
public bool IsSatisfied { get; private set; }
public BoolComparer(int value, bool isSatisfied)
{
this.Value = value;
this.IsSatisfied = isSatisfied;
}
public static bool operator true(BoolComparer comparer)
{
return comparer.IsSatisfied;
}
public static bool operator false(BoolComparer comparer)
{
return !comparer.IsSatisfied;
}
public static implicit operator bool(BoolComparer comparer)
{
return comparer.IsSatisfied;
}
public static BoolComparer operator |(BoolComparer comparer, BoolComparer value)
{
return new BoolComparer(comparer.Value, comparer.Value == value.Value);
}
public static implicit operator BoolComparer(int value)
{
return new BoolComparer(value, false);
}
}
This satisfies the subsequent || 3 || 12 || 33 checks and the final true/false evaluation for the if statement.
These two classes working in conjunction makes the syntax tomfoolery work. It's terrible. Do not use it. Also, it doesn't work for for the negative: if (x != 1 || 3 || 12 || 33). That might be a simple fix, but I don't want to dive into that at the moment)
Some working checks:
IntComparer x = 1;
bool check1 = x == 1 || 3 || 12 || 33; //true
bool check2 = x == 2 || 3 || 12 || 33; //false
bool check3 = x == 5 || 1 || Int32.MaxValue; //true
bool check4 = x == -1; //false