What does ":" do in this exact situation? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# ?: Conditional Operator
Could someone explain me what does ":" do in this situation?
var skupaj = dni + zacetniDan + (((dni + zacetniDan) % 7 != 0) ? 7 - ((dni + zacetniDan) % 7) : 0);

: is part of a Ternary Operator. It is shortcode for an if/else clause.
Example:
int a = b > 5 ? 2 : 3;
is the same as:
int a = 0;
if (b > 5)
{
a = 2;
}
else
{
a = 3;
}

It's a ternary operator.
It is shorthand for the following equivalent of your code:
int skupaj = dni + zacetniDan;
if ((dni + zacetniDan) % 7 != 0) {
skupaj += 7 - ((dni + zacetniDan) % 7);
}
else {
skupaj += 0;
}

? : is conditional operator short form for if / then / else
The first part is condition should be evaluated to boolean its before the ? The expression after ? is then part and is returned when condition is ture and the expression after : is else part and is returned when condition is evaluated to false

(((dni + zacetniDan) % 7 != 0) ? 7 - ((dni + zacetniDan) % 7) : 0);
This is a ternary expression Condition?Expr1:Expr2
The result of the expression is the result of Expr1 if Condition is true and the result of Expr2 otherwise.
In your particular case condition is
((dni + zacetniDan) % 7 != 0)
If this condition is true, the result of the ternary subexpression will be
7 - ((dni + zacetniDan) % 7)
Otherwise 0.

Ternary operator. It allows you to treat a conditional value as a single value.
here's a rudimentary example converting a boolean to a string
string str = myBool ? "true" : "false";
which is equivalent to
string str
if(myBool)
str = "true";
else
str = "false";

Thats the ternary operator: http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx
if (dni + zacetniDan) % 7 != 0) is true then evaluate to 7 - ((dni + zacetniDan) % 7) else evaluate to 0

You can easily understand a line with ? and : by splitting in 3.
The term on the left of ? is the condition
The term between ? and : is what should be used if the condition is true
The term after : is what should be used if the condition is false

Related

VB to C# conversion error (assign and if statements)

what is the proper way to convert
if((year mod 4=0 and year mod 100<>0) or (year mod 400=0), “Leap Year”, “Not a Leap Year”)
To C#
I was able to successfully convert the first part if ((year % 4 == 0 & year % 100 != 0) | (year % 400 == 0)) but when I add the messages, I get an error.
Any help would be greatly appreciated.
The equivalent of that VB If operator is the C# ternary operator (?:), i.e.
If(x, y, z)
is equivalent to:
x ? y : z;
For the record, there's another If operator like this:
If(x, y)
which evaluates to x if x is not null, otherwise it evaluates to y. The C# equivalent is called the null coalescing operator (??):
x ?? y;
The original VB code should have used the DateTime.IsLeapYear(Int32) Method, so that in C# it would become:
DateTime.IsLeapYear(year) ? "Leap Year" : "Not a Leap Year";
The answer in compilable code is:
private string LeapYearResponse(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return "Leap Year";
else
return "Not a Leap Year";
}
Or more concisely:
private string LeapYearResponse(int year)
{
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) ? "Leap Year" : "Not a Leap Year";
}

Single line If condition without else clause [duplicate]

This question already has answers here:
? operator without else-part
(3 answers)
Closed 3 years ago.
How can we write a single line If condition without else in the operator?
Example:
If(count==0) { count=2; }
How can we write above like below:
count=count==0?2;
As ternary operator requires if else condition. I want to do it without the ternery operator. Is there any operator available in C#?
Thanks.
You do not need to pair else with if; you can use it on its own:
if (count == 0)
count = 2;
This can be written in multiple ways if the syntax isn't to your liking:
if (count == 0) count = 2;
if (count == 0) { count = 2; }
if (count == 0) {
count = 2;
}
if (count == 0)
{
count = 2;
}
As another poster points out, you can use nullable int with initialization to null to have a binary interaction with the null coalescing operator:
int? count = null; // initialization
// ... later
count = count ?? 2;
count = count == 0 ? 2 : count;
Or for more fun:
using System;
public class Program
{
public static void Main()
{
foreach(int x in System.Linq.Enumerable.Range(-5, 10))
{
int count = x;
bool y = count == 0 && (0 == count++ - count++);
Console.WriteLine(count);
}
}
}

What is = i < 10 ? "0" + Convert.ToString(i) : Convert.ToString(i) - C# [duplicate]

