28
votes
\$\begingroup\$

The Task

Create a function/subroutine which returns 1. You can make it as elaborate as you like, as long as it returns 1.

The Rules

The entry with the most upvote wins - just like any popularity contest. Good luck!

\$\endgroup\$

closed as too broad by Gareth, undergroundmonorail, TimWolla, Milo, mniip Mar 25 '14 at 2:56

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

locked by Alex A. Feb 10 '16 at 18:22

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. See the help center for guidance on writing a good question.

Read more about locked posts here.

  • 6
    \$\begingroup\$ +1 four downvotes but 13 Answers?, if people are having fun with this question why so many downvotes? \$\endgroup\$ – jsedano Jul 30 '13 at 22:48
  • \$\begingroup\$ 13 answers, but only two of them have garnered any votes. Perhaps this is our version of the emacs vs vi question -- one where everyone has an answer but none of them are particularly better than another. \$\endgroup\$ – breadbox Jul 31 '13 at 19:16
  • 5
    \$\begingroup\$ @anakata, because four (make that six now) people think that this is the kind of question they think would have been better not posted. Some people are against popularity-contest on principle, and this is scraping the bottom of that category. \$\endgroup\$ – Peter Taylor Aug 1 '13 at 10:55
  • 1
    \$\begingroup\$ This is one of those places where codegolf fits uneasily into the stackexchange format. Compare the Collatz Conjecture, which is also trending right now. The answers are all pretty mundane (no offense), because it's not a good problem for creative golfing — the naive approach is also the shortest. Whereas in this question, the popularity-contest allows all kinds of interesting answers to a very trivial task. Far more enjoyable to read — but stackexchange is supposed to avoid open-ended stuff like this. Thus the downvotes. \$\endgroup\$ – breadbox Aug 1 '13 at 17:13
  • \$\begingroup\$ @breadbox Point taken - I will make my challenges more interesting from now :) \$\endgroup\$ – Doorknob Aug 6 '13 at 2:12

70 Answers 70

37
votes
\$\begingroup\$

Golf Script

1

It took a long time to optimise this code to its most pure, and dare I say it - beautiful form. Such elegance of the language does not come without years of dedicated practice. The program that, without a Zero-Instruction-Set-Computer can literally never be compressed any further. My entire code golf career has been leading to this moment.

I am free. I am alive.

I see the code that underlies the universe.

