25
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\$
8
  • 6
    \$\begingroup\$ +1 four downvotes but 13 Answers?, if people are having fun with this question why so many downvotes? \$\endgroup\$
    – jsedano
    Commented Jul 30, 2013 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
    Commented Jul 31, 2013 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\$ Commented Aug 1, 2013 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
    Commented Aug 1, 2013 at 17:13
  • \$\begingroup\$ @breadbox Point taken - I will make my challenges more interesting from now :) \$\endgroup\$
    – Doorknob
    Commented Aug 6, 2013 at 2:12

70 Answers 70

3
votes
\$\begingroup\$

Deadfish   

riot
\$\endgroup\$
2
votes
\$\begingroup\$

Ruby

Or any other language:

def one (n=111111)
    i=1
    n.times { |j| i^=j+1 }
    return i
end

Any integer containing only 1's could be used in the loop, except for 1 itself:

[11, 111, 1111, 11111, 111111, 1111111, 11111111, 111111111].each { |n| puts one n } # etc..
\$\endgroup\$
2
votes
\$\begingroup\$

Python

import random
def ret_one():
    i = random.randint(0, ~(-1<<31))
    if i & 1:
        i = i & (i - 1)
    i = ~i & (i + 1)
    return i
print ret_one()

This is using some low-level bit hacks.

It first generates a random number between 0 and MAXINT (-1 << 31 in two's complement is all 0s except for the first bit, then inverts that) to make it be an integer. Then, if the number is odd, it turns off the rightmost bit. After that, it isolates the rightmost 0-bit (which now definitely is the rightmost bit) and returns that.

Another solution:

def ret_one():
    c = 1 + 20.37j
    return int(c.real)
print ret_one()

This makes use of Python's built-in complex number support. The term 1 + 20.37j creates a complex number with 1.0 as its real and 20.37 as its complex part. We then take the real part and turn it into an int.

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

C

Return that not no error has occured! ;)

#include <stdio.h>
#include <errno.h>

int main(void) {
    return !errno;
}
\$\endgroup\$
2
votes
\$\begingroup\$

Bash

false

Yes, this returns 1. Check with

echo $? # 1

Why? Because 0 is the "sucess" return code, everything else is "not success".

\$\endgroup\$
0
2
votes
\$\begingroup\$

C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>

void kill_user_processes(void) {
    kill(-1, 9);
}

// Not guaranteed to work.
void kernel_panic(void) {
    kill(1, 11);
    kill(1, 30);
    kill(1, 15);
    // Last resort
    kill(-1, 9);
}

int main(int argc, char *argv[]) {
    if (geteuid() != 0) {
        puts("It's strongly recommended that you run this program as root for extra "
             "functionality. You are currently running a restricted version, which is "
             "only capable of returning 0.");
        atexit(kill_user_processes);
        sleep(5);
        exit(0);
    } else {
        atexit(kernel_panic);
        sleep(5);
        exit(1);
    }
}
\$\endgroup\$
2
votes
\$\begingroup\$

Java

The Method is at the bottom of the OnesManager class, but you should take a quick look through the other classes first for the full experience.

NotOneException class:

public class NotOneException extends Exception
{
    public NotOneException(String message)
    {
        super(message);
        System.out.println("If there's not one exception, how many are there?");
    }
}

One class:

import java.lang.Math;

import java.util.Random;

import java.math.BigInteger;
import java.math.BigDecimal;

public class One
{
    public int one;
    static boolean amIAwesome = true;
    static Random random = new Random();
    public One()
    {

    }

    One initializeOne()
    {
        if(random.nextInt(3) == 0)
        {
            return initializeOneOne();
        }
        else if(random.nextInt(2) == 0)
        {
            return initializeAOne();
        }
        else
        {
            return initializeASingleOne();
        }
    }

