/* Configuration */
var QUESTION_ID = 169724; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 81420; // This should be the user ID of the challenge author.
/* App */
var answers = [],
answers_hash, answer_ids, answer_page = 1,
more_answers = true,
comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function(data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function(data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if (OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
//else console.log(body);
});
valid.sort(function(a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function(a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
lang = jQuery('<a>' + lang + '</a>').text();
languages[lang] = languages[lang] || {
lang: a.language,
lang_raw: lang,
user: a.user,
size: a.size,
link: a.link
};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function(a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i) {
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
body {
text-align: left !important;
display: block !important;
}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 500px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr>
<td>Language</td>
<td>User</td>
<td>Score</td>
</tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr>
<td></td>
<td>Author</td>
<td>Language</td>
<td>Size</td>
</tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr>
<td>{{PLACE}}</td>
<td>{{NAME}}</td>
<td>{{LANGUAGE}}</td>
<td>{{SIZE}}</td>
<td><a href="{{LINK}}">Link</a></td>
</tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr>
<td>{{LANGUAGE}}</td>
<td>{{NAME}}</td>
<td>{{SIZE}}</td>
<td><a href="{{LINK}}">Link</a></td>
</tr>
</tbody>
</table>
666 => False
debería ser un caso de prueba.Respuestas:
Conjunto Z80 (8 bits), 2 bytes
El siguiente código solo funciona con valores de hasta 255:
Versión de 16 bits (funciona en todos los casos de prueba), 3 bytes
Esto funciona con valores de hasta 65535.
Si te sientes aventurero, puedes reducir 1 byte almacenando la entrada
A
yC
asíy luego corriendo
Sin embargo, esto pone la carga sobre la persona que llama, por lo que puede ser que los dos bytes (
push BC
ypop AF
) también se cuenten.fuente
or
son bit a bit con 2 operandosor
mnemónica es el acumulador A. En este caso, el comando no cambia A. Solo actualiza el registro de estado (y en particular, el indicador de paridad) a reflejar el contenido de A.P
permitido según codegolf.meta.stackexchange.com/a/8509/29560 ? Es un solo bit dentro delF
registro (flags) que tiene solo tres pares de instrucciones afectadas por él. Además, esta respuesta no menciona que solo compite por valores de 8 bits, ya queA
es un registro de 8 bits. Esto significa que no puede dar una respuesta777
o cualquier otro valor sin signo superior a 255.:P
A
está emparejadoF
, por lo que no aceptaríaAB
oBA
como un valor de 16 bits.BC
es de 16 bits, pero luego necesita una instrucción adicional para cargar uno de ellosA
antes de XORear el otro. Siempre he mencionado que mis respuestas Z80 funcionan completamente hasta 255 o 65535, dependiendo de la pregunta. ¿Quizás agregar una versión de 16 bits también? Entonces 2 bytes para valores de 8 bits, 3 bytes para valores de 16 bits.JavaScript (ES6), 18 bytes
Pruébalo en línea!
Explicación
La lógica bit a bit es así:
~-n
es equivalente a-(-n)-1
, por lo que solo es otra forma de hacerlon-1
. En ese caso particular, podríamos haberlo usadon-1
.n & (n-1)
elimina el bit menos significativo establecido en 1 en n porque la disminución de n convierte todos los 0 finales en 1 y borra el 1 que sigue inmediatamente (por propagación de acarreo), mientras deja todo lo demás sin cambios.Ejemplo para n = 24 (11000 en binario):
Por lo tanto, procesamos tantas llamadas recursivas como haya 1 en la representación binaria de n , invirtiendo el resultado cada vez con
!
. La última llamada siempre devuelve 1 .Ejemplos:
fuente
Python 2 , 25 bytes
Pruébalo en línea!
bin(n)
da un resultado como'0b10101'
. Al leer esto como un entero de base 13, obtenemosque reduce el módulo 2 a ≡ 1 ⋅ 1 5 + 1 ⋅ 1 4 + 0 ⋅ 1 3 + 1 ⋅ 1 2 + 0 ⋅ 1 1 + 1 ⋅ 1
Entonces
int(bin(n),13)%2
es igual a 1 + (número de unidades enbin(n)
) módulo 2.Si
n
es malo, entonces el resultado es 1; de lo contrario es 0.Aprendí este truco de Noodle9 .
fuente
lambda n:int(`n`,13)%2
. Pruébalo en línea!Japt
-h!
,543 bytesIntentalo
Explicación
fuente
¤¬x v
Esta es la respuesta de KevinC # (compilador interactivo de Visual C #) ,
4338 bytesGolfed Pruébelo en línea!
Sin golf
Código completo con pruebas
Lanzamientos
-5 bytes
- ReemplazadoCount
porSum
43 bytes
- Solución inicial.Notas
fuente
Bash (sin utilidades externas),
5644 byteswhile(($1));do set $(($1/2)) $(($2+$1%2));done;!(($2%2))
Esto supone que el número se encuentra en
$1
, después de haber sido pasado como el primer argumento de línea de comando. También supone que este es un script de shell (para que pueda hacerloexec
).Recurre, de una manera, usando
exec $0
, hasta que el número (in$1
) llegue a cero, dividiéndolo por dos en cada iteración. También suma (in$2
) la cantidad de veces que obtenemos un número que es impar. Al final, el número original era "malvado" si la suma$2
no es impar.Invocaciones de ejemplo:
Para
0
:Resultado correcto, con un poco de extra en el lateral.
fuente
R ,
3726 bytesPruébalo en línea!
Una alternativa a la respuesta de Robert S. , evita la división de bits incorporada
pero termina siendo menos golfosay gracias a JayCe y digEmAll termina siendo un poco más golfista.Solo funciona para enteros positivos menores que231- 1 .
fuente
%/%
and%%
operators so it would be a moot point.05AB1E, 4 bytes
Try it online or verify all test cases.
Explanation:
fuente
Stax, 4 bytes
Run and debug it
fuente
R,
9998443428 bytes-1 thanks to Kevin Cruijssen! -54 thanks to ngm! -10 thanks to Giuseppe! -6 thanks to JayCe!
Try it online!
Alternatively, using the
binaryLogic
package (39 bytes):fuente
==0
can be<1
:)C (gcc), 36 bytes
Try it online!
Method from K&R https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
Must be compiled with optimization level 0
fuente
error: expected constructor, destructor, or type conversion before '(' token
(arrow is pointing at thef
in the function name). What compiler flag(s) do I need?-O
.-O0
compiler flag.Wolfram Language (Mathematica),
2422 bytesTry it online!
fuente
2∣
is an improvement onEvenQ
. Try it online!PHP,
3736 bytesTo run it:
Or Try it online!
Prints
1
for true, and0
for false.-1 byte thanks to Benoit Esnard!
fuente
<?=1&~substr_count(decbin($argn),1);
. This one also prints 0 for false.Brachylog, 4 bytes
Try it online!
With multiple test cases (😈 is evil and 👼 is not.)
Uses something I discovered recently about the
-
predicate: its documentation just says "the difference of elements of [input]", but what it actually does is "sum of even-indexed elements (starting from 0th) of input, minus the sum of odd-indexed elements of input".Here,
ḃ
converts the number into an array of binary digits,o
sorts them to bring all the 1s together.Now, if there were an even number of 1s, there would be an equal number of 1s in even indices and odd indices. So the
-
after that would give a 0. But if there were an odd number of 1s, there would be an extra 1 sticking out, resulting in the difference being either -1 or 1.So, finally, we assert that the difference is
0
, and get a true or false result according to that. With more flexible output requirements, this could be removed for a 3 byte answer, with 0 as truthy output and -1 and 1 as both falsey outputs.fuente
INTERCAL,
906563 bytesTry it online!
Ungolfed and expanded (for what it's worth) with C style comments.
I had to make a few concessions to make this feasible in INTERCAL. The first is, as with all INTERCAL programs, numerical input must be written out. So if you want to input
707
you would provideSEVEN OH SEVEN
.The second is that INTERCAL doesn't really have proper truthy or falsy value. Instead, it will output the Roman Numeral
I
(1) if the number is not evil, or a 0 (typically represented as-
since Roman Numerals can't normally represent 0).If you want to flip those so that evil numbers return 1 and non-evil numbers return 0, you can change lines 4 and 5 from the ungolfed version as follows, although it does add 3 bytes.
fuente
Attache,
1312 bytesTry it online!
(Old 13 bytes:
Even@1&`~@Bin
)This is a composition of three functions:
Bin
Sum
Even
This checks that the
Sum
of theBin
ary expansion of the input isEven
.fuente
dc,
1816 bytesReturns (to the stack) 0 for evil and 1 for not evil
Try it online!
Fairly straightforward - recursively applies the combined quotient/remainder operator
~
to the new quotient and adds all the remainders together, then mods by 2(after spending two bytes to flip to a standard truthy/falsy).Edited to reflect consensus that 0 for truthy and 1 for falsy is okay, especially in a language that has no sort of
if(boolean)
construct.fuente
Python 2, 29 bytes
Try it online!
Returns 1 if True, else 0.
Converts the number to a binary string like '0b11', counts the number of 1s, gets the complement of result, and returns the last bit of the complement (thanks, https://codegolf.stackexchange.com/users/53560/cdlane!) (1 if the original number was even, 0 if it was odd).
fuente
lambda n:~bin(n).count('1')&1
replaces the modular division with something potentially less expensive.x86-16, 3 bytes
NASM listing:
16-bit integer function arg in AX (which is destroyed), return value in PF.
The hardware calculates the parity of the result for us, in x86's Parity Flag. The caller can use
jp
/jnp
to branch, or whatever they like.Works exactly like @cschultz's Z80 / 8080 answer; in fact 8086 was designed to make mechanical source-porting from 8080 easy.
Note that PF is only set from the low byte of wider results, so
test edi,edi
wouldn't work for an x86-64 version. You'd have to horizontal-xor down to 16 bits, orpopcnt eax, edi
/and al,1
(where 0 is truthy).fuente
C++ (gcc) (-O0),
3631 bytesTry it online!
C++ (clang), 35 bytes
Try it online!
Here is my first attempt at code golfing, hope I didn't break any rule I might have missed.
Edit:
- Saved 5 bytes thanks to @Jonathan Frech : replaced
!=
by-
andreturn
byi=
(the last replacement does not seem to work with clang though)- Since there seems to be a debate whether I should use gcc -O0 abuse, I thought I could just give both versions
fuente
!=
to-
and another four by golfingreturn
toi=
.gcc -O0
hack? It's not like the length of a language's total boilerplate matters much when comparing implementations. Also, it makes it more interesting to choose betweenreturn
vs. call-by-reference (updating*i
in place). I'd rather write C or C++ answers, not un-optimized-gcc-only answers, because un-optimized-gcc isn't a very useful language.SML, 32 Bytes
Explaination:
%
is function namen
is input, returns (n + %(n//2)) % 2Made by 2 bored Carnegie Mellon Students
fuente
Forth (gforth), 53 bytes
Try it online!
Explanation
Takes the xor-sum of the digits of the binary form of the number. (repeatedly divides by 2 and xors the remainder with the "sum" value)
Code Explanation
fuente
Java 8,
4036 bytes-4 bytes thanks to @Okx for something I shouldn't have forgotten myself..
Try it online.
Explanation:
Note that the character encoding for
0
and1
are48
and49
, but summing them and taking modulo-2 still holds the correct results because48%2 = 0
and49%2 = 1
.fuente
n.toString(n,2)
saves 4 bytes.~n.toString(n,2).chars().sum()%2
to save one byte.0
and1
aren't truthy/falsey in Java, onlybooleans
/Booleans
are. If a challenge would state two distinct outputs are allowed the<1
could have been removed to save 2 bytes indeed. :)Perl 6, 21 bytes
Test it
Expanded:
fuente
*.base(2)%9%%2
{:3(.base(2))%%2}
Retina 0.8.2, 28 bytes
Try it online! Link includes test cases. Explanation:
Convert to unary.
Partial binary conversion (leaves extra zeroes).
Delete all the zeros.
Modulo the ones by two.
Test whether the result is zero.
fuente
x86 Assembly,
1211 bytes-1 byte thanks to @ceilingcat's suggestion
fuente
inc eax
instead ofnot eax
. Also may want to mention that this requires a processor with support for thepopcnt
instruction.Bash + GNU utilities, 33
Try it online!
Reads input from STDIN. Outputs 1 for True and 0 for False.
dc
converts input to a binary stringtr
removes zeroswc
counts remaining ones (and trailing newline, which corrects sense of logicdc
calculates count mod 2 and outputs the answerfuente
Python 2,
2827 bytesTry it online!
Returns a truthy value if exactly one of
the ones-bit is a 1
andthe result of calling this function on n/2 is truthy
is true (orn==0
). It works becausen/2
is equivalent to a right bitshift with floor division (so Python 2 only).Alternate version, also
2827 bytesTry it online!
Based on the K&R method of counting set bits referenced by vazt.
Both of these could be two bytes shorter if the output allowed falsey to mean evil.
Edit: Thanks to Amphibological for saving a byte!
fuente
1
and theor
to save +1 byte. Nice solution!APL (Dyalog Unicode), 10 bytesSBCS
Anonymous tacit function. Can take any array of integers as argument.
Try it online!
2∘⊥⍣¯1
convert to binary, using as many digits as needed by the largest number, separate digits along primary axis1⍪
prepend ones along the primary axis≠⌿
XOR reduction along the primary axisfuente
J, 9 bytes
Anonymous tacit function. Can take any integer array as argument.
Try it online!
1-
one minus (i.e. logical negation of)2|
the mod-2 of1#.
the sum (lit. the base-1 evaluation) of#:
the binary representationfuente
2|1+1#.#: