7
\$\begingroup\$

Your task is to write a program or function which, given two nonzero integers x and y, returns a truthy value if the image at coordinates x east and y north of xkcd's click and drag comic is mostly white and a falsey value otherwise.

Specifications

  • The image should be retrieved from imgs.xkcd.com/clickdrag/[y]n[x]e.png, where [y] and [x] are replaced with the absolute values of the input y and x values.
  • If x is negative, e should be changed to a w. If y is negative, n should be changed to a s.
  • If a 404 error is returned, assume the image is mostly white (output truthy) if y is positive and mostly black otherwise. This is because (as far as I can tell) xkcd stores neither completely white regions of the sky nor completely black regions of the ground, leading to less data in their servers and these 404s you must handle. This error handling is not intended to deal with the images not being available.
  • "white" is defined as rgb #FFFFFF. You may assume that the images are only white(#FFFFFF) and black(#000000), without gray or other colors. "Mostly white" is defined as at least 2097153 pixels of the image are white (because the png the program should retrieve from img.xkcd.com is always 2048x2048 pixels).
  • The program may have any behavior when dealing with pixels that are not exactly #FFFFFF nor #000000 but must produce the same output as expected for the test cases.

Example

The image at x=2, y=9 should be retrieved from imgs.xkcd.com/clickdrag/9n2e.png and appears as follows (formatted as quote to show border):

clickdrag/9n2e

It is mostly white, so the program should return a truthy value.

Input / Output

Input should be two integers or a list of two integers representing x and y.

Output should be a truthy or falsy value corresponding to if the image is mostly white.

Input and output should be through any standard I/O method.

Test Cases

Truthy (as (x,y))

2,9
7,-17
9, 5
3, 2
-5, 1
1, 3

Falsy (as (x,y))

3, 1
3, -1
7, -16
2, 1
5, 1
17, -1
\$\endgroup\$
  • \$\begingroup\$ @JonathanAllan Yes. \$\endgroup\$ – fireflame241 Jun 10 '17 at 1:43
  • \$\begingroup\$ @JonathanAllan I switched the X and Y for that. I will look over any other errors I may have made. \$\endgroup\$ – fireflame241 Jun 10 '17 at 1:46
  • \$\begingroup\$ How should we handle the greys? Can we assume that any colour that isn't exactly #fff is black or, alternatively, that any colour that isn't #000 is white? \$\endgroup\$ – Shaggy Jun 10 '17 at 14:40
  • 1
    \$\begingroup\$ @Shaggy You may have any behavior regarding pixels which are not white nor black. Updating in the question. \$\endgroup\$ – fireflame241 Jun 10 '17 at 15:58
  • 2
    \$\begingroup\$ Boo-urns to input validation! (handling 404s) \$\endgroup\$ – Shaggy Jun 10 '17 at 16:50
3
\$\begingroup\$

MATLAB, 144 bytes

function r=f(x,y);n=@num2str;r=1;try;r=nnz(imread(['http://imgs.xkcd.com/clickdrag/',n(y),'n'+5*(y<0),n(x),'e'+18*(x<0),'.png'],'png'))>2^21;end

This function takes two arguments x,y. imread reads the image at the given path. In this case we get a black and white image where each pixel (= entry in a matrix) contains the number 0 or 255. To count the white (255) pixels, nnz is used (which conts the number of nonzero entries). To account for possible eerrors, we wrap this call in try/end and predefine the return value to 1 (nonzero numbers are truthy in MATLAB). The change of e.g. n and s depending on the sign of y is done via character arithmetic.

\$\endgroup\$
2
\$\begingroup\$

bash, 172 164 158 bytes