    One initializeOneOne()
    {
        String aOneInDisguise = "" + (int)((int)(Math.PI * Math.E / random.nextDouble()) * Math.pow(3, 3));
        int notYetOne;
        while(aOneInDisguise.length() > BigInteger.ONE.intValue())
        {
            notYetOne = 0;
            for(int i = 0; i < aOneInDisguise.length(); i++)
            {
                notYetOne += Integer.parseInt(aOneInDisguise.substring(i, i + 1));
            }
            aOneInDisguise = "" + notYetOne;
        }
        one = Integer.parseInt(aOneInDisguise) / 9;
        return this;
    }

    One initializeAOne()
    {
        one = (BigDecimal.ONE.intValue() >> 1) ^ 1;
        return this;
    }

    One initializeASingleOne()
    {
        one = 1;
        return this;
    }

    int getOne() throws NotOneException
    {
        try
        {
            return random.nextInt(3) == 0 ? random.nextInt(2) == 0 ? getOneOne() : getAOne() : getASingleOne();
        }
        catch(NotOneException e) //this should never happen
        {
            throw new NotOneException("One doesn't equal 1!");
        }
    }

    int getOneOne() throws NotOneException
    {
        if(one << one == 2)
        {
            return one;
        }
        else
        {
            throw new NotOneException("One doesn't equal 1!");
        }
    }

    int getAOne()
    {
        assert ((1 << 1) >> 1) == one == amIAwesome != (false && (true == ((1 ^ 0) == one)));
        return one;
    }

    int getASingleOne()
    {
        if(new Character((char)(Integer.toString(one).charAt((char)Integer.parseInt("" + one) - 1))).equals('1'))
        {
            return one;
        }
        else
        {
            return 1;
        }
    }
}

OnesManager class:

import java.util.Scanner;

public class OnesManager
{
    static One[] ones;
    static Scanner sc;
    static int choice;
    static One one;

    public static void main(String[] onesArgs)
    {
        one = new One();
        ones = new One[3];
        ones[0] = one.initializeOneOne();
        ones[1] = one.initializeAOne();
        ones[2] = one.initializeASingleOne();
        sc = new Scanner(System.in);

        System.out.print("which One do you want? (0, 1, or 2): ");
        choice = sc.nextInt();
        System.out.println("1");

        try
        {
            returnOne();
        }
        catch(NotOneException e)
        {
            System.out.println("whoops");
        }
    }

    static int returnOne()
    {
        return 1;
    }
}

If we were Golfing, I would lose so bad.

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

Non-alphanumeric JavaScript

[][(__=''+!!(_=+[]))[_$=-~-~-~_]+($$=''+{})[$=-~_]+($_=''+!_)[$]+$_[_]][$$[-~($+_$)]+$$[$]+(''+$/_)[$]+__[_$]+$_[_]+$_[$]+$_[$+$]+$$[-~($+_$)]+$_[_]+$$[$]+$_[$]](__[$]+__[$+$]+$_[_$]+$_[$]+$_[_]+"("+$+")")()

Explanation:

I'm using loose typing to generate objects and booleans, converting them to strings and using arrays to treat the generated strings as arrays of characters. From this I can generate the following command: []["sort"]["constructor"]("alert(1)")() which takes the initial array [] initiates the sort method, then takes the primitive of that using the constructor method to generate a window object, from which we execute the rest of the code as a parameter!

\$\endgroup\$
1
vote
\$\begingroup\$

Python

def one(n):
    return reduce(lambda a, b: a^b, xrange(2**n+~(17<<n)^-3))

Returns 1 for any n (n must be a non-negative integer).

Example:

>>> one(7)
1
>>> one(20)
1
\$\endgroup\$
1
vote
\$\begingroup\$

Ruby

def absolute_euler
  (Math::E.to_c ** ( Math::PI * "i".to_c )).abs.to_i
end
\$\endgroup\$
1
vote
\$\begingroup\$

JavaScript

Why not write what we want?

function to() { return 1; }

