# Print 123454321 without if statements and using only 2 variables [closed]

The challenge: Write a function, that delivers following output: "1 2 3 4 5 4 3 2 1".

Kids stuff? Of course. But here's the point:

• You only can use: 1 for loop, 2 int variables.

• You must not use: IF terms, another function, ...

• Do not hardcode the output

There are also some more restrictions to make this harder:

• No functions like abs or sth. else are allowed! (Yep, it's possible)
• No static output like echo "1 2 3 4 5 4 3 2 1"

This is a , so the answer with the most votes wins!

## closed as off-topic by squeamish ossifrage, Peter Olson, Yimin Rong, Ypnypn, Peter TaylorJun 10 '14 at 16:42

• This question does not appear to be about programming puzzles or code golf within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

• I think the function you're looking for is abs. Python: for i in range(1, 10): print 5-abs(5-i), – primo Jun 10 '14 at 9:04
• Just to give folks some background this was a "do my homework" question on SO 10 min ago... – monocell Jun 10 '14 at 9:10
• This question appears to be off-topic because it looks too much like a homework assignment or "brain twister". – Yimin Rong Jun 10 '14 at 15:39
• Fun fact! If you take the binary representation of the unicode string "1 2 3 4 5 4 3 2 1" and convert it into a base 10 number, it becomes 3922771099780750640552066885681. I wanted to generate this in some epic way and cout it with No Comment's @ operator, but turns out, it's prime. What. – cjfaure Jun 10 '14 at 16:41
• for(x=11111;x<=11111;x*=x);printf("%d\n", x); – Digital Trauma Jun 10 '14 at 18:50

# Cobra

## Really, this is quite trivial.

class Program
def main
for i in 10, Console.write(5 - Math.abs(5 - i))


Or

class Program
def main
v as int = 123454321
for i in v.toString, Console.write(i)


Or even simpler

class Program
def main
print 1, 2, 3, 4, 5, 4, 3, 2, 1


## But if you insist on following the question exactly:

class Program
def main
num as int = 123454321
for i in '[num]'
Console.write(i)
Console.write(' ')


This uses only one integer variable, only one loop, and the only function explicitly called is used for output.

• I'm not sure whether Math.abs constitutes "another function" which is forbidden. haha – justhalf Jun 10 '14 at 9:58
• I was about to submit your latest example to lol – Teun Pronk Jun 10 '14 at 10:12
• @justhalf latest version only explicitly calls the print function. – Οurous Jun 10 '14 at 10:23
• The last 3 versions appear to fail the stipulation "do not hardcode the output" – Kyle Kanos Jun 10 '14 at 13:03
• Doesn't seem particularly right, since these solutions either use hard-coded data or use another function (Math.abs). – Tal Jun 10 '14 at 13:29

## Python

One for loop, one int variable (i), no if, no other functions (unless you consider print or +-*/ as functions, haha):

for i in range(9):
print i+1 - 2*(i//5)*(i-4),

• This one gets my vote as it complies with ALL the rules, i.e. does not use any functions or extra variables. I think we can call print a procedure as we are not interested in its return value (I don't know if it returns a value in Python.) // is integer division in python? hmmm – Level River St Jun 10 '14 at 15:29
• Steveverrill, '//' one of the slashes is likely a directive for the print function to ignore the other slash. I think the idea here is that print functions will think the slash is a file system slash instead of a math operator. The double slash clears this up. – MarcClintDion Jun 10 '14 at 16:55
• @Marc // is integer divison in python. You're thinking of \\, where one backslash escapes the other. – undergroundmonorail Jun 10 '14 at 22:28
• @steve Integer division is the default in python 2, in python 3 you specify it manually with //. – undergroundmonorail Jun 10 '14 at 22:29
• I'm working with Python 2 and Python 3 sometimes, so to be sure that I'm doing integer division, I always use //, because it works in both Python 2 and Python 3. Thanks for all the votes! – justhalf Jun 11 '14 at 3:51

# C

No function, no hidden IF (abs, min, etc.)

#include <stdio.h>

int main()
{
int sum=0;
for (int i=3; i<12; i++)
{
sum += 1-2*(i/8);
printf("%d\n", sum );
}
}


Explanation : The 4th bit of i is the heart of the trick : it's 0 for [3,7] and 1 for [8,11].

i/8 gives the value of the bit (just like i>>3) for i in [3,11] it gives : 0, 0, 0, 0, 0, 1, 1, 1, 1

1-2*(i/8) is simple math to obtain 1, 1, 1, 1, 1, -1, -1, -1, -1

+= is used to sum the values

• This is another answer that fully complies with all the rules. I was thinking on something like this, but at the end I used another approach since why two int variables when you can only use one? :D – justhalf Jun 11 '14 at 3:54
• Why hopping when you can use your both legs? :o) But I have to admit that your answer is better. – cpri Jun 11 '14 at 23:35
• I like your analogy. +1 – justhalf Jun 12 '14 at 2:12

Javascript, 32 characters

+new Date(1970,0,2,11,17,34,321)


edit: not timezone-dependant, 42 chars

+new Date(Date.UTC(1970,0,2,10,17,34,321))

• I get 107254321 jsfiddle.net/KnLJL – Clyde Lobo Jun 10 '14 at 15:28
• what browser are you using? it works for me in firefox and chrome. – koko Jun 10 '14 at 15:32
• This answer is probably timezone-dependent. – Josh Jun 10 '14 at 16:16
• and hard-coded. – MarcClintDion Jun 10 '14 at 16:59
• Please add that to your answer – Clyde Lobo Jun 11 '14 at 9:22

print 5 - $x . " "; }  For both versions: 1 For loop, and 2 variables, $_ and $x, and I'm not using if or any other function. Ruby - 47 chars (1..4).to_a.push((1..5).to_a.reverse).join ' '  Edit - 33 chars [*(1..4),[*(1..5)].reverse]*' '  • to_a can be simplified using splats since Ruby 1.9.x or so. Also, look up Array#* – John Dvorak Jun 10 '14 at 16:42 • @JanDvorak Made it 33 chars – bsd Jun 10 '14 at 16:47 Java Used one loop and the loop variable. Added a constant for the upper bound. public class Test { private static final int BOUND = 5; public static void main(String[] args) { for (int i = 1; i < BOUND * 2; i++) { System.out.print(i - (2 * ((i % BOUND) * (i / BOUND))) + " "); } } }  # Brainfuck, 83 +++++++[>+++++++>+++++++>+++++++>+++++++>+++++++<<<<<-]>.>+.>++.>+++.>++++.<.<.<.<.  Only 1 loop, no ifs (if you don't count the loop as an if). No int variables. # JavaScript function f(){ for ( var i=1,j=5; j>0; ++i>j&&(--i,--i,--j) ) console.log(i); }  • for(a=b=0;b++<9;)console.log(a+=(b<6)-(b>5)) – nderscore Jun 11 '14 at 4:55 • How does this work? ++i>j&&(--i,--i,--j) – Arturo Torres Sánchez Jan 12 '15 at 14:18 # C Not sure if it follows exactly the rules but my answer is below int main() { int x; for(x = 123454321; x > 10; x /= 10) { printf("%d ", x % 10); } printf("%d", x); return 0; }  Run the code Well, I guess the fastest and most naive solution (in Python) would be: ' '.join (str(x) for x in range(1,6)) + ' ' + ' '.join (str(x) for x in range(4,0,-1))  • Two range will constitute as two loops, which is against the rule, I guess. – justhalf Jun 10 '14 at 9:55 • @justhalf I was rather relying on range not counting as a loop :p – Tal Jun 10 '14 at 9:57 • And by the way the fastest solution in Python should be print '1 2 3 4 5 4 3 2 1' :D – justhalf Jun 10 '14 at 10:07 # Javascript This might not be the best and fastest way to do it, but I like what I came up with. z = ''; for (x = 1; x <= 5; x++) { // Don't need a loop, but hey, I like loops! z += x + ' '; // Creates "1 2 3 4 5 " } document.getElementById('result').innerHTML = z + z.split("").reverse().join("").substring(2, 10); // "1 2 3 4 5 " + " 4 3 2 1"  Result: 1 2 3 4 5 4 3 2 1  You can see it in action Here! • Uses the function String.prototype.reverse – MT0 Jun 10 '14 at 15:48 As 2.0 var num:Int = 11111; alert(num*num);  ## Java, 79 chars (standalone: 131 chars) int b=-1,i=1;for(;i>0&(i<5||(b=1)==1);i-=b){System.out.print(i+(b==i?"":" "));}  Uses two ints, and no other variables. No if statements, just a for loop for evaluation. This will run on its own when put in the main(String[] args) method in a class, or in any other function. The full code, including class declaration and method, is 131 chars. public class M{public static void main(String[]a){int b=-1,i=1;for(;i>0&(i<5||(b=1)==1);i-=b){System.out.print(i+(b==i?"":" "));}}}  While I'm at it: ## PHP, 70 chars (standalone: 78 chars) $b=-1;for($i=1;$i>0&($i<5||($b=1)==1);$i-=$b){echo$i.($b==$i?"":" ");}  Uses same method as Java. Standalone script is 62 chars: <?php$b=-1;for($i=1;$i>0&($i<5||($b=1)==1);$i-=$b){echo$i.($b==$i?"":" ");}?>  • I think that the ternary operator would count as an if statement – Peeyush Kushwaha Jun 11 '14 at 4:41 • Ah, you're right. I didn't notice that. – bilde2910 Jun 12 '14 at 13:04 C #include <stdio.h> int main(void) { int i; for (i = 21911761; i > 0 && printf("%d", i&7); i = i>>3) i > 1 && printf(" "); return 0; }  # Fortran 90: 60 integer::j(9)=5;do i=1,4;j(i)=i;j(10-i)=i;enddo;print*,j;end  If you wanted it formatted slightly better, I can add a few characters to make the print statement print'(9i2)',j. Ungolfed & written properly, this is program main implicit none integer :: i, j(9) j = 5 do i=1,4 j(i) = i j(10-i) = i enddo print *,j end program main  # Powershell ((1..9)|%{$_ = ($_%18-5) 5 - @($_,-$_)[$_ -lt -$_] })-join ' '  1 variable, no if, no functions (unless you were to count -join which is just for displaying the data... Explanation: Loops from 1 to 9, then for each value calculates the reminder of the current value by 18, then subtracts 5 and assigns it to the currently used $_ variable. After that it evaluates $_ < -$_ (this is to handle negative values), and uses the result (False/True) to get the value from the array @($_,-$_), therefore making sure we always get a positive number in this case, after that it subtracts this number to 5 and finally joins the results with space.

• Since I can't add an answer, another option would be "\$(1..5+4..1)" – Rynant Jun 11 '14 at 13:24

# Scala, 53

(4 to 12).foldLeft(1)((a,b)=>{print(a);a+1-2*(b/8)})


I stole the neat bit shifting idea from @cpri

http://scalafiddle.net/console/3b3fff6463464959dcd1b68d0320f781

• This fits the rules better: (1 to 9).map(x => 5-Math.abs(5-x)).mkString(" ") – user24909 Jun 10 '14 at 16:20
• If you found a shorter code, you can edit your answer to update the code. – ProgramFOX Jun 10 '14 at 16:34