20
\$\begingroup\$

Martin has created a nice snippet that can be used to keep track of the score for answers to challenges. That's great and all, but wouldn't it be better if you could keep track of it yourself?

Create a program that compares the byte counts in itself with the rest of the answers to this question, and returns "I'm answer number n".

Rules:

  • The byte count in your own answer can be hardcoded in the code

  • The function can take the url as input, or it can be hardcoded. The chars for the url will not count toward the byte count, so it's not necessary to use a url-shortener.

  • url-addresses to answers cannot be hardcoded

  • The score for the answers can be found from the header, (the same way Martin's snippet does).

  • The answer header must have the correct format (described below).

  • If it's possible to run the program online, please share a link to an online compiler (or a code snippet that can be executed from the answer). If it's not possible, please show how to call the function, and show the output from your own compiler (at the time you posted the answer. You don't need to update it unless you want to of course).

  • You have to actually compare the answer with the other answers to this question. Simply writing a script I'm answer number 1. in some language is not legal.

  • If other answers have the same number of bytes as your own, you can choose if you want to be best or worse of them.

The header must be formatted:

# Language Name, N bytes

Strike-through etc cannot be used, so if the code size is changed, show it in bold text below the header or indicate it in some other way.

The output must be I'm answer number n., where the number n is the position (trailing newline/spaces are OK). So, the shortest answer will output: "I'm answer number 1.", the second will be "I'm answer number 2." etc.

This is code golf, so the shortest answer in bytes will win.

\$\endgroup\$
  • \$\begingroup\$ If other answers have the same number of bytes as your own, you can choose if you want to be best or worse of them. Maybe post date should be a tie-breaker, so you don't have two answers claiming to be the same number. Or, you could use the standard that if they're tied, they're both tied for the higher place. \$\endgroup\$ – mbomb007 Oct 9 '15 at 16:51
  • 2
    \$\begingroup\$ I'm not sure this is going to work. Most (good) online interpreters don't allow curling other webpages, but in the challenge it says that the code has to run on an online interpreter. \$\endgroup\$ – a spaghetto Oct 9 '15 at 17:16
  • \$\begingroup\$ Let's talk about this in chat. \$\endgroup\$ – a spaghetto Oct 9 '15 at 17:19
  • \$\begingroup\$ Do any quotes around the URL need to be counted? Some answers currently exclude them from the count, others include them. \$\endgroup\$ – hvd Oct 10 '15 at 20:31
2
\$\begingroup\$

Perl, 107 bytes

use LWP;print"I'm answer number ",1+grep($_<107,LWP::UserAgent->new->get('http://codegolf.stackexchange.com/q/60204')->content=~/<h1>.+, (\d+)/g),'.';

Slightly less golfed:

use LWP;
$agent = new LWP::UserAgent();
$response = $agent->get('http://codegolf.stackexchange.com/q/60204');
@answers = $response->content =~ m/<h1>.+, (\d+)/g;
print "I'm answer number ", 1+grep($_<107, @answers), '.';

Sample Usage

$ perl my_rank.pl
I'm answer number 1.
\$\endgroup\$
7
\$\begingroup\$

Python 2, 145 bytes

from requests import*
print"I'm answer number %s."%(sorted([int(a["body"].split(",")[1].split()[0])for a in get('http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=activity&site=codegolf&filter=!SWJ_BpAceOT6L*G2Qa').json()["items"]]).index(145)+1)

Output from 2015-10-10 17:30:00 UTC:

I'm answer number 1.

I didn't count any of the URL for my score, if I should please comment on how much I should add to it. Has own score hardcoded in it, assumes that it's already posted. Will break if ever more than 99 answers are posted.

\$\endgroup\$
6
\$\begingroup\$

AutoIt, 175 bytes

(202 bytes - 27 for the URL)

#include<String.au3>
$0=_StringBetween
$1=1
For $2 In $0(BinaryToString(InetRead("http://q.codegolf.xyz/60204")),'<h1>',' b')
$1+=$0($2,', ','')[0]<175?1:0
Next
ConsoleWrite("I'm answer number "&$1&".")

Output from 2015-10-09 17:47:00 UTC:

I'm answer number 1.
\$\endgroup\$
  • \$\begingroup\$ I've never even heard of Autolt, but it is correct that this won't work if the language name has a comma in it? (I don't know if there are any such languages, so I'm not sure if it matters) \$\endgroup\$ – Stewie Griffin Oct 9 '15 at 17:43
  • \$\begingroup\$ @StewieGriffin Yes, but I don't recall any language with a comma in it either ;-) . If one comes up I'll change it. \$\endgroup\$ – mınxomaτ Oct 9 '15 at 17:44
  • \$\begingroup\$ @minxomat The name looks like it has an l instead of an I, so I misread it. The only reason I realized that is by seeing the Wikipedia article, which has a serif. \$\endgroup\$ – mbomb007 Oct 9 '15 at 18:12
  • \$\begingroup\$ Just waiting for someone to invent a language with a comma in it just to sabotage this answer... \$\endgroup\$ – Darrel Hoffman Oct 10 '15 at 15:12
  • \$\begingroup\$ @DarrelHoffman Well, it would have to have a comma and a space consecutive in it's name ^^ \$\endgroup\$ – mınxomaτ Oct 10 '15 at 16:32
4
\$\begingroup\$

JavaScript (ES7), 149 bytes

283 bytes - 134 for the URL. I've never use HTTP requests before, but here goes...

x=z=>alert(`I'm answer number ${[for(y of z.items)y.body.match(/, (\d+)/)[1]].sort().indexOf("149")+1}.`);document.write('<script src="//api.stackexchange.com/2.2/questions/60204/answers?pagesize=100&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T&callback=x">\x3C/script>')

Tested successfully in Firefox 41.

First it looks through the headers of all the answers to find their byte-counts, then it finds the first position with byte-count 243 149. It's currently set up to check only the first 100 answers, and will break if someone gets under 100 bytes, but it works for now. ;)

Thanks to @GeorgeReith for the much shorter technique. Old version using AJAX (243 bytes):

x=new XMLHttpRequest,x.onreadystatechange=_=>{if(x.readyState==4&&x.status==200)alert(`I'm answer number ${[for(y of JSON.parse(x.responseText).items)y.body.match(/, (\d+)/)[1]].sort((a,b)=>a-b).indexOf("243")+1}.`)},x.open("GET","//api.stackexchange.com/2.2/questions/60204/answers?pagesize=100&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T",!0),x.send()
\$\endgroup\$
  • \$\begingroup\$ Looking good... although will possibly break if someone posts another 151 byte answer \$\endgroup\$ – George Reith Oct 10 '15 at 20:11
  • \$\begingroup\$ @GeorgeReith Nah, it shouldn't. The OP says that ties can be broken either way, and this'll just place itself ahead of the other. \$\endgroup\$ – ETHproductions Oct 10 '15 at 20:15
  • \$\begingroup\$ Ah he edited that out. Still its probably better to sort by creation date instead to make it more likely it finds yours instead of one of the few who posted before and edit their answer. \$\endgroup\$ – George Reith Oct 10 '15 at 20:19
  • \$\begingroup\$ @GeorgeReith If other answers have the same number of bytes as your own, you can choose if you want to be best or worse of them. That's still in the main post; am I misunderstanding something? \$\endgroup\$ – ETHproductions Oct 10 '15 at 20:22
  • \$\begingroup\$ No apologies I was reading the edit history and got confused. \$\endgroup\$ – George Reith Oct 10 '15 at 20:40
4
\$\begingroup\$

PHP, 158 159 164 bytes

I'm answer number <?for(;$h[]=json_decode(fread(gzopen('http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T',r),1e4),1)[items][+$i++][body];);echo array_sum(preg_filter(~„ÑÕß×£›ÔÖ߆‹šŒÃЗÎÑÕ‚Œš,~ÛÎÃÎÊÇ,$h)),~Ñ;

127 bytes from 'http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T' not counted

Formatted version with ungolfed strings:

<?
for(;
    $h[]=json_decode(
        fread(
            gzopen(
                'http://api.stackexchange.com/2.2/questions/60204/answers?pagesize=99&order=desc&sort=votes&site=codegolf&filter=!--pn9sqW9y0T',r
            ), 1e4
        ), 1
    )[items][+$i++][body];
);
echo"I'm answer number ",
    array_sum(
        preg_filter('{.* (\d+) bytes</h1.*}se','$1<159', $h)
    ),
    ".";
  • Loads the JSON response (one time per answer actually to save 5 bytes, thanks to @Blackhole)
  • Collects answer bodies in $h
  • replaces whole text with "1" (true) if the byte count is <=159, or "" (false) otherwise
  • sums the results

The character sequences like ¶Ø’ßž‘Œˆšß‘Š’šß are valid constant names in PHP, but because the constants do not exist are treated as string literal. ~ inverts them, this one to "I'm answer number " (saving a byte for one quotation mark each)

Usage

php -derror_reporting=0 howareyou.php

I'm answer number 1.

\$\endgroup\$
  • \$\begingroup\$ Is the $a variable really necessary? Why don't you simply do $h[]=json_decode(…)[items][+$i++][body]? What are this strange characters, by the way? \$\endgroup\$ – Blackhole Oct 9 '15 at 22:48
  • \$\begingroup\$ Good point. This will make a new request for each answer but who cares :) The strange characters are bitwise inverted strings. They are valid constant names in PHP that are used as string literals if they don't exist, so I can save the quotation marks. For example " " (3 bytes) can be reduced to (2 bytes) \$\endgroup\$ – Fabian Schmengler Oct 9 '15 at 23:00
  • \$\begingroup\$ Indeed, I've found your explanation on this answer. Since that's an unusual method, I think it could be a good idea to explain it again here in your post :). \$\endgroup\$ – Blackhole Oct 9 '15 at 23:02
  • \$\begingroup\$ I think you can do a lot better if you skip the json_decode and just split on ':' or something, e.g.: codepad.org/7rZg06by \$\endgroup\$ – primo Oct 15 '15 at 12:31
  • \$\begingroup\$ Good idea but I fear it might be unreliable as there will be lots of colons in the source codes. Putting "I'm answer number" before the opening PHP tag saves at least two bytes, thanks for that! \$\endgroup\$ – Fabian Schmengler Oct 15 '15 at 13:49