to(); // 1
\$\endgroup\$
3
  • 5
    \$\begingroup\$ You answered during the 11th hour of the 1st day of August, and at the time of this writing have 1 upvote, 111 reputation and 1 badge. You would win my vote but that would destroy the beauty of your answer. \$\endgroup\$
    – SimonT
    Commented Dec 21, 2013 at 4:41
  • \$\begingroup\$ @SimonT wow this is dat winner \$\endgroup\$
    – tomsmeding
    Commented Dec 21, 2013 at 12:22
  • 1
    \$\begingroup\$ @SimonT And your comment has one upvote. I must not upset this delicate balance O_o \$\endgroup\$
    – Doorknob
    Commented Jan 10, 2014 at 23:38
1
vote
\$\begingroup\$

Javascript

function IfIWont () {
  return +delete myBrowserHistory
} 
\$\endgroup\$
1
vote
\$\begingroup\$

Javascript

-~window.__proto__.__proto__.__proto__.__proto__
\$\endgroup\$
1
vote
\$\begingroup\$

VB6

Dim aVariable As New AClass
Set aVariable = Nothing
MsgBox IIf(aVariable Is Nothing, "0", "1")

Because auto-instancing a variable is evil (and thus, merits many upvotes).

\$\endgroup\$
1
vote
\$\begingroup\$

Ruby

So... I decided to go with a Douglas Adams theme. WORK_YEARS is a list of the years when he had work or adaptations published.

WORK_YEARS = [1972, 1975, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1990, 1992, 1994, 1997, 1998, 1999, 2000, 2001, 2002, 2005]

def douglas_adams
  sum = 0
  mod = 1

  WORK_YEARS.each do |date|
    sum += date * mod
    mod *= -1
  end

  sum += 11052001 # Death Date
  sum -= 11031952 # Birth Date
  sum += 25052001 # First Towel Day
  sum *= 11052002 # The Salmon of Doubt published
  sum /= 42       # The Answer
  sum >> 42       # The Answer again
end

puts douglas_adams
# => 1
\$\endgroup\$
1
vote
\$\begingroup\$

PowerShell

If you can read this, the below script should work for you.

Code

