28
loading...
This website collects cookies to deliver better user experience
const isEven = n => 'x'.repeat(n).replace(/xx/g, '') === '';`
<small id="shcb-language-1"><span>Code language:</span> <span>JavaScript</span> <span>(</span><span>javascript</span><span>)</span></small>
function isEven(number) {
if (0 == number) {
return true;
} else if (number < 0) { //I actually don't remember if JS has an absolute value function,
return !isEven(number+1); // so this is how we handle negative numbers
} else {
return !isEven(number-1);
}
}
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
char isEvenFile() {
while (access("/tmp/isEven", F_OK)) ;
//We have to wait until the other process created the file
FILE *comms = fopen("/tmp/isEven", "r");
int c = EOF;
while (c == EOF)
c = fgetc(comms);
//In case we were so fast that the other process didn't write to the file
for (;;) {
int newC = fgetc(comms);
if (newC != ' ')
//the number has been sent
c = newC;
else {
FILE *out = fopen("/tmp/out", "w+");
switch (c) {
case '0': case '2': case '4': case '6': case '8':
fprintf(out, "b");
break;
default:
fprintf(out, "a");
//printing a null char would be the end of the string.
break;
}
fflush(out);
break;
}
}
fclose(comms);
exit(0);
}
char isEven(int n) {
char input[10];
sprintf(input, "%d", n);
int pid = fork();
if (pid == -1)
return 2; //error
if (pid == 0) {
isEvenFile();
}
else {
FILE *comms = fopen("/tmp/isEven", "w+");
fprintf(comms, "%d ", n);
fflush(comms);
//send the number to stdin of the child
while (access("/tmp/out", F_OK | R_OK)) ;
FILE *out = fopen("/tmp/out", "r");
int result = EOF;
while (result == EOF)
result = fgetc(out);
//Again, we have to wait until the other process is done
result = result == 'b';
fclose(comms);
fclose(out);
remove("/tmp/isEven");
remove("/tmp/out");
return (char) result;
}
}
28