3
\$\begingroup\$

Javascript (ES6), 186 bytes

(335 - 149 bytes for the URL)

a=d=>alert(`I'm answer number ${d.items.map(q=>(y=[q.body.match(/, (\d+)/)[1],(x=q.owner.user_id==11182)])&&x?z=y:y).sort().indexOf(z)+1}.`)
document.write(`<script src="https://api.stackexchange.com/questions/60204/answers?pagesize=100&order=desc&sort=activity&site=codegolf&filter=!)Q2B_A19OPkd2j8JforD00f5&callback=a">\x3C/script>`)

\$\endgroup\$
  • \$\begingroup\$ I had no clue you could do it that way! May I ask why you used \x3C instead of <? \$\endgroup\$ – ETHproductions Oct 10 '15 at 16:31
  • \$\begingroup\$ @ETHproductions Because the browser looks for the closing script tag right away and won't execute the script otherwise, this defers the closing of the script tag until post insertion. It uses JSONP with a callback and is up to the API whether it supports it but luckily stackexchange does. Honestly I don't fully understand the reasoning for it but it is a legitimate issue. \$\endgroup\$ – George Reith Oct 10 '15 at 19:54
1
\$\begingroup\$

Awk, 153 bytes

BEGIN{if(u){print"I\047m answer number "system("curl -s "u"|awk -f a")".";exit}FS="1>.*,|es<\/h"}NF==3{r+=($2+0)<153?1:0}END{exit(r<1?1:r)}