\$\endgroup\$
  • 3
    \$\begingroup\$ Can you write a program that only uses a single bit? \$\endgroup\$ – Kevin - Reinstate Monica Dec 19 '13 at 5:16
  • \$\begingroup\$ @Kevin Only in Minecraft (I've done it before - made a 3x5 px screen and everything). \$\endgroup\$ – Timtech Jan 12 '14 at 17:20
  • 1
    \$\begingroup\$ without a Zero-Instruction-Set-Computer can literally never be compressed any further. Our current computers can easily handle 0 instructions programs. All you need a language that has: "The empty program returns 1" in its specification \$\endgroup\$ – Cruncher Aug 11 '14 at 20:02
36
votes
\$\begingroup\$

C

Two examples, using obscure language features such as “strong return” (return!) and the “approaches” operator (-->):

int foo(void) {
    return! 0;
}
int bar(void) {
    int i=7;
    while (i --> 0);
    return-i;
}
\$\endgroup\$
34
votes
\$\begingroup\$

Brainfuck

+++++++
+++++++
    +++
    +++
    +++
    +++
    +++
++++++++++
++++++++++.

Or if you are not fun at parties:

+++++++[->+++++++<]>.
\$\endgroup\$
  • 2
    \$\begingroup\$ That looks more like a lowercase l than a 1. \$\endgroup\$ – Joe Z. Mar 18 '15 at 0:49
26
votes
\$\begingroup\$

APL

one ← {⍴⍴⍴⍵}

gives you the dimensions of a vector. The dimension of that is always one-dimensional, so the dimension of that is always one. Or:

"Rho, rho, rho of X
Always equals one,
Rho is dimension; rho rho, rank
APL is fun!"

(I didn't write that verse, it's Stallman's.)

\$\endgroup\$
  • 2
    \$\begingroup\$ I have learned the Modern Major Generals Song, sung the Money song by Monty Python and Still Alive from Portal... and that is still the nerdiest song that has ever been stuck in my head. Good find marinus! A good verse Stallman! \$\endgroup\$ – lochok Aug 22 '13 at 9:28
  • \$\begingroup\$ The same thing in J: # @: # @: # (Spaces are optional) \$\endgroup\$ – ɐɔıʇǝɥʇuʎs Aug 26 '14 at 7:37
21
votes
\$\begingroup\$

Java

public static int funWithOne() {
    try {
        try {
            return funWithOne();
        } finally {
            return funWithOne();
        }
    } catch (Throwable _) {
        return 1;
    }
}

This will call itself 21024 times (this number may vary on different platforms) before finally returning 1. Don't hold your breath, though; it will easily take much longer than the age of the universe.

\$\endgroup\$
  • 3
    \$\begingroup\$ "This will call itself 2^1024 times" Why? I think its a stack issue. Try to call yourself until you run out of stack, then do it again, and again? \$\endgroup\$ – user8777 Aug 9 '13 at 6:24
  • \$\begingroup\$ @LegoStormtroopr there's some try finally stuff here that keeps the stack low, but still has a lot of calls \$\endgroup\$ – Cruncher Dec 18 '13 at 15:05
  • 2
    \$\begingroup\$ @LegoStormtroopr See this. \$\endgroup\$ – arshajii Dec 19 '13 at 1:19
20
votes
\$\begingroup\$

Fish

x sends the program counter in a random direction. # is a wall that the program counter "bounces" off. This will literally wander around aimlessly until it finds the "^" and then print 1 and finish.

xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxx###xxxxxxxxxxxxxx
xxxxxxxxxx#;#xxxxxxxxxxxxxx
xxxxxxxxxx#n#xxxxxxxxxxxxxx
xxxxxxxxxx#1#xxxxxxxxxxxxxx
xxxxxxxxxx#^#xxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
\$\endgroup\$
  • \$\begingroup\$ +1 for both tiring the interpreter and letting other ><> pee in their pants. Lol. \$\endgroup\$ – tomsmeding Dec 21 '13 at 12:16
  • \$\begingroup\$ It's nice how this is easily translated into Befunge 98; simply change every x into a ?, every # into a r, n into . and ; into @. However, this ><> program looks better than the equivalent Befunge. Translation shown here: ideone.com/ZyuSKk \$\endgroup\$ – Justin Jan 15 '14 at 5:49
  • \$\begingroup\$ Maybe I like this too much; here is another Befunge, but this one takes ~4 million operations to finish. I imagine that it can be directly translated into ><> by changing every ? into a x and every # into a ! (should work fine when left the same too) and (of course) . to n and @ to ;. ideone.com/gfApjT \$\endgroup\$ – Justin Jan 15 '14 at 6:11
  • \$\begingroup\$ @Quincunx looks like it should take about 2^10 tries, with an expected number of operation per try at about 10. This gives me about 2000 operations. Am I missing something? \$\endgroup\$ – Cruncher Mar 7 '14 at 16:01
  • \$\begingroup\$ @Quincunx Nevermind, it's 4^10. Got it. lol. FYI, I'm pretty sure that code can be minimized greatly and still do the same thing. \$\endgroup\$ – Cruncher Mar 7 '14 at 16:02
19
votes
\$\begingroup\$

Unix Shell (Bourne, POSIX, bash, ksh, csh, …)

expr 0

This prints 0 but returns 1, which may come as a surprise to programmers used to other languages. You can turn off the printed output and see the return code by running expr 0 >/dev/null; echo $?.

\$\endgroup\$
  • 1
    \$\begingroup\$ I've been bit by this before. You want to know if a process exists? $(pidof progname) < 1 \$\endgroup\$ – Mr. Llama Aug 2 '13 at 17:10
18
votes
\$\begingroup\$

Java

This is one of my favorite Java specific question.

public static int ret1() {
    try {
        return 0;
    } finally {
        return 1;
    }
}
\$\endgroup\$
  • \$\begingroup\$ I don't get it... \$\endgroup\$ – The Guy with The Hat Jan 14 '14 at 14:57
  • 5
    \$\begingroup\$ Trying to return in a try block instantly fires finally which returns 1 before the other return statement can run. \$\endgroup\$ – PsHegger Jan 14 '14 at 17:31
  • \$\begingroup\$ Ah, okay. Thanks! \$\endgroup\$ – The Guy with The Hat Jan 14 '14 at 19:29
  • \$\begingroup\$ Returning in a finally block should throw a compile error. I can't think of any legitimate use case for doing it. \$\endgroup\$ – Cruncher Aug 11 '14 at 20:00
  • \$\begingroup\$ In C# it does throw compile error, but in Java it is possible. Of course it doesn't mean it's useful, neither can I think of any legitimate use case \$\endgroup\$ – PsHegger Aug 11 '14 at 20:02
16
votes
\$\begingroup\$

JavaScript

function getOne() {
    return -~![];
}

Explanation:

  • first ![] evaluates to false.
  • then ~false becomes -1 because false is first casted to 0, and ~0 == -1.
  • finally, --1 evaluates to 1.

Alternate:

return +!([][~~{}])

Crazy alternate (each line is exactly 80 chars long):

this[693741..toString(36)]('acnuftiao nobcbdaterbaurn +abeba!!be'.replace(/b./g,
function(b){return '{}()'.split('')['aecd'.split('').indexOf(b.charAt(1))]})[''+
'replace'](new RegExp('a'+Array(5).join('(.)'),'g'),(a='$')+'4321'.split([]+[]).
join(a)))
\$\endgroup\$
  • 1
    \$\begingroup\$ -~{}+[] is another approach. {}+[] evaluates to 0. \$\endgroup\$ – tristin Dec 17 '13 at 22:15
16
votes
\$\begingroup\$

JavaScript

// we all know that OOP == good
function OneManager() {
    // constants == good too
    this.values = {
        ERROR: -1, // value on error
        ONE: 1 // desired value
    }
    this.value = this.values.ERROR // set the value to ERROR
    this.setValue = function(num) {
        if (typeof num !== "number") throw new Error('cannot set value to non-number')
        if (!this.value) this.value = this.values.ERROR // oh noes
        else this.value = num
    }
}
// initialize the one
OneManager.prototype.initializeOne = function() {
    this.setValue(this.values.ONE) // set the value to ONE
    return true // return true for success
}
// get the value
OneManager.prototype.getValue = function() {
    if (this.value == this.values.ERROR) { // if the value is ERROR
        throw new Error('value not initialized')
    } else return this.value // return the value
}

function getOne() {
    var m = new OneManager() // make a OneManager
    var success = m.initializeOne() // initialize the value
    if (success) return m.getValue() // return the value
    else  {
        // there was an error in the initialization
        var retVal = m.values.ERROR // we will return an error
        delete m // maybe it's corrupted
        return retVal // return an error
    }
}

alert(getOne())
\$\endgroup\$
  • 4
    \$\begingroup\$ That's one robust piece of code you got here. \$\endgroup\$ – mveroone Jan 3 '14 at 13:59
  • \$\begingroup\$ @Kwaio I lost it reading your comment \$\endgroup\$ – Newbrict Mar 24 '14 at 7:14
  • \$\begingroup\$ OO == good or OO === good? \$\endgroup\$ – JoshWillik Mar 24 '14 at 18:41
  • 3
    \$\begingroup\$ @JoshWillik: Yes. ;-) \$\endgroup\$ – Doorknob Mar 24 '14 at 18:43
12
votes
\$\begingroup\$

Haskell & The Church of the ADT

data One = One deriving (Eq, Ord, Bounded, Enum, Show, Read)

This defines the one true One. This One is both the type denoting Oneness, and the constructor One, which is itself the nullary function that returns the one true, and only one value of type One, which is, behold, One.

Usage in the ghci REPL:

λ: One                  -- One returns the one true One
One
λ: One == One           -- One is equal to itself, as no others are 
True
λ: One < One            -- One is no less than itself
False
λ: minBound :: One      -- One is the least One there is, yet it is all you need
One
λ: maxBound :: One      -- One is as big as the universe of One, it is omnipotent
One
λ: [ One .. One ]       -- One is the beginning, and ending, of all that is One
[One]
λ: show One             -- The textual gospel of One
"One"
λ: read "One" :: One    -- To read the word of One, is to become one with One
One

The full Book of One is now on-line. Loading it gets you both testaments: Computation and Arithmetic. This enables you to explore more truths:

λ: One + One            -- One can only add to its magnificence
One
λ: negate One
*** Exception: One cannot be negated, mortal fool!

λ: One `div` One        -- One is indivisible
One
λ: One `mod` One
*** Exception: Nothing can modulate the power of One

λ: toRational One       -- Ye shall know One as both Numerator and Denominator
1 % 1
λ: toInteger One * 42   -- One multiplies all to wholeness
42
λ: toRational One / 2   -- Even divided, One is on top
1 % 2
\$\endgroup\$
9
votes
\$\begingroup\$

Groovy

-"""
int getRandomNumber()
{
    return 4;   //chosen by fair dice roll.
                //guaranteed to be random.
}
""".indexOf(4)

Doesn't contain 4

\$\endgroup\$
  • \$\begingroup\$ I think i've seen this on xkcd. \$\endgroup\$ – mveroone Jan 3 '14 at 14:02
  • 1
    \$\begingroup\$ Yes, that was the idea :) \$\endgroup\$ – Fels Jan 6 '14 at 8:31
8
votes
\$\begingroup\$

Perl

sub ret1 { print $->$= }

(Despite appearances, the function doesn't print anything.)

I know Perl programmers like to say TMTOWTDI, but this is a task for which T really MTOWTDI.

\$\endgroup\$
8
votes
\$\begingroup\$

PHP

<?php
function getOne() {
  return 0 + "one" == 0;
}

Edit:

If you prefer a longer one, here's an alternative (it doesn't print anything):

<?php
function getOne() {
    return print('the' + 'integer' + 'between' + 0 and 2);
}
\$\endgroup\$
8
votes
\$\begingroup\$

C

float one(void)
{
    const int n = 24; // magic number
    float x = 0.5f;
    float y = x;
    int i;

    for (i = 0; i < n; ++i)
    {
        x *= 0.5f;
        y += x;
    }
    return y;
}
\$\endgroup\$
  • \$\begingroup\$ How did you come up with this? \$\endgroup\$ – Saurabh Rana Dec 20 '13 at 19:23
  • 4
    \$\begingroup\$ It's the geometric series 1/2 + 1/4 + 1/8 + ... = 1. \$\endgroup\$ – Casey Chu Dec 21 '13 at 2:44
  • 2
    \$\begingroup\$ and it loops 24 times because float has 24 bits of precision \$\endgroup\$ – phuclv Jun 4 '14 at 5:09