t=tr\ \\-0-9
curl imgs.xkcd.com/clickdrag/${2#-}$($t sn<<<${2::1})${1#-}$($t we<<<${1::1}).png|convert - a.pgm
echo $[$??$2>0:`grep -ao ÿ a.pgm|wc -l`>2**21]

This won't work on TIO due to the requirement for internet access.

There's an \xFF byte in the code, which is likely to be mangled due to encodings, so here's a script you can use to run all the test cases locally:

#!/bin/bash

xxd -r >clickdrag.sh <<'end'
00000000: 743d 7472 5c20 5c5c 2d30 2d39 0a63 7572  t=tr\ \\-0-9.cur
00000010: 6c20 696d 6773 2e78 6b63 642e 636f 6d2f  l imgs.xkcd.com/
00000020: 636c 6963 6b64 7261 672f 247b 3223 2d7d  clickdrag/${2#-}
00000030: 2428 2474 2073 6e3c 3c3c 247b 323a 3a31  $($t sn<<<${2::1
00000040: 7d29 247b 3123 2d7d 2428 2474 2077 653c  })${1#-}$($t we<
00000050: 3c3c 247b 313a 3a31 7d29 2e70 6e67 7c63  <<${1::1}).png|c
00000060: 6f6e 7665 7274 202d 2061 2e70 676d 0a65  onvert - a.pgm.e
00000070: 6368 6f20 245b 243f 3f24 323e 303a 6067  cho $[$??$2>0:`g
00000080: 7265 7020 2d61 6f20 ff20 612e 7067 6d7c  rep -ao . a.pgm|
00000090: 7763 202d 6c60 3e32 2a2a 3231 5d         wc -l`>2**21]
end

for x in '2 9' '7 -17' '9 5' '3 2' '-5 1' '1 3' '3 1' '3 -1' '7 -16' '2 1' '5 1' '17 -1'
do
    bash clickdrag.sh $x 2>/dev/null
done

rm clickdrag.sh

Explanation

First, an explanation of how the URL is built:

imgs.xkcd.com/clickdrag/${2#-}$($t sn<<<${2::1})${1#-}$($t we<<<${1::1}).png

Here, ${2#-} removes a leading negative sign from the second command line argument, and ${1#-} does the same for the first. The n/s and e/w are generated, respectively, with the snippets (after expanding $t)

tr '\-0-9' sn<<<${2::1}
tr '\-0-9' we<<<${1::1}

The ${_::1}s take the first character of the appropriate command line argument (which will be - if it is negative and a digit otherwise). The tr command then turns - into s/w and digits into n/e.

The URL is then passed to curl, which retrieves the image:

curl URL|convert - a.pgm

The convert command from ImageMagick turns the difficult PNG format into the much easier PGM, which uses one byte per pixel. It writes to the file a.pgm.

If the URL 404s, the convert command will fail to find an image and exit with a nonzero status code. Thus, we can effectively use $? (exit code of the last command) as an indicator of whether the URL returned a 404. This comprises the remainder of the code:

echo $[$??

If the exit code was nonzero (link was a 404), we simply check whether the y coordinate is positive:

$2>0

Otherwise, we count the number of \xFF bytes (white) in the image and test to see whether it's greater than 221:

:`grep -ao ÿ a.pgm|wc -l`>2**21]
\$\endgroup\$
1
\$\begingroup\$

Javascript (ES6), 317 bytes

f=(x,y)=>{l=console.log;c=document.createElement`canvas`.getContext`2d`;i=new Image;i.onload=_=>{c.drawImage(i,0,0,1,1);l(!!c.getImageData(0,0,1,1).data[0])};i.onerror=e=>l(y>=0);i.crossOrigin='anonymous';i.src=`https://crossorigin.me/https://imgs.xkcd.com/clickdrag/${(y<0?y*-1+'s':y+'n')+(x<0?x*-1+'w':x+'e')}.png`}

This works by shrinking the image to an 1*1 pixel, and checking whether the red channel of this pixel is 0 or not (if white it would be 255).

Note that it has a somehow big margin of error for 50 white/50 black cases : on my computer, if there are less than between 50% - 1024px and 50%, it will report as gray, and hence white. But, as long as there is no proof that there is an image in the list with less than 1024 px of difference between black and white, I guess it's still valid.

Ungolfed :

f=(x,y)=>{
  l=console.log; // output in the console since the function is async
  c=document.createElement`canvas`.getContext`2d`;
  i=new Image;
  i.onload=_=>{
    c.drawImage(i,0,0,1,1); // draw resized at 1px*1px
    // is the first red value of the pixel '0' ?
    l(!!c.getImageData(0,0,1,1).data[0])
    };
   // handle 404
  i.onerror= e=> l(y>=0);
  // 56 bytes only for cross-origins...
  i.crossOrigin="anonymous";
  i.src= `https://crossorigin.me/https://imgs.xkcd.com/clickdrag/${
    // there could probably be some out-golfing to do here
    (y<0?y*-1+'s':y+'n') + (x<0?x*-1+'w':x+'e')
    }.png`;
}

Here is a 319 bytes Promise based live version, for better logging of the outputs, since all this is async :

f=(x,y)=>new Promise(l=>{c=document.createElement`canvas`.getContext`2d`;i=new Image;i.onload=_=>{c.drawImage(i,0,0,1,1);l(!!c.getImageData(0,0,1,1).data[0])};i.onerror=e=>l(y>=0);i.crossOrigin='anonymous';i.src=`https://crossorigin.me/https://imgs.xkcd.com/clickdrag/${(y<0?y*-1+'s':y+'n')+(x<0?x*-1+'w':x+'e')}.png`})


var pos = [
// truthy
  {x:2,y:9},
  {x:7,y:-17},
  {x:9,y:5},
  {x:3,y:2},
  {x:-5,y:1},
  {x:1,y:3},
// falsy  
  {x:3,y:1},
  {x:3,y:-1},
  {x:7,y:-16},
  {x:2,y:1},
  {x:5,y:1},
  {x:17,y:-1}
  ];
function test(i){
  let p = pos[i];
  let prom = f(p.x, p.y)
  prom.then(r=>{ 
    console.log(p.x, p.y, ': ', r);
    if(i < pos.length) 
      test(++i);
    });
  }
test(0);

And if ever someone find an image with less than 1024px of difference between whites and blacks, here is a 378 bytes version which handles it :

f=(x,y)=>{l=console.log;o=document.createElement`canvas`;w=o.width=o.height=2048;i=new Image;i.onload=_=>{c=o.getContext`2d`;c.drawImage(i,0,0);l(c.getImageData(0,0,w,w).data.reduce((a,v,i)=>(i%4&&v?++a:a),0)/4>w*w/2)};i.onerror=e=>l(y>=0);i.crossOrigin='anonymous';i.src=`https://crossorigin.me/https://imgs.xkcd.com/clickdrag/${(y<0?y*-1+'s':y+'n')+(x<0?x*-1+'w':x+'e')}.png`}
\$\endgroup\$
  • \$\begingroup\$ Nice idea, shrinking the image to a single pixel (although I can't test how accurate it is on my phone). Few things: You don't need to handle errors and your function doesn't need to log the result, simply output it. \$\endgroup\$ – Shaggy Jun 10 '17 at 16:27
  • \$\begingroup\$ Oh, wait, in this case we do need to handle errors. Boo-urns to input validation! \$\endgroup\$ – Shaggy Jun 10 '17 at 16:45
  • \$\begingroup\$ @Shaggy, I have to admit I didn't really tested for exactly 2097152blacks vs 2097152 whites, and I guess that results may vary across devices and implementations, but as long as nobody shows me a perfectly 50/50 images in xkcd where it fails, I guess it holds, right ? And for the console.log, it's because the function is async... I could have returned a promise, but at the cost of 2 bytes (added it anyway though). \$\endgroup\$ – Kaiido Jun 11 '17 at 2:02
  • \$\begingroup\$ So after testing, there is a somewhat large gray area around 50/50 where the pixel will be set to 128,128,128, and hence my code will see it white, but once again, I'm waiting for someone to find an image in the list which would fall into this gray area. \$\endgroup\$ – Kaiido Jun 11 '17 at 2:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.