This question already has answers here:
Benefits of using the conditional ?: (ternary) operator
(17 answers)
Closed 4 years ago.
Never seen something like this before. Specifically line 4.
Currently I understand:
days array at position i-1 gets the value...
I don't know anything beyond the = sign excluding the concatenation from the +.
public String[] months() {
String[] days = new String[12];
for (int i = 1; i <= 12; i++) {
days[i - 1] = i < 10 ? "0" + Convert.ToString(i) : Convert.ToString(i);
}
return days;
}
Also why are there 2 converts?
Looking further into the other code I think the developer copied and pasted previous code. Days array should be months probably, as there are 12 months.
Solved
Thanks, never seen ternary operators before. Thanks!
public String[] months() {
String[] months = new String[12];
for (int i = 1; i <= 12; i++) {
/* faster way of saying */
/* if i < 10 {} else {} */
/* if condition is met do everything before the :, else do everything after */
/* checks for 10 because months can be 1 or 2 digits, 0-9, then 10-12 */
/* single digits concatenated to the 0 */
/* double digits replace the 0 */
months[i - 1] = i < 10 ? "0" + Convert.ToString(i) : Convert.ToString(i);
}
return months;
}
This is the conditional operator, also known as the ternary conditional operator.
It's shorthand for...
if (i < 10)
{
days[i - 1] = "0" + Convert.ToString(i);
}
else
{
days[i - 1] = Convert.ToString(i);
}
The code is basically prepending a "0" to the front of single digit numbers.
It's the ternary operator. If the expression in front of the ? sign is true, the result will be the value after the ? sign, otherwise the value after the colon.
This code adds a leading zero to the value. If the value is less than 10, the value becomes "0" + the value, so 9 becomes "09" etc.
?: is shorthand
IF i < 10
days[i-1] = "O" + Convert.ToString(i)
ELSE
days[i-1] = Convert.ToString(i)

string.Format("{0:n0}") in javascript [duplicate]

This question already has answers here:
Format numbers in JavaScript similar to C#
(17 answers)
Closed 9 years ago.
I'm trying to find an equivalent function to:
string.Format("{0:n0}")
in javascript.
Or in different words, I have a long number 10898502 and i want to display it like this 10,898,502.
Is there an easy way to do it ?
Thanks,
For a pure Javascript solution, I would recommend the function below. It is courtesy of this SO Community Wiki entry: How can I format numbers as money in JavaScript?
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
console.log(
(1000000.94).formatMoney(1, '.', ',') // 1,000,000.9
);

shunting yard algorithm with trigonometric functions

