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!
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.
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\$
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;
}
return-i
keyword :P
\$\endgroup\$
+++++++
+++++++
+++
+++
+++
+++
+++
++++++++++
++++++++++.
Or if you are not fun at parties:
+++++++[->+++++++<]>.
l
than a 1
.
\$\endgroup\$
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.)
# @: # @: #
(Spaces are optional)
\$\endgroup\$
Commented
Aug 26, 2014 at 7:37
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.
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 $?
.
$(pidof progname) < 1
\$\endgroup\$
Commented
Aug 2, 2013 at 17:10
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
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\$
?
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\$
This is one of my favorite Java specific question.
public static int ret1() {
try {
return 0;
} finally {
return 1;
}
}
try
block instantly fires finally
which returns 1 before the other return
statement can run.
\$\endgroup\$
function getOne() {
return -~![];
}
Explanation:
![]
evaluates to false
.~false
becomes -1
because false
is first casted to 0
, and ~0 == -1
.--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)))
// 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())
OO == good
or OO === good
?
\$\endgroup\$
Commented
Mar 24, 2014 at 18:41
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
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.
-"""
int getRandomNumber()
{
return 4; //chosen by fair dice roll.
//guaranteed to be random.
}
""".indexOf(4)
Doesn't contain 4
<?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);
}
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;
}
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
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.
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);
}
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.
In my opinion, the most elegant mathematical way to return 1 using Mathematica:
-Exp[I Pi]
The Euler Identity.
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.
C#
It should depend on hardware architecture:
return IntPtr.Size / (Environment.Is64BitOperatingSystem ? 8 : 4);
WOW!
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();
}
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]
is this simple enough?
(+!~~{})
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.
+TRUE
happens to give TRUE
.
\$\endgroup\$
Commented
Aug 1, 2013 at 6:41
FALSE + 1
, am I correct?
\$\endgroup\$
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.)
It even includes documentation on its parameters.
int
return_1
(x) int
x;{
/*x
can
be:
any
val
ue.
***/ return
!x?1:x /x;}
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\$