Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

This was fun! However with only three digits, the fun was over way too soon. This challenge is similar, but we'll keep the fun going.

The Challenge

Print as many digits of the Golden Ratio φ as possible. The Golden Ratio is defined as the number that satisfies φ = (φ + 1)/φ and the first 100 digits are given by:

1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911375...

This challenge is not about computing φ! It's about printing as many digits as possible without using any method for doing that twice. So find as many creative ways to get your digits as you can!

Restrictions

By itself, printing the digits of φ would be a bit too simple, so here are the rules:

  1. You have to construct the number in order from left to right, either by printing it piece by piece or by constructing a string from left to right and printing it at the end - you could even generate an array of digit characters and then join it and print it, as long as you do it in order. In the following rules "print" and "output" may refer to any of those processes (e.g. if you're building a string, and the string contains 1.6 that counts as having 1.6 already printed).
  2. For your code you get a budget of 15 characters per digit. The period does not count towards that budget, but has to be printed as well. Note that the restriction is only on total code size: you may use more than 15 characters for any digit as long as you don't use more on average. In fact, you may build up a "debt" in characters and "pay it off" later. E.g. to print 1.618 you have 60 characters.
  3. Standard-library includes/imports do not count towards the code size. But you can't give those includes shorthand aliases for free!
  4. You must not use the digit you are currently generating, nor any you have already printed. E.g. 1 may appear nowhere in your source code, because it's the very first digit. The code that outputs the 8 in 1.618 may use any or all of the digits [0234579], but none of [168]. For this purpose, all literals that are equivalent to a single digit are treated as that digit. So if your language can represent 9 as '\t' you are not allowed to use that anywhere, where you couldn't use an 9 instead.
  5. You must not produce multiple digits at once. It should be possible to clearly split your code into chunks that generate one digit a time.
  6. You must not refer to any built-in function, mathematical/boolean/bit-wise/string operator, variable or constant which you have used in code that generated an earlier digit. Exceptions are integer-to-string conversion, string concatenation and printing functions which you might need for every single digits. Note that it doesn't matter by which name you refer to any built-in: just because you alias a built-in PI to both p and q doesn't mean you get to use p once and q once. Likewise, you are allowed to use a name twice if it refers to two different built-ins, like string length and array length.

    If your programming language doesn't have functions use your best judgement on what the equivalent would be - e.g. for bash scripting, invoking other programs should follow the rules imposed on functions

  7. Your submission must be written in a single language. So no executing another language's interpreter to get access to that language's built-ins as well.

Implications

The following points are all implied by the above rules, but I add them here to avoid questions that have already come up in the sandbox::

  • You're not allowed to overwrite parts of your output by printing some backspaces (usually '\b') in between.
  • Loops which generate/output multiple digits are forbidden. (Loops that compute a single digit are fine, though.)
  • Using an obfuscated version (1 + √5)/2 or dividing Fibonacci numbers to obtain more than a single digit is forbidden.
  • You cannot precalculate the 10 digits and store them in 10 variables and then just refer to those, because those variable references dont' generate the digit - the code that fills the variable does, so this is a violation of rule 6.
  • In fact, you can't reuse any previous (or intermediate results), because that would mean two digits would share code for being generated.
  • Otherwise, you can use any means whatsoever (which do not have to purely mathematical) to generate the digits. (And you should!)
  • In fact there is no need to calculate anything, if you can pull out the correct digits from many different places using your standard library.
  • You may use an operator multiple times while generating a single digit, so 2+2+2 is fair game to generate the first 6 (although it's unlikely the shortest).
  • You may use any literal as often as you want, because they are not built-in constants. So as long as you don't have to print 5, you can as many 5s in your code as you want.
  • You can't hardcode the output, because that would involve using the digits you are outputting.

In short: don't use any method of generating digits twice and don't use the digit you are currently outputting or any have already printed.

If you do spot a loophole which allows you to get a (quasi-)infinite score, please don't ruin the challenge by exploiting it, but let me know so I can see if the loophole can be fixed without breaking anything.

Scoring

The program that prints the highest number of digits correctly wins. In case of a tie the shorter code breaks the tie.

Please add an ungolfed commented version that identifies which part of your code generates which digit.

PS: If anyone beats the 100 digits above, here are some more.

share|improve this question
    
Comments purged; please notify me for any possible lost information. –  Doorknob 冰 May 23 at 1:12
    
"Using an obfuscated version..." That's just using the quadratic formula on x = (x+1)/x (or x^2 = x+1) (or x^2-x+1). –  Cole Johnson Jun 16 at 3:59

12 Answers 12

up vote 13 down vote accepted

PHP, 100 digits

I'm probably bending the rules a bit here, but PHP has dozens of constants to choose from:

<?php
echo TRUE . '.' . PM_STR . DNS_A . MSG_EOR . LC_ALL . T_FMT . LOCK_UN . SQL_DATE
. E_NOTICE . IMG_WBMP . INI_ALL . E_PARSE . SOCKET_EBADF . LOG_USER .
IMAGETYPE_JPC . IMG_PNG . GLOB_MARK . LOCK_NB . LOG_NDELAY . D_FMT . PHP_ZTS .
GLOB_ERR . AM_STR . SQL_DOUBLE . SOL_TCP . FILE_APPEND . LOG_ERR . SORT_ASC .
SOCK_RAW . LOG_INFO . LC_TIME . SQL_FLOAT . SORT_DESC . INFO_MODULES . E_ERROR .
IMG_GIF . SQL_REAL . LOG_DEBUG . DNS_NS . CODESET . CAL_FRENCH . CURLE_OK .
LDAP_OPT_RESTART . LOCK_SH . XML_PI_NODE . SQLITE_INTERRUPT . MYSQLI_ASYNC .
CURLM_OK . SNMP_NULL . SQLITE_NOMEM . LC_MESSAGES . IMG_JPG . SO_KEEPALIVE .
SOCKET_ENXIO . LOCK_EX . D_T_FMT . ENT_QUOTES . LOG_NOTICE . SOCK_RDM .
INPUT_ENV . CURLAUTH_NTLM . INPUT_SESSION . AF_INET . IMG_JPEG . SQL_CONCURRENCY
. SEEK_SET . SOCKET_EIO . LC_CTYPE . PHP_URL_QUERY . LOG_KERN . INI_SYSTEM .
IMAGETYPE_BMP . SEEK_END . JSON_HEX_QUOT . LOG_PID . LIBXML_DTDATTR .
XML_DOCUMENT_NODE . PHP_DEBUG . LOG_CRIT . ENT_IGNORE . LC_NUMERIC .
DOM_NOT_SUPPORTED_ERR . PHP_URL_FRAGMENT . FILE_TEXT . IMAGETYPE_TIFF_II .
LOG_CONS . LOG_EMERG . UPLOAD_ERR_CANT_WRITE . MSG_PEEK . SQLITE_OK . FNM_PERIOD
. AF_UNIX . CURLPROTO_FTPS . STREAM_NOTIFY_FAILURE . MYSQL_BOTH .
CURLE_FTP_ACCESS_DENIED . MSG_OOB . FTP_TEXT . LC_MONETARY .
CURLE_COULDNT_CONNECT . SQLITE_BUSY . "\n";

This probably isn't very portable code, but it works fine on my system. Here's the code that generated it:

<?php
$phi = "6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911375";
echo "<?php\necho TRUE . '.' . ";
$consts = get_defined_constants();
foreach($consts as $k=>$v) if (preg_match('/\d|TRUE|PHP_EOL/',$k)) unset($consts[$k]);
for ($p=0;$p<strlen($phi);$p++) {
  $d = ord($phi[$p]) - 48;
  $min = 999;
  foreach($consts as $k=>$v) {
    if (strlen("$v")==1 && $v==$d && strlen($k)<$min) {
      $min = strlen($k);
      $maxk = $k;
    }
  }
  if ($min==999) break;
  echo "$maxk . ";
  unset($consts[$maxk]);
}
echo "\"\\n\";\n";
share|improve this answer
    
Hm, I have to admit that is probably valid. The only thing it might fall under is "multiple names referring to the same constant", but I didn't actually intend that wording to cover this case. I clarified in kernigh's answer that this would be only invalid if the actually pointed to the same integer, but I think that's unlikely. The fact that a lot of this does depend on your system is a shame, but not part of the rules either. So unless someone else can spot a problem here, I'll have to admit that your answer is perfectly valid. ;) –  Martin Büttner May 21 at 18:21
    
<?for(;;); uses 9MB of memory. Now I know why... I do like @kernigh's self-imposed restriction #7, though, which closes this sort of loophole. Also, for what it's worth, the output on my system is this: codepad.org/wSrtJBco –  primo May 22 at 3:32
    
Although, running the generator does produce a valid representation, so +1 for that ;) A version that runs on the codepad server: codepad.org/myBpc6cB –  primo May 22 at 3:56
1  
Congrats, you broke the challenge. ;) ... Not really... this answer does sidestep the actual challenge somewhat, but it's well within the rules as far as I can see, so I'll have to admit defeat and accept it. :) –  Martin Büttner May 28 at 17:31

Perl - 37 digits

use Math::Trig;
use POSIX;

print
  !0,'.',chop$=||$=,A==A,2**3,$|,++$^F,75/5/5,pi*pi%\_,4+4,a^Y,w&'?',~"\xcb",$^=~y/_//c,
  ord"\b",unpack(h,"\t").@{[c,c,c,c]},$#{[b..j]},"$^W"|'$',$^H>>log$^H,cos()- -cos,$[,
  $-=sqrt%SIG,$%=$],$+[*$=~/($)/],split('',$~).map(glob,"{,,,}{,}"),index(\L,L),
  exp(exp)<<exp,ceil(sinh acosh$^C).keys{stat$0},rindex(\R,R),($s=ssssss)=~s/s//g,
  $?=acos(--$z),$^T=pack(u,$^T.$^T.TTTT),B~~B,C<=C,length$^V,

392 bytes currently, (10.6 per digit).

Output:

1.618033988749894848204586834365638117

Self-imposed Restrictions

I've added a few additional restrictions to limit the use of language features that would trivialize the problem. For example, array dereference @{...} and array final index $#{...} are only used once. Each array used is generated in a different manner (compare [c,c,c,c], [b..j], split('',$~), map(glob,"{,,,}{,}")). Additionally, no symbol or bareword is used more than once, although this is explicitly allowed in the challenge description. I think it's a good idea for perl (or any language with int-only special variables (are there any others?)), because it limits the number of implicit int conversions.


Pieces

!0                       # returns 1
'.'
chop$=||$=               # $= is 60, chop the 0, returns 6
A==A                     # returns 1 (because 0==0)
2**3                     # returns 8
$|                       # auto flush, returns 0
++$^F                    # max system filehandle pre-incremented, returns 3
75/5/5                   # returns 3
pi*pi%\_                 # pi² mod a large value, returns 9
4+4                      # returns 8
a^Y                      # bitwise 'a' xor 'Y', returns 8
w&'?'                    # bitwise 'w' and '?', returns 7
~"\xcb"                  # bitwise inversion of char 203, returns 4
$^=~y/_//c               # count non-underscores in $^, returns 9

ord"\b"                  # returns 8
unpack(h,"\t")           # unpack "\t" as a hex nibble, returns 9
@{[c,c,c,c]}             # anonymous array, returns 4 in scalar context
$#{[b..j]}               # final index of the range b..j, returns 8
"$^W"|'$'                # bitwise '0' or '$', returns 4
$^H>>log$^H              # $^H is 256, log$^H is ~5, returns 8
cos()- -cos              # cos(undef) is 1, subtract -1, returns 2
$[                       # array start index, returns 0

$-=sqrt%SIG              # set $- to sqrt(23), returns 4
$%=$]                    # set $% to the version number, returns 5
$+[*$=~/($)/]            # match end on *$ (aka *main::$), returns 8
split('',$~)             # split "STDOUT" into chars, returns 6 in scalar context
map(glob,"{,,,}{,}")     # an array of 8 empty strings, returns 8 in scalar context
index(\L,L)              # finds 'L' in 'SCALAR(...)', returns 3

exp(exp)<<exp            # 2.718281828 << 1, returns 4
ceil(sinh acosh$^C)      # ceil(2.30129...), returns 3
keys{stat$0}             # stat$0 is an array with 13 entries, which has 6 keys when
                         # interpreted as a hash, returns 6 in scalar context
rindex(\R,R)             # finds 'R' in 'SCALAR(...)' in reverse, returns 5
($s=ssssss)=~s/s//g      # replace the every 's' in 'ssssss' with nothing, returns 6

$?=acos(--$z)            # set $? to 3.14159... implicit int conversion, returns 3
$^T=pack(u,$^T.$^T.TTTT) # set $^T to "8,30P,...", returns 8
B~~B                     # returns 1 (because B represents the same thing as B)
C<=C                     # returns 1 (because 0<=0)
length$^V                # string length of $^V, returns 7
share|improve this answer

Python 2.7, 19 digits, 231 relevant chars

from math import ceil, pi, trunc, gamma, sin