7
votes
\$\begingroup\$

Rhetorical Java

You didn't say it had to be an integer 1.

float one_F(){
    return FloatFactoryFactory.getInstance(FloatFactoryFactory.
    defaultInstanceDescriptionString).getFactory(Locale.getLocale
    ("en-US")).createBuilder().setString("1.0").getResult();
}

Source: http://bash.org/?946461

\$\endgroup\$
7
votes
\$\begingroup\$

JavaScript (ECMAScript really)

function one() { return Number.length; }

Time for some spec porn.

Section 15.7.3 states that the length property of the Number constructor is 1 (and we know that a constructor is a function object as mentioned in 4.3.4), and that's because section 15.3.5.1 says:

The value of the length property is an integer that indicates the “typical” number of arguments expected by the function. However, the language permits the function to be invoked with some other number of arguments.

…and since the Number constructor's typical number of arguments is 1, the length of Number is 1. So one could say that the length of a number in Javascript is 1.

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

Perl

sub one{ $a[@a{@a[%a=map{@$a[@a{$a++=>$a}]+++$#$a+$a=>$a}$a]++}+$a] }

Open wide and say aaaaa.

The creative concept was to nest braces inside brackets inside braces... as deeply as possible, while still returning the desired result, and only using a "one" variable ($a, @a, %a, @$a and $#$a are of course all different variables).

Although this does modify its environment significantly, it will always return 1 on subsequent calls. To get a grasp of what it's doing, you might consider running this code:

use Data::Dump qw(dump);
for (1..8) {
  one();
  dump(@a);
  dump(%a);
  dump(@$a);
}
\$\endgroup\$
6
votes
\$\begingroup\$

Tcl

proc return1 {} {
    catch {(5+2-3)/4}
}

Does not work as you might think.

(5+2-3)/4 is not a valid command, so it throws an error (return -code 1), catch returns this number.

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

MATHEMATICA

In my opinion, the most elegant mathematical way to return 1 using Mathematica:

-Exp[I Pi]

The Euler Identity.

\$\endgroup\$
5
votes
\$\begingroup\$

Java

public class print {
    public static char getNum() throws Exception{
        String method = print.class.getSimpleName()+Splitter.class.getDeclaredMethods().length;
        return (char)Splitter.class.getMethod(method).invoke(null);
    }
}
class Splitter{
    public static char print1(){
        return P.getNum();
    }
}
class P{
    public static char getNum(){
        String s = Thread.currentThread().getStackTrace()[P.class.getDeclaredMethods().length].getMethodName();
        return s.charAt(s.length()-P.class.getSimpleName().length());
    }
    public void doNothing(){}
}

Can be adjusted to return any other positive number n by adding the methods printX for X from 1 to n into Splitter. For example, modifying Splitter to

class Splitter{
    public static char print1(){
        return P.getNum();
    }
    public static char print2(){
        return P.getNum();
    }
}

Will return '2', without any other changes necessary. The added methods should, apart from the name, be an exact duplicate of print1. Uses reflection to get the number of methods in splitter, and call a function with that name. P.getNum, which is then called, reads the stack trace and parses out the last character in the calling method, and displays it.

Calling print.getNum() return the character '1'

Edit - modified to use no String/integer/etc literals.

\$\endgroup\$
5
votes
\$\begingroup\$

C#

It should depend on hardware architecture:

return IntPtr.Size / (Environment.Is64BitOperatingSystem ? 8 : 4);

WOW!

\$\endgroup\$
5
votes
\$\begingroup\$

C#

Merging this (controversial) one with the neighboring (controversial) Collatz Conjecture:

public int CollatzOne()
{
    var current = new BigInteger(new Random().Next(1, Int32.MaxValue));
    var history = new[] { new BigInteger(-1), new BigInteger(-1), new BigInteger(-1) };
    do
    {
        history[0] = history[1];
        history[1] = history[2];
        history[2] = current;
        if (current.IsEven)
            current /= 2;
        else
            current = current * 3 + 1;
    } while (current != history[0]);
    return (int)history.Min();
}
\$\endgroup\$
5
votes
\$\begingroup\$

Ruby

Abusing the RNG...

Random.new(56417).rand(10000)

Generates a "random" number between 0 and 10000, and because I picked the right seed it just so happens to be 1. ;)

Script I used to find the number:

irb(main):001:0> (1..100000).select{|x|Random.new(x).rand(10000) == 1}
=> [14033, 25845, 35101, 36955, 45334, 56417, 87438, 87460, 99178, 99451]
\$\endgroup\$
5
votes
\$\begingroup\$

Javascript 8 bytes

is this simple enough?

(+!~~{})
\$\endgroup\$
  • \$\begingroup\$ Returns can only be used in a function. Just saying. \$\endgroup\$ – Mama Fun Roll Feb 6 '16 at 4:54
  • \$\begingroup\$ @ӍѲꝆΛҐӍΛПҒЦꝆ fixed ;D \$\endgroup\$ – dhazelett Feb 8 '16 at 17:03
4
votes
\$\begingroup\$

R

A classic:

TRUE + 0

+ tries to coerce its argument to a common type: here, because of the order of precedence, it coerces to integers. The coercion of TRUE to an integer gives 1.

\$\endgroup\$
  • \$\begingroup\$ Would +TRUE not work? \$\endgroup\$ – Griffin Jul 31 '13 at 16:13
  • 1
    \$\begingroup\$ @Griffin +TRUE happens to give TRUE. \$\endgroup\$ – plannapus Aug 1 '13 at 6:41
  • \$\begingroup\$ Also FALSE + 1, am I correct? \$\endgroup\$ – Timtech Jan 12 '14 at 17:27
  • \$\begingroup\$ @Timtech yes you are. \$\endgroup\$ – plannapus Jan 13 '14 at 7:54
4
votes
\$\begingroup\$

Turing Machine

Single-state Turing machine with B as the blank symbol, computes 1 (= 0.111... in base 2):

q B 1 R q

(This follows Turing's convention of starting with a blank tape, and prefixing '0.' to the generated infinite sequence.)

\$\endgroup\$
4
votes
\$\begingroup\$

C

It even includes documentation on its parameters.

    int
  return_1
(x)     int
       x;{
      /*x
     can
    be:
  any
 val
ue.
***/ return
!x?1:x /x;}
\$\endgroup\$
  • \$\begingroup\$ But that's a 2! \$\endgroup\$ – Joe Z. Apr 2 '14 at 17:00
  • 1
    \$\begingroup\$ So? It's fully documented! \$\endgroup\$ – Michael Hampton Apr 2 '14 at 17:32
3
votes
\$\begingroup\$

Python

one = lambda zero = 0o11: zero > 1 and all(one(zero-1) for l in '1111111111') and 1 or one and zero or one()

one() will call itself 111,111,111 times, each time returning 1, before returning a final value of 1.

You can also specify the number of digits. For example, one(3) will return 1 only 111 times.

I might add an explanation later, but I really don't have time at the moment.

\$\endgroup\$
3
votes
\$\begingroup\$

R

NA ^ 0

Any number to the power of 0 is 1.

\$\endgroup\$

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