This should be saved to a file a and run like:

awk -v u=http://codegolf.stackexchange.com/questions/60204/how-are-you-doing -f a

I'm subtracting the 68 bytes for http://codegolf.stackexchange.com/questions/60204/how-are-you-doing and adding 13 to the code for the bootstrapping awk -v u= and -f a.

Less golfed, this can be even shorter:

curl -s http://codegolf.stackexchange.com/questions/60204/how-are-you-doing | awk -F"1>.*,|es<\/h" 'NF==3{r+=(0+$2)<103?1:0}END{print"I\047m answer number "(r<1?1:0)"."}'

It always prefers itself in ties. The byte count is hard coded in each.

The more golfy version has the script calling itself and outputting the exit value via system. In each case only counts lower than the hard-coded value increment r, which then has to be adjusted back to 1 if it's leading.

This will fail to correctly find bytes if there's whitespace between bytes and </h1> and probably a number of other cases I haven't considered.

As of Sun Oct 11 05:17:51 UTC 2015, this gives:

I'm answer number 3.
\$\endgroup\$
  • \$\begingroup\$ Since this is my first time golfing please let me know if I've violated any rules, loopholes, counts etc or what improvements I could make. \$\endgroup\$ – n0741337 Oct 11 '15 at 4:15
  • \$\begingroup\$ I think you need to print "I'm answer number" rather than "I am number". \$\endgroup\$ – lirtosiast Oct 11 '15 at 4:58
  • \$\begingroup\$ @ThomasKwa Hah! I knew it was too good to be true. Thanks and fixed. Does adding bytes back require a strike-through? \$\endgroup\$ – n0741337 Oct 11 '15 at 5:20
  • \$\begingroup\$ You don't need one, just like you don't need a strikethrough when you golf off bytes. \$\endgroup\$ – lirtosiast Oct 11 '15 at 5:55
1
\$\begingroup\$

GNU Awk, 156 bytes

(Inspired by n0741337's Awk solution.)

This one does it all itself, without running external command.

BEGIN{d="/inet/tcp/0/"h"/80"
print"GET "p" HTTP/1.1\nHost:"h"\n"|&d
while(d|&getline)n+=match($0,/1>.*, ([0-9]+)/,m)&&m[1]<156
print"I'm answer number",n+1}

Expects hostname and path as separate values. Given they are available for free, hopefully this not breaks the rules.

Sample run:

bash-4.3$ awk -v h=codegolf.stackexchange.com -v p=/questions/60204/how-are-you-doing -f number.awk 
I'm answer number 4
\$\endgroup\$

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.