print ''.join(map(str,
[33-32,
chr(46),
~-7,
8>>3,
trunc(gamma(4.3)),
'x'.find('x'),
22/7,
range(4).pop(),
len('am I phi?'),
52%44,
2*4,
5|2,
ord('/'),
'\b',
5+2+2,
2<<2,
eval("5+2+2"),
ceil(pi),
'\b',
'\b',
str(sin(5))[5],
5&52]))
share|improve this answer
    
This answer was posted before the backspace-loophole was closed. As it's quite a clever trick and is not harmful to the challenge in this case (and because this was the answer that actually pointed me to the loophole), this answer may remain as is - so please don't downvote it based on that, rather upvote it for cleverness. :) –  Martin Büttner May 19 at 23:46

Java, 21 digits, 276 characters

class C{public static void main(String[]a){System.out.print((3&5)+"."+(2|4)+Byte.BYTES+2*4+"".length()+(7-4)+~-4+(7+2)+(2<<2)+(int)Math.sqrt('@')+(2^5)+(int)Math.pow(2,2)+32%23+Byte.SIZE+('$'>>2)+Float.BYTES+Long.BYTES+Integer.BYTES+Double.BYTES+Short.BYTES+Math.round(.2));}}

class C {
  public static void main(String[] a) {
    System.out.print(
      (3&5)+       // 1
      "."+         // .
      (2|4)+       // 6
      Byte.BYTES+  // 1
      2*4+         // 8
      "".length()+ // 0
      (7-4)+       // 3
      ~-4+         // 3
      (7+2)+       // 9
      (2<<2)+      // 8
      (int)Math.sqrt('@')+  // 8
      (2^5)+       // 7
      (int)Math.pow(2,2)+   // 4
      32%32+       // 9
      Byte.SIZE    // 8

      // rest of explanation to come later today
    );
  }
}
share|improve this answer
    
Ha, I like 7-4 & -4+7, that's clever! :) –  Martin Büttner May 19 at 22:24
    
clever, but I think it violates the rule of not re-using constants (positive 7 is used in both) –  rangu May 19 at 22:25
1  
@rangu 7 is not a constant but a literal –  Martin Büttner May 19 at 22:26
    
So why did you stop there? –  Valentin Grégoire May 21 at 10:23

Ruby, 74 chars, 10 digits

It's just a start; I have to go so I will improve it later.

$><<[3-2,?.,3+3,?..size,2**3,$*.size,24/8,7%4,[*7..77][2],2*4,7.next].join

I have 76 characters saved up for later, when it will get more difficult!

share|improve this answer
    
This a good start! At last an answer in the spirit of the question. :) –  Martin Büttner May 19 at 21:24

Ruby 2.1 for 54 digits, 808 characters

#!ruby -rdate -rdigest -ropenssl -rprime -rset -rsocket
print 2/2,?.,9-3,3&5,2*4,2^2,7%4,55>>4,5+4,2<<2,-~7,5|2,2**2,(2r+2+5).to_i,(2.2+5).ceil,(55r/5-2).floor,(2.2*2).to_i,(2r*2*2).ceil,(2.2**2).floor,2.to_bn<<2,__LINE__,$<.to_i,IO::LOCK_NB,Errno::EIO::Errno,File::APPEND,'aaaaaa'.size,?a.encoding.name.sub(/\D+/,''),%w[a a a].size,%w[a b c d].to_set.size,%w[a a a].count,Socket::AF_NS,Date.jd(Date::ITALY).wday,*Digest::MD5.digest(?j).scan(/\d/),Set[?a,?b,?c].count,SignalException.new('FPE').signo,Float::ROUNDS,begin
exit false
rescue Object
$!.status
end,Process::RLIMIT_NPROC,:aaaaaaa.size,Prime.first,?/.next,{a:p,b:p,c:p}.size,STDIN.lineno,?a.crypt('at')[/\d/],{a: :a}.find_index([:a,:a]),/b/=~'aaaaaaaaab',[?a,?b].index(?b),:aaaaaaab=~/b/,?\t.ord,'aaaaaaaab'=~/b/,open(?/).pos,'aaaaab'.index(?b),?\a.bytes{|b|break b},'aaaaaaa'.rindex(?a),%w[a a].map.size

This program works with ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-openbsd]. Systems other than OpenBSD 5.5 might have different values for a few digits.

Interpretations

