0
[Challenge] [PL,java,Py,RB,js] Shorten this code !
[Perl] This code has 34 char, can you shorten it under 34 char? AUTOLOAD { $p=@{$_[0]}; $p == 3 ? 0 : $p % 2 } Detail : @_ is array, and check the size. [Java] int f(int[] p) { return p.length!=3?p.length%2:0; } [Ruby] def f p y=p.size y==3?0:y%2 end [Python] def f(p): x=len(p) return 0 if x==3 else x%2 [JS] f=p=>p.length==3?0:p.length%2;
5 ответов
0
I can shorten your Python version, a little bit:
[Python]
def f(p):
x=len(p)
return x%2
- (x==3)
I'm new to Perl! Does this work? If so, it's shorter.
AUTOLOAD {
$p == 3 ? 0 : @{$_[0]} % 2
}
0
how this can be work? (x!=3) * x%2
0
Apologies, my python code had a bug. It should have been x%2 - (x==3)
Explanation:
The result is always length % 2 (odd numbered lengths return 1, even numbered lengths, 0), except for when length is 3, which should give 0, instead of the usual 1.
(x==3) either equates to 0 or 1. 1 for when x is equal to 3, and 0 at any other time.
x%2 - (x==3)
Table of evaluated expressions to explain:
x, x%2, (x==3), x%2 - (x==3)
0, 0, 0, 0
1, 1, 0, 1
2, 0, 0, 0
3, 1, 1, 0
4, 0, 0, 0
5, 1, 0, 1
6, 0, 0, 0
7, 1, 0, 1
8, 0, 0, 0
9, 1, 0, 1
0
(x!=3) * x%2 also can be work in my testcase :D
- 1
bump this post