I am working on implementing shunting yard algorithm in C#. Although it parses mathematical expressions with symbols( + , * - / and ^) pretty well.But for some reason it is not working for sine cosine functions . Like for example if I try to calculate sin(45) I get 0.707106 .
But when I try to parse expression like
sin(25)+cos(15+sin(25))+3 it gives me 0.43756 (Correct answer is: 2.19106879911)
sin(45)+cos(45) it gives me 0.715779 (Correct answer is: 1.414)
I have followed all the steps that are mentioned in this article at Wikipedia . I have trying this for a few days now but I am unable to make it work perfectly. Here is the main parsing function
private void parse()
{
//scan the input string
for (int j = 0; j < input.Length; j++)
{
if (Char.IsDigit(input[j])) //if its a number
{
string number = extractNumber(input, j); //extracts multiple digit number
j = currentposition; //increment the counter according to length of the digit
postfix += number + " ";
Console.WriteLine(postfix);
}
//if its a function character
else if(Char.IsLetter(input[j]) )
{
//its a letter
string function = getFunction(j); //get the function name
operators.Push( function );
j = currentposition;
}
else if(input[j] == ',') //if its a comma
{
while(operators.Peek() != "(")
{
postfix += input[j] + " ";
}
}
else if (IsAnOperator(input[j])) // if we have got an operator
{
if (operators.Count != 0 && IsHigherPrecedence(operators.Peek().ToCharArray()[0], input[j]))
{
while ( ( operators.Count != 0 && IsHigherPrecedence(operators.Peek().ToCharArray()[0], input[j]) ) )
{
postfix += operators.Pop() + " ";
}
}
operators.Push(Char.ToString(input[j]));
}
else if (input[j] == '(')
operators.Push(Char.ToString(input[j]));
else if (input[j] == ')')
{
while (operators.Count != 0 && operators.Peek() != "(")
postfix += operators.Pop() + " ";
operators.Pop();
}
} // end for loop
while(operators.Count > 0 )
postfix +=operators.Pop() + " ";
//Conversion Logic (postfix to final answer )
postfixtokens.AddRange( postfix.Split(' ') ) ;
for (int j = 0; j < postfixtokens.Count-1; j++)
{
if (IsAnOperator(postfixtokens[j][0]) && basket.Count > 1)
{
Double second = Double.Parse( basket.Pop() );
Double first = Double.Parse(basket.Pop() );
char op = postfixtokens[j][0];
Double result = ApplyOperation(op,second, first);
// Console.WriteLine("{0} {1} {2} = {3}", first, op, second, result);
basket.Push( result.ToString());
}
else if (IsAnOperator(postfixtokens[j][0]) && basket.Count == 1)
{
Double second = Double.Parse(basket.Pop());
Double first = 0.0;
char op = postfixtokens[j][0];
Double result = ApplyOperation(op, second, first);
// Console.WriteLine("{0} {1} {2} = {3}", first, op, second, result);
basket.Push(result.ToString() );
}
else if (Char.IsDigit(postfixtokens[j][0]))
{
basket.Push( postfixtokens[j] );
}
else if( isAFunction(postfixtokens[j]) )
{
//if its a single argument function
if (AllowedFunctions[postfixtokens[j]] == 1)
{
//single arg logic
if (postfixtokens[j] == "sin")
{
Double result = Math.Sin( Double.Parse(basket.Pop() )*Math.PI/180.0 );
//result = Math.PI / 180;
basket.Push(result.ToString());
}
else if (postfixtokens[j] == "cos")
{
Double result = Math.Cos( Double.Parse(basket.Pop() )*Math.PI/180.0 );
//result = Math.PI / 180;
basket.Push(result.ToString());
}
}
}
}
}
Moreover,
Here is the output of the program:
Input: 3+4*2/(1-5)^5^10
PostFix: 3 4 2 * 1 5 - 5 10 ^ ^ / +
Answer: 3
Input: 2+4
PostFix: 2 4 +
Answer: 6
Input Expression: -5-4
Input: -5-4
PostFix: 5 - 4 -
Answer: -9
Input: -4+3
PostFix: 4 - 3 +
Answer: -1
Input Expression: 4^(4^4)
Input: 4^(4^4)
PostFix: 4 4 4 ^ ^
Answer: 1.34078079299426E+154
Input: sin45
PostFix: 45 sin
Answer: 0.707106781186547 (correct)
//the faulty ones
Input: sin(25)+cos(15+sin(25))+3
PostFix: 25 15 25 sin + 3 + cos + sin
Answer: 0.437567038002202
Input: sin(45)+cos(45)
PostFix: 45 45 cos + sin
Answer: 0.71577935734684
New Cases:
Input: sin45+cos45
PostFix: 45 45 cos + sin
Answer: 0.71577935734684
Input: 2+sin30
PostFix: 2 30 sin +
Answer:2.5
Input: sin30+2
PostFix: 30 2 + sin
Answer: 0.529919264233205
Thats all.Can anybody point me what I am doing wrong.
Edit:
Here is the IsHigherPrecedance function and precedance enum
:
public enum Precedance { Plus =1,Minus=1,Multiply=2,Divide=2,Exponent=3,Unary = 4,Parenthesis=5 };
private bool IsHigherPrecedence(char a, char b)
{
Precedance f = getPrecedance(a);
Precedance s = getPrecedance(b);
if (f >= s)
return false;
else
return true;
}
public Precedance getPrecedance(char a)
{
if (a == '+')
return Precedance.Plus;
else if (a == '-')
return Precedance.Minus;
else if (a == '*')
return Precedance.Multiply;
else if (a == '/')
return Precedance.Divide;
else if (a == '^')
return Precedance.Exponent;
else if (Char.IsLetter(a))
return Precedance.Unary;
else if (a == '(' || a == ')')
return Precedance.Parenthesis;
else
return Precedance.Plus;
}
Now that these trigonometric function are single argument function, are they going to be parsed with some other logic or does this shunting yard algo works with such functions as well as well?
Regards.
There are a copule of problems here, but the primary one is that you are treating functions as operators, though they are not (intrinsic to this is that you call your stack "operators" as though that is the only thing that can be on it, not true). In particular, this branch:
else if (IsAnOperator(input[j])) // if we have got an operator
{
if (operators.Count != 0 && IsHigherPrecedence(operators.Peek().ToCharArray()[0], input[j]))
{
while ( ( operators.Count != 0 && IsHigherPrecedence(operators.Peek().ToCharArray()[0], input[j]) ) )
{
postfix += operators.Pop() + " ";
}
}
operators.Push(Char.ToString(input[j]));
}
needs to check to see if what's on the "operators" stack is actually an operator:
else if (IsAnOperator(input[j])) // if we have got an operator
{
while (operators.Count != 0
&& IsAnOperator(operators.Peek().ToCharArray()[0])
&& IsHigherPrecedence(operators.Peek().ToCharArray()[0], input[j]))
{
postfix += operators.Pop() + " ";
}
operators.Push(Char.ToString(input[j]));
}
Other issues include the branch that handles commas:
else if (input[j] == ',') //if its a comma
{
while (operators.Peek() != "(")
{
// this isnt right, but its not the problem
postfix += input[j] + " ";
// should be this:
postfix += operators.Pop() + " ";
}
}
If you use this library: https://github.com/leblancmeneses/NPEG
you could use this grammar to parse your expression.
Digit: (?<Digit>[0-9]+('.'[0-9]+)?);
(?<Trig>): 'sin(' Expr ')' / 'cos(' Expr ')';
Value: Digit / Trig / '(' Expr ')';
(?<Product>): Value ((?<Symbol>'*' / '/') Value)*;
(?<Sum>): Product ((?<Symbol>'+' / '-') Product)*;
(?<Expr>): Sum ;
Test it out here:
http://www.robusthaven.com/blog/parsing-expression-grammar/npeg-language-workbench
cos(25)+cos(15+sin(25.333))+3
((((12/3)+5-2*(81/9))+1))
nuget:
Install-Package NPEG
to see a sample evaluation of the AST for boolean algebra.

Categories

Resources