The restrictions of this challenge, especially restriction 6, are not precise for Ruby. So I add my own interpretations:

  1. The parentheses, dot and double-colon are not operators. The parentheses just change the order of operations. The dot calls methods, as in $<.fileno, and the double colon gets constants, as in IO::LOCK_NB. The name of the method or constant is part of the operation. Because () . :: are not operators, I do not apply restriction 6 to them. I may reuse them to generate more digits.
  2. A method with a different implementation is a different method. For example, Array#count and Enumerable#count are not the same function for restriction 6. Both methods act the same, but Array#count overrides Enumerable#count with a different implementation. If I use Array#count to generate one digit, I may use Enumerable#count to generate another digit.
  3. Class#new is one method. In Ruby, Mutex.new, Random.new, Time.new and so on refer to the same method, Class#new. I use SignalException.new to generate one digit. Because of restriction 6, I may never again use Class#new.
  4. Constants for classes or modules are still constants. In Ruby, class names like Float and IO are constants! I use IO::LOCK_NB to generate one digit. Because of restriction 6, I may never again use IO. This interpretation binds only Ruby, and not other languages where package names are not constants.
  5. Literals are not constants. Though 2 is a mathematical constant (independent of any variables), it is not a constant in Ruby. I do not apply restriction 6 to literals, and I may reuse the literal 2 for more than one digit.
  6. Literals are not operators. I do not apply restriction 6 to the brackets or quotes that form literal arrays, hashes, regular expressions, or strings, as in [] {} // ''. I may always use such literals to generate more digits.
  7. Two constants with the same value are the same constant. File::APPEND and IPSocket::LOCK_UN are two names for the same number 8. Restriction 6 says, "it doesn't matter by which name you refer to any built-in." Because File::APPEND and IPSocket::LOCK_UN differ only by name, they must be the same constant, so I may not use them for two digits.
  8. Two digits may not refer to the same global variable. This closes a loophole. Restriction 6 only applies to functions, operators and constants. Restriction 4 only applies to literals. $SAFE is a built-in global variable, not a function, operator, constant, nor literal. $SAFE has the value 0. With the loophole, I can reuse $SAFE to generate every digit 0 in the program. I close the loophole by interpreting restriction 6 to also restrict global variables.

Comments

The first line is #!ruby -rdate -rdigest -ropenssl -rprime -rset -rsocket. Ruby parses this line and loads six parts of its standard library, as if by require 'date', require 'digest' and so on. I do not count these 56 characters, because restriction 3 exempts "standard library imports/includes".

