I was asking myself if its was possible to do something like that :
condition ? do this && THIS : else;
like :
nb = (nb1 + nb2) > 9 ? (nb1 + nb2) % 10 && nb1 + 1 : 0;
Note this is just an example, it means nothing.
There is a simple way:
condition ? function_that_does_several_things() : else_expr;
The other thing is you can collect expressions in a list:
int a = (1,2);
assigns 2 to a. So you can try this:
condition ? (do_this, and_this) : else_expr;
But I suggest against it; it's really hard to see what is going on here and a lot of people will be confused, surprise and frustrated when they see such code.
It's not "do this", it's "evaluate this". Remove the condition and the "false" path, and you get this:
nb = (nb1 + nb2) % 10 && nb1 + 1;
So, yes, you can do it, but the value of nb will be the result of a logical expression ... which is essentially this:
nb = ((nb1 + nb2) % 10 != 0) && (nb1 + 1 != 0);
Related
I am trying to sort a list of entrants depending on their scores. If the score are the same, I then want to sort them on another value.
So far I have
setSortedEntrants(props.event.entrants.sort((a, b) => (a.score < b.score) ? -1 : 1));
which sorts the entrants on their current score. I want to add to this, so that if the scores match, I then want to sort those on another value a.scoreCard.back9Score vs b.scoreCard.back9Score
I have tried this but doest seem to be quite right
setSortedEntrants(props.event.entrants.sort((a, b) => (a.score < b.score) ? -1 : a.score === b.score ? a.scoreCard.back9Score < b.scoreCard.back9Score: -1 ? a.score > b.score : 1));
logic being,
1- if a.score is less than b.score, move up one
2 - if a.score equals b.score then if a.scoreCard.back9Score is less than b.scoreCard.back9Score then move up one.
3 - otherwise if a.score > b.score move down one.
all values for score and scoreCardback9Score and numbers
Is there somewhere obvious I am going wrong.
the condition should be as follows. You put the right code indentation, then you can figure out the matching clauses of ternary operator.
setSortedEntrants(props.event.entrants.sort((a, b) =>
(a.score < b.score) ?
-1
: (a.score === b.score ?
(a.scoreCard.back9Score < b.scoreCard.back9Score ?
-1
: 1)
: 1)
);
I am trying to create password Generate in ruby. At the moment all is working just got stuck at the final piece of generating the password.
I asked user if he/she would like the password to include numbers, lowercase or uppercase.
If YES, user will enter 1 and 0 for NO.
I used the code below to generate password if everything is 1. Meaning user want to include numbers, lowercase and uppercase.
if numbers == 1 && lowercase == 1 && uppercase == 1
passGen = [(0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a].flatten.sample(10)
end
p passGen
This works 90% of the time. 10% of the time the generated password will not include say any numbers. But everything else present. I am not sure if this is because of the size or length of Array from which the password is sampled.
Anyway lets go to the main problem below
Here is the problem, I am struggling to write the code to generate password if one or more of input is 0. That's if user don't want to include numbers. Or no numbers and uppercase etc . As I can't predict what user may want or not want. I need help on this please.
Thank you.
You will need to make your input array more dynamic:
passGen = []
passGen += (0..9).to_a if numbers == 1
passGen += ('A'..'Z').to_a if uppercase == 1
passGen += ('a'..'z').to_a if lowercase == 1
passGen.sample(10).join
Now, to tackle your other issue with missing characters - this is caused as you are simply taking 10 random characters from an array. So it can just take, for example, all digits.
To tackle this you need to get one character from each generator first and then generate the remaining characters randomly and shuffle the result:
def generators(numbers:, lowercase:, uppercase:)
[
(0..9 if numbers),
('A'..'Z' if uppercase),
('a'..'z' if lowercase)
].compact.map(&:to_a)
end
def generate_password(generators:, length:, min_per_generator: 1)
chars = generators.flat_map {|g| Array.new(min_per_generator) { g.sample }}
chars += Array.new(length - chars.length) { generators.sample.sample }
chars.shuffle.join
end
gens = generators(numbers: numbers == 1, uppercase == 1, lowercase: lowercase == 1)
Array.new(10) { generate_password(generators: gens, length: 10) }
The code doesn't know it needs to include a digit/letter from every group. The sample takes random signs and since you a basically sampling 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz there is a possibility that all the signs will not be digits.
The easiest way to fix it is to check if a sign from every group is in the "password" and then replace a random sign with a sign from group that is not present.
If I were to program this I would do it like that
def random_from_range(range)
range.to_a.sample.to_s
end
def passGen(numbers, lowercase, uppercase)
result = ''
possibleSigns = []
if numbers == 1
range = (0..9)
result += random_from_range(range)
possibleSigns += range.to_a
end
if lowercase == 1
range = ('A'..'Z')
result += random_from_range(range)
possibleSigns += range.to_a
end
if uppercase == 1
range = ('a'..'z')
result += random_from_range(range)
possibleSigns += range.to_a
end
desired_lenth = 10
while result.length < desired_lenth
result += possibleSigns.sample.to_s
end
result
end
puts passGen(1,1,1)
By saying (0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a, you're creating an Array of 10 + 26 + 26 = 62 elements, and then you pick only 10 elements out of it.
At your place I'd wrap password generation around an until block:
def generate_password_with_digits_and_caps
[(0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a].flatten.sample(10).join
end
passGen = ''
until passGen.match(/[A-Z]/) && passGen.match(/[a-z]/) && passGen.match(/\d/)
passGen = generate_password_with_digits_and_caps
end
This could also work (closer to your snipppet):
if numbers == 1 && lowercase == 1 && uppercase == 1
passGen = ''
until passGen.match(/[A-Z]/) && passGen.match(/[a-z]/) && passGen.match(/\d/)
passGen = [(0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a].flatten.sample(10).join
end
end
Start with something simple and stupid:
passGen = (('0'..'9').to_a.sample(1)+ ('A'..'Z').to_a.sample(1)+('a'..'z').to_a.sample(8).shuffle).join
Technically speaking, this already fulfills your requirement. From the viewpoint of aesthetics and security, the disadvantage here is that the number of upper case characters is always 8. A more elegant solution would be to find three non-zero integers which add up to 10, and can be used as the arguments for the sample call. Also, if no numbers are requested, you simply pass 0 as argument to sample.
Since this exceeds the scope of your question, and I don't even know whether you want to go so far, I don't elaborate on this here further.
I am stuck at this exercise of c program that have a comma in C for loop if, I replace , with && it works same
for(i = 5, j = i - 1 ; i > 0 , j > 0 ; --i ,j = i - 1)
printf("\n%d",i);
In this loop I get how for( i = 5,j = i - 1 ; ? ; --i ,j= i - 1) but the part where ? is there I don't get how that is working 1,1 = true ? 1,0 = false ? C is trick that's why love it 3> can you explain me how that part is working
but the part where ? is there i don't get how that is working
The comma operator in C evaluates the expression before the comma, and then the expression after the comma, and then returns the value of the expression after the comma. So the value of the expression 1, 0 in C is 0. The result of 1, 1 is 1. The result of foo(x), bar(x) is the value of bar(x).
This doesn't come up very often because in practice, the comma operator isn't used all that often. It can be handy in a few cases, such as in for or while loops where you might want to manipulate more than one variable each time through the loop. But in general, combining expressions with the comma operator just creates uncertainty about how those expressions will be evaluated, what the result of the overall expression is, and so on. Whenever possible, separate the expressions and execute them one at a time.
Why my for loop works with "&&" and not with ","
The && operator combines (using logical AND) the result of both expressions instead of throwing the result of the first expression away, so depending on the expression you can get a different result than you do with ,. 1 ? 0 and 1 ? 1 give the same result for both , and && because the result of the && depends on the second expression in both cases. But 0 ? 0 and 0 ? 1 will give different results — , again returns the value of the second expression, and && returns 0 because both expressions are considered and 0 AND anything is 0.
; i > 0 , j > 0 ;
Formally, the "," is know as the Comma operator:
The comma operator expression has the form
lhs , rhs
where
lhs - any
expression rhs - any expression other than another comma operator (in other words, comma operator's associativity is left-to-right)
First, the left operand, lhs, is evaluated and its result value is discarded. Then, a sequence point takes place, so that all side effects of lhs are complete. Then, the right operand, rhs, is evaluated and its
result is returned by the comma operator as a non-lvalue.
More informally, in ;i > 0 , j > 0; the i > 0 is evaluated and ignored to determined if the loop should or not terminate, and then j > 0 is evaluated and its value is used to determined if the loop should (or not) continue.
I am stuck at this exercise of c program that have a comma in C for
loop if, I replace , with && it works same
In this case it works the same with "," or "&&" because when i = 1 then j = 0 and consequently j > 0 evaluates to false and you exit the loop. When j > 0 evaluates to false i > 0 also evaluates to false, hence the reason why in your case it is the same using i > 0 && j > 0 or i > 0 , j > 0. Nevertheless, i > 0 && j > 0 and i > 0 , j > 0 are not semantically the same.
In your case:
for(i = 5, j = i - 1 ; i > 0 && j > 0 ; --i ,j = i - 1)
actually, you can simplified i > 0 && j > 0 to just i > 0 since whenever j > 0 evaluates to false i > 0 will also evaluate to false since j = i - 1.
I am new to C programming, in fact programming at all, and recently learn the use of macros with regard to preprocessor directives. Although I am getting more familiar with it the following exercise that I got from a textbook stumbles me since I do not get the solution or the general "take-away lesson" from it.
Before I wrote this question here, I tried to execute the code myself by adding some printf() in order to obtain the correct answers but it does not even compile. Now, before I write down the question and code I want to make it explicit that this is a self-learning question and that I do not want to offend people here with a question that many will find trivial. I just want to understand what is going on.
The code is as follows
int x=2, y=3, a=4,b=5;
#define MAX(x, y) x > y x : y
int c,d,e,f;
c = MAX( a, 3 );
d = MAX( y, x );
e = MAX( ++x, 1 );
f = MAX( b, MAX (6, 7) );
I am asked to give the values of c,d,e and f. There is an additional hint that although it is named that way the above macro is NOT the maximum operator. Therefore, I don't think the "obvious" guess of e.g. max(a,3) = 4 is correct. Consequently, I don't know what is going on.
EDIT: I forgot to mention: I know that there are parentheses missing for the correct use. But I am specifically asked to evaluate the terms without them. Therefore I am confused since I do not know exactly how the results change and the function behave without those included.
Expanding the macro as-is, we get the following:
Original Expanded
-------- --------
c = MAX( a, 3 ); c = a>3 a : 3;
d = MAX( y, x ); d = y>x y : x;
e = MAX( ++x, 1 ); e = ++x>1 ++x : 1;
f = MAX( b, MAX (6, 7) ); f = b>MAX (6, 7) b : MAX (6, 7);
f = b>6>7 6 : 7 b : 6>7 6 : 7;
Macro expansion is just dumb text substitution - syntax, scope, precedence, associativity, values, side effects, etc., are simply not taken into account when a macro is expanded (macro expansion occurs before the source code is fed to the compiler proper).
Obviously, none of the expanded expressions above will compile. For that to happen, we need to fix the MAX macro by defining it as
#define MAX( x, y ) x>y ? x : y
Now we get the following:
Original Expanded
-------- --------
c = MAX( a, 3 ); c = a>3 ? a : 3;
d = MAX( y, x ); d = y>x ? y : x;
e = MAX( ++x, 1 ); e = ++x>1 ? ++x : 1;
f = MAX( b, MAX (6, 7) ); f = b>MAX (6, 7) ? b : MAX (6, 7);
f = b>6>7 ? 6 : 7 ? b : 6>7 ? 6 : 7;
Better. The expanded expressions above will compile, but the last two don't do anything like what you expect them to. e won't get the max of x and 1, it will either get x+2 or 1 (? introduces a sequence point, so the behavior isn't undefined). f gets ... something, can't remember the associativity of > and ?: offhand, not really willing to dig it up.
Again, macros don't take precedence and associativity into account when expanding their arguments. Imagine we write a macro CUBE that does the following:
#define CUBE(x) x * x * x
and we call it as
y = CUBE( 2 + 3 );
That expands to
y = 2 + 3 * 2 + 3 * 2 + 3;
which gives us the value 17, when we were probably expecting 125.
The right way to define the MAX macro is
#define MAX( x, y ) ((x) > (y) ? (x) : (y))
We not only parenthesize each argument, we parenthesize the entire expression. This way, precedence and associativity are preserved not only if you pass complex expressions as arguments, but also if you pass this macro as an argument to another one (as in the last example):
Original Expanded
-------- --------
c = MAX( a, 3 ); c = ((a) > (3) ? (a) : (3));
d = MAX( y, x ); d = ((y) > (x) ? (y) : (x));
e = MAX( ++x, 1 ); e = ((++x) > (1) ? (++x) : (1));
f = MAX( b, MAX (6, 7) ); f = ((b) > (MAX (6, 7)) ? (b) : (MAX (6, 7)));
f = ((b) > ((6) > (7) ? (6) : (7)) ? (b) : ((6) > (7) ? (6) : (7)));
This time, f will be evaluated like you expect it to be.
The evaluation of e is still problematic (++x can still be evaluated twice). This is a problem in general with macros that expand their arguments more than once - arguments that have side effects can be evaluated multiple times, which will lead to wrong answers or undefined behavior.
Incorrect use of ternary operator.
#define MAX(x,y) x>y x : y
Should be:
#define MAX(x,y) (x>y) ? x : y
And to allow for more complex expressions:
#define MAX(x,y) (((x)>(y)) ? (x) : (y))
You mention that you don't know what is going on. There is only way - run only the preprocessor.
What compiler are you using? Assuming gcc/clang you can -
gcc -E filename.c
This will only run the preprocessor and let you analyze what is going on.
BTW you code doesn't compile because you made a mistake with the ternary operator - should be x > y ? x : y.
This is the DFA i have drawn-
Is it correct?
I am confused because q4 state has 2 different transitions for same input symbol which violates the rule of DFA, but I can't think of any other solution.
Your DFA is not correct.
your DFA is completely wrong so I don't comment
DFA for RE:
0(1 + 0)*0 + 1(1 + 0)*1
Language Description: if string start with 0 it should end with 0 or if string start with 1 it should end with 1. hence two final states (state-5, state-4).
state-4 : accepts 1(1 + 0)*1
state-5 : accepts 0(1 + 0)*0
state-1 : start state.
DFA:
EDIT :
+ Operator in Regular Expression
(0 + 1)* = (1 + 0)* that is any string consist of 1s and 0s, including Null string ^.
Here + means Union if it appear between two RE: and A U B = B U A (similarly)=> (0 + 1) = (0 + 1) .
meaning of plus + depends on syntax it appears in: If expression is a+ (+ is superscripted) this means one of more as, and If a+b then + means Union operation either a or b.
a+ : { a, aa, aaa, aaa.....} that is any number of a string in language with length > 1.
I think you should start with 0 first
0(1 + 0)*0 + 1(1 + 0)*1