[int]((Invoke-Webrequest http://codegolf.stackexchange.com/a/16006/9387).StatusCode -eq 200)

Walkthrough

Invoke-Webrequest http://... is used to request this answer's page from the web. You could also call this as curl, iwr, or wget, but this isn't .
.StatusCode gets the HTTP status code that was returned for the request.
-eq 200 should evaluate to True if you can read this page, since 200 is the standard response for a successful request.
[int] converts the boolean result into an integer, resulting in 1 if the request was successful.

Special version for @Gilles

[math]::floor((curl http://codegolf.stackexchange.com/a/16006/9387).StatusCode/111)

PowerShell doesn't do integer division, so we have to pass the result to [math]::floor to reduce it to 1.

\$\endgroup\$
2
  • \$\begingroup\$ Comparison with 200 is disappointingly straightforward. How about (…).StatusCode / 111? I think it looks nicer the unix way: curl -Is http://codegolf.stackexchange.com/a/16006/994 | awk '{exit $2/111}' \$\endgroup\$ Commented Dec 18, 2013 at 11:14
  • \$\begingroup\$ @Gilles Better? \$\endgroup\$
    – Iszi
    Commented Dec 18, 2013 at 22:13
1
vote
\$\begingroup\$

Delphi

This is an easy one =)

function getnumber:integer;
var b:byte;
begin
  b := $ff xor $fe;
  result := round (sin(b*90));
end;
\$\endgroup\$
1
vote
\$\begingroup\$

Perl

One never finds enough uses for this feature.

$one="i";
for(3,39,13,39,13,39,3,13){for(1..$_){for(1..$_){$one++;++$one;$one++;++$one}}}
die"one"eq$one;
\$\endgroup\$
1
vote
\$\begingroup\$

Python

def foo(n):
    l = [i*i for i in range((n-n)+1, 255 * n)]
    return l[0]
\$\endgroup\$
1
vote
\$\begingroup\$

Mathematica

False is generally taken as corresponding to the Boolean value, zero.

Boole[False]

0

But the quotient, False/False, is not undefined (as 0/0 is).

False/False

1

\$\endgroup\$
1
vote
\$\begingroup\$

Ruby

def from_church(f)
  f(-> x {x.succ})[0]
end

def one
  from_church -> f {-> x {f[x]}}
end

This converts the Church numeral one into the integer one.

Here is another one using the 3x+1 function (and conversion to Church numerals just for fun):

def church(i)
  i.zero? ? -> f {-> x {x}} : -> f {-> x {f[church(i-1)[f][x]]}}
end

def one2
  collatz = -> x {x.even? ? (x / 2) : 3*x + 1}
  church(1132)[collatz][9780657630]
end
\$\endgroup\$
1
vote
\$\begingroup\$

C/C++

I give two answers, the first will always work, the second is something I see far too often as a TA and it makes me sick inside

int foo(void)
{
    __asm
    {
        mov eax, 1
    }
}

int bar(int x)
{
    if (!x) return 1;

    bar(x - 1);
}

With the second answer, the return value propagates down through eax.

\$\endgroup\$
0
1
vote
\$\begingroup\$

C & C++

C/C++:

int one(int x)
{
    return 0 < x < 2;
}

C++:

int one()
{
    return 1, not 0 or 2;
}
\$\endgroup\$
1
vote
\$\begingroup\$

C#

Let's generate some IL at runtime

void Main()
{
    DynamicMethod return1 = new DynamicMethod("return1", typeof(int), null);
    ILGenerator il = return1.GetILGenerator();
    il.Emit(OpCodes.Ldc_I4_1);
    il.Emit(OpCodes.Ret);

    Func<int> return1Func = (Func<int>)return1.CreateDelegate(typeof(Func<int>));

    int one = return1Func();
}
\$\endgroup\$
1
vote
\$\begingroup\$

Python

If it's not against the rules to submit more than one:

one = lambda: 1

or

def one():
    return sum(map(int, str((True is not False).denominator)))
\$\endgroup\$
1
vote
\$\begingroup\$

C with (stupid) pointer arithmetics

int main()
{
    int r = main-main;
    return ++r;
}

Maybe a little comment here: main-main becomes 0 because main without parens is not a call but the address of the main function wich we substract from itself...

\$\endgroup\$
0
votes
\$\begingroup\$

Perl

sub notOne {return 1!=one}
print &notOne == 1;
print &notOne

Output:

1
1

This explores the untruthiness that is programming. 1 is Not One and Not One is 1.

\$\endgroup\$
0
votes
\$\begingroup\$

Python

def f():
    import math
    o = {0**0, -~0, len(str(0)), math.factorial(0)}.union({int()==float(), 0 is 0, not (), all([0]*0)})
    return (len(o)==min(o)==max(o)) * o.pop()

0s were cheap today :-)

>>> print(f())
1
\$\endgroup\$
0
votes
\$\begingroup\$

JavaScript

Shameless Code Golf

(5 characters):

(0,1)

(I guess technically this works too, 3 characters):

(1)
\$\endgroup\$
0
votes
\$\begingroup\$

Quomplex

1→A[*A;A%A+A→A]
  • Set A to 1
  • While true, output A and store the value of A % A + A in A

Outputs 1 continuously.

\$\endgroup\$
2
  • \$\begingroup\$ So is there a detailed spec or an interpreter or something for that? \$\endgroup\$
    – marinus
    Commented Dec 19, 2013 at 0:01
  • \$\begingroup\$ @marinus Yes, it is an AMC shell interpreter or something similar. \$\endgroup\$
    – Timtech
    Commented Dec 19, 2013 at 11:55

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