The rest of the program calls print with a long list of arguments, to convert them to strings and print them in order. The arguments are these:

  1. 1 from 2/2: division Fixnum#/
    . from ?.: literal single-character string
  2. 6 from 9-3: subtraction Fixnum#-
  3. 1 from 3&5: bitwise and Fixnum#&
    • By interpretation 5, I may use 3 again.
  4. 8 from 2*4: multiplication Fixnum#*
  5. 0 from 2^2: bitwise exclusive-or Fixnum#^
  6. 3 from 7%4: modulus Fixnum#%
  7. 3 from 55>>4: right shift Fixnum#>>
  8. 9 from 5+4: addition Fixnum#+
  9. 8 from 2<<2: left shift Fixnum#<<
  10. 8 from -~7: negation of complement Fixnum#-@ Fixnum#~
    • Subtraction Fixnum#- and negation Fixnum#-@ are different methods.
  11. 7 from 5|2: bitwise or Fixnum#|
  12. 4 from 2**2: exponentiation Fixnum#**
  13. 9 from (2r+2+5).to_i: rational addition Rational#+ Rational#to_i
    • By interpretation 2, Fixnum#+ and Rational#+ are different methods. They both add numbers, but they have different implementations, starting from different types for the left number.
    • Rational literals like 2r are new in Ruby 2.1. 2r+2 calls Rational#+ and returns another rational; 2r+2+5 calls Rational#+ again.
    • Ruby prints rationals like 2/1 and floats like 2.0. To fix this, I convert to integer: to_i rounds toward zero, ceil rounds up, floor rounds down.
  14. 8 from (2.2+5).ceil: float addition Float#+ Float#ceil
    • By interpretation 1, I may use parentheses () and dot . again.
  15. 9 from (55r/5-2).floor: rational division and subtraction Rational#/ Rational#- Rational#floor
  16. 4 from (2.2*2).to_i: float multiplication Float#* Float#to_i
  17. 8 from (2r*2*2).ceil: rational multiplication Rational#* Rational#ceil
  18. 4 from (2.2**2).floor: rational exponentiation Rational#**
  19. 8 from 2.to_bn<<2: left shift with OpenSSL big number Fixnum#to_bn OpenSSL::BN#<<
  20. 2 from __LINE__: magic constant for current line number
  21. 0 from $<.to_i: file descriptor of standard input IO#to_i
  22. 4 from IO::LOCK_NB: flag for non-blocking file lock
    • This is the first of many constants to depend on system. OpenBSD has 4.
    • By interpretation 4, I may no longer use IO. By interpretation 7, I may no longer use any constant with the value of 4.
  23. 5 from Errno::EIO::Errno: number for input/output error
  24. 8 from File::APPEND: flag to append to a file
    • This is a loophole around interpretation 4. I may not use IO, but File inherits constants from IO, so File::APPEND is a different way to get IO::APPEND.
  25. 6 from 'aaaaaa'.size: length of string String#size
  26. 8 from ?a.encoding.name.sub(/\D+/,''): part of name of encoding String#encoding Encoding#name String#sub
    • By interpretation 6, I may use string quotes again.
    • Since Ruby 2.0, the default encoding is UTF-8. I take the name "UTF-8" and substitute /\D+/ matching "UTF-" with an empty string. This yields "8".
  27. 3 from %w[a a a].size: length of array Array#size
  28. 4 from %w[a b c d].to_set.size: number of elements in set Array#to_set Set#size
  29. 3 from %w[a a a].count: count all elements Array#count
    • The difference between Array#size and Array#count is that the latter takes optional arguments to choose which elements to count. I pass no arguments, so it counts all elements.
  30. 6 from Socket::AF_NS: number for NS address family
  31. 5 from Date.jd(Date::ITALY).wday: weekday number for Friday 15 October 1582, when Italy switched to Gregorian calendar Date::jd Date#wday
  32. 6 from *Digest::MD5.digest(?j).scan(/\d/): first ASCII digit in binary MD5 digest of "j" Digest::MD5::digest String#scan
    • String#scan returns an array of all matches. The * passes the array elements as arguments to print. This array is ["6"].
  33. 3 from Set[?a,?b,?c].count: count all elements Set::[] Enumerable#count
    • By interpretation 2, Array#count and Enumerable#count are different methods.
  34. 8 from SignalException.new('FPE').signo: number of SIGFPE Class#new SignalException#signo
  35. 1 from Float::ROUNDS: rounding mode, here 1 for round-to-nearest
  36. 1 from begin (newline) exit false (newline) rescue Object (newline) $!.status (newline) end: exit status for failure
    • This is the same value as SystemExit.new(false).status, but by interpretation 3, I may no longer call Class#new. Instead I raise and rescue a SystemExit.
  37. 7 from Process::RLIMIT_NPROC: number for resource limit for number of processes for one user
  38. 7 from :aaaaaaa.size: length of symbol Symbol#size
  39. 2 from Prime.first: first prime number Enumerable#first
  40. 0 from ?/.next: next string after "?" String#next
  41. 3 from {a:p,b:p,c:p}.size: length of hash Hash#size String#p
  42. 0 from STDIN.lineno: current line number for standard input IO#lineno
    • By interpretation 8, I may not reuse $<. I use STDIN. The difference is that $< is a global variable and STDIN is a constant. A program may set $< to a different input, but STDIN is always the original value of $<.
  43. 3 from ?a.crypt('at')[/\d/]: first ASCII digit in encrypted password String#crypt String#[]
    • System with different crypt() function will give different result.
  44. 0 from {a: :a}.find_index([:a,:a]): index of first key :a, value :a in hash Enumerable#find_index
    • I use a hash, not an array, because Array#find_index is an alias for Array#index, which I plan to use soon.
  45. 9 from /b/=~'aaaaaaaaab': index where string matches /b/ Regexp#=~
  46. 1 from [?a,?b].index(?b): index of first "b" in array Array#index
  47. 7 from :aaaaaaab=~/b/: index where symbol matches /b/ Symbol#=~
  48. 9 from ?\t.ord: ASCII value of tab "\t" String#ord
  49. 8 from 'aaaaaaaab'=~/b/: index where string matches /b/ String#=~
    • By interpretation 2, Regexp#=~ and String#=~ are different methods.
  50. 0 from open(?/).pos: position in file after opening root directory "/" as a file Kernel#open IO#pos
  51. 5 from 'aaaaab'.index(?b): index of first "b" in string String#index
  52. 7 from ?\a.bytes{|b|break b}: ASCII value of alert "\a" String#bytes
    • This works by iterating the bytes in "\a", but breaking the loop by returning the first byte.
  53. 6 from 'aaaaaaa'.rindex(?a): index of last "a" in string String#rindex
  54. 2 from %w[a a].map.size: size of enumerator that maps from array Array#map Enumerator#size
share|improve this answer
    
Impressive! Most of your interpretations are in line with the rules anyway. 1. I never intended invocation, dereferencing and access operators to be restricted, which is why I said "mathematical, boolean, bit-wise and string" operators. 2. Covered by rule 6. 3. Reusing new would be fine in other languages, because it's usually an operator - it just can't be reused on the same class because it calls a constructor (built-in function). How is that in Ruby? Does new really always call the same imlpementation or is it overridden in subclasses? [ctd.] –  Martin Büttner May 21 at 6:35
    
4. I'd be fine if you made an exception there for Ruby, but thanks for your sportsmanship. ;) 5. and 6. No they aren't, which is why some of the rules are stated the way they are. 7. That's a good subtle point I didn't think about. Technically, if they don't refer to the same 8, it would be fine to use both of them. 8. Good point, I didn't think about built-in variables. I'll check if it doesn't substantially break any other submission and amend rule 6. Thanks for playing fair! :) –  Martin Büttner May 21 at 6:39
    
I couldn't find any rule violation in this answer so I accepted it. However, I would like to reward your answer, as it's by far the longest one that actually plays by how the challenge was intended. Therefore, I will offer a bounty for this challenge. The bounty will run for seven days though and should an answer come along that beats yours in a "fair" way, I'll award the bounty accordingly. (Of course, you're free to try and beat any contenders ;).) Hope you're alright with that! –  Martin Büttner May 28 at 17:52

Ruby, 17 digits, 168 bytes

$><<[-~0,'.',9-3,3/3,2**3,$.,25%22,'   '=~/$/,2+7,2<<2,"10".oct,2|5,[2,2,2,2].size,[*$....2*5].last,(2^5).succ,'a'.to_i(25).pred,'aaaa'.count('a'),eval(55.chr.next)]*''

Ungolfed:

$><<[
  -~0,                # 1
  '.',                # .
  9-3,                # 6
  3/3,                # 1
  2**3,               # 8
  $.,                 # 0
  25%22,              # 3
  '   '=~/$/,         # 3
  2+7,                # 9
  2<<2,               # 8
  "#{'a'.hex}".oct,   # 8
  2|5,                # 7
  [2,2,2,2].size,     # 4
  [*$....2*5].last,   # 9
  (2^5).succ,         # 8
  'a'.to_i(25).pred,  # 9
  'aaaa'.count('a'),  # 4
  eval(55.chr.next)   # 8
]*''

Haven't been forced to do anything particularly clever yet, I may come back and add digits.

share|improve this answer
    
Thanks, fixed it. –  histocrat May 19 at 21:47
1  
"Haven't been forced to do anything particularly clever yet." Yeah, I figured Ruby, Perl and the usual suspects would not have a really hard time with 15 characters per digit, but I wanted to leave room for things like C-derivatives and Mathematica with large standard-libraries but more convoluted names. –  Martin Büttner May 19 at 21:50
    
"If they are really only aliases, no [you cannot use them]." succ and next are aliases. –  Doorknob 冰 May 20 at 0:25
    
The first is being called on a Fixnum, the second on a String, so I don't think they count as the same method. –  histocrat May 20 at 0:35
    
Ah, good point. However, the question also says "You must not refer to any... constant which you have used in code that generated an earlier digit," and you use $. twice. Although, gotta love $.... :D –  Doorknob 冰 May 20 at 2:11

Golfscript, 17 digits

A straightforward attempt. Golfscript may have a lot of non-alphanumeric one-letter built-ins, but it doesn't have many built-ins as a whole!

".",                         # 1: string length (separate from array length)
'.'    
3 3+                         # 6: addition
''[49]+                      # 1: string concatenation
-9~                          # 8: bitwise not
2!                           # 0: boolean not
7 4%                         # 3: modulus
4(                           # 3: decrement
7))                          # 9: increment
257 2/2/2/2/2/               # 8: division
4 2*                         # 8: multiplication
22 5- 5- 5-                  # 7: subtraction
2 2?                         # 4: power
[2 5] 2 base                 # 9: base conversion
[2 2 2 2 2 2 2 2],           # 8: array length (separate from str length)
[2 2 2 2 2 2 2 2 2 5]5?      # 9: array.find()
2 2+                         # 4: addition
"2 2*2*"~                    # 8: eval
share|improve this answer
2  
I think you could continue with 5,)\; # range, right uncons, flip, and pop. –  Peter Taylor May 22 at 17:43

Bash, 5 digits in 65 chars

I will update this soon! For now, it just prints 1.6180, and does not contain any digits.

false
tr -d ' '<<<$?.`wc -c<<<abcde``nl<<<' '``kill -l FPE`$(())

Explanation

The following methods are used to generate the digits:

1: exit status of false

6: string length

1: nl abuse

8: kill signal numbers

0: numeric value of an empty expression

share|improve this answer

Mathematica 9 8 digits, in 86 83 78 characters.

10`8FromDigits@#/10^Length@#&@{a/a,3!,-I I,2π/(45°),#&''[],Prime@2,Sqrt@9,4+5}

Output:

1.6180339
share|improve this answer
    
Ah, I knew I made a mistake somewhere.Prefix notation doesn't quite seem to work in this case. Using unicode Pi and Degree, does seem to still work. –  Tally May 23 at 15:13
    
Yeah, that #&''[] will generate an error from missing input, while in this form it ignores that it got no input. Still doesn't excuse me from not using it where it works though. –  Tally May 23 at 15:24
1  
Thx. I personally loved #&''[] (Basically the second derivative of f[x] = x –  Tally May 23 at 16:10
    
(Cleaned up the comments.) That is quite nice, but you could probably save a character, by replacing # with an allowed digit, and dropping one of the dashes. –  Martin Büttner May 23 at 16:29
    
Figured this way I'd be able to save that digit for potential future use. –  Tally May 23 at 17:49

Julia - 23 digits in 345 characters (15 per digit exactly)

print(div(2,2),'.','/'+7,length(" "),2^3,size([])[end],isqrt(9),int(cbrt(27)),54-45,'h'$'P',[2:22][7],endof("2222222"),count(isodd,[5,5,5,5]),search("Hello man",'n'),nextpow2(5),rsearch("Love boat",'t'),sizeof('й'),("I"summary(b"H"))[22],iceil(float(pi)),iround(cosh(e)),ifloor(exp(catalan)),cmp(5,5),itrunc(5sin(one(Int))),uint(erfcx(-ones())))

Output: 1.6180339887498948482045

I interpreted characters and strings as usable, so long as I did not re-use a specific character or string (characters in a string could be re-used, as long as the string was not); however, I did not permit myself to use the int value of a character directly. There is one non-ASCII character (й).

In a more readable fashion (not actual code):

1> div(2,2)
.> '.'
6> '/'+7
1> length(" ")
8> 2^3
0> size([])[end]
3> isqrt(9)
3> int(cbrt(27))
9> 54-45
8> 'h'$'P'
8> [2:22][7]
7> endof("2222222")
4> count(isodd,[5,5,5,5])
9> search("Hello man",'n')
8> nextpow2(5)
9> rsearch("Love boat",'t')
4> sizeof('й')
8> ("I"summary(b"H"))[22]
4> iceil(float(pi))
8> iround(cosh(e))
2> ifloor(exp(catalan))
0> cmp(5,5)
4> itrunc(5sin(one(Int)))
5> uint(erfcx(-ones()))
share|improve this answer
    
+1 for Julia! :) –  Martin Büttner May 23 at 16:34

C++ 12.4 chars per line, was 14 chars per line for each digit

Fixed my mistake of reusing operators.

#include <iostream>
#include <math.h>
#define S std::string
#define C(x) std::cout<<x
int main()
{
C(cos(0));
C(char(46));
C('j'%'d');
C('\0'+3-2);
C(sqrt('@'));
C(log(1));
C('c'/'!');
S s("xyz");
C(s.size());
return 0;
}

Not sure if using chars like this counts as char literals or not? If this code is acceptable it can be continued forever and char debt will be paid back.

#include <iostream>
#define C(x) std::cout<<x
int main()
{
C('b'-'a');//1
C(char(46));//.
C('g'-'a');//6
C('b'-'a');//1
C('i'-'a');//8
C('a'-'a');//0
C('d'-'a');//3
C('d'-'a');//3
C('j'-'a');//9
//etc
return 0;
}
share|improve this answer
    
The literals are fine (because they are not equivalent to single-digit numbers), but you keep reusing the - operator. Also, I like how you counted the comment for the line length. :D –  Martin Büttner May 21 at 20:18
    
Yes that looks much better, but you are using 1 to produce a 0 (which is disallowed, because the 1 appeared earlier in the golden ratio). Also you do need to count the #define S (not the other one), as it's not an include but just defining a shorthand alias. –  Martin Büttner May 22 at 20:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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