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.

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!

share|improve this question

closed as off-topic by squeamish ossifrage, Peter Olson, Yimin Rong, Ypnypn, Peter Taylor Jun 10 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.

3  
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 at 9:04
11  
Just to give folks some background this was a "do my homework" question on SO 10 min ago... –  monocell Jun 10 at 9:10
1  
This question appears to be off-topic because it looks too much like a homework assignment or "brain twister". –  Yimin Rong Jun 10 at 15:39
2  
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 at 16:41
1  
I don't understand why OP's accepted answer is as is, as it doesn't comply with the rules. –  justhalf Jun 11 at 3:49

21 Answers 21

up vote 5 down vote accepted

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.

share|improve this answer
    
I'm not sure whether Math.abs constitutes "another function" which is forbidden. haha –  justhalf Jun 10 at 9:58
2  
I was about to submit your latest example to lol –  Teun Pronk Jun 10 at 10:12
    
@justhalf latest version only explicitly calls the print function. –  Ourous Jun 10 at 10:23
1  
The last 3 versions appear to fail the stipulation "do not hardcode the output" –  Kyle Kanos Jun 10 at 13:03
3  
Doesn't seem particularly right, since these solutions either use hard-coded data or use another function (Math.abs). –  Tal Jun 10 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),
share|improve this answer
    
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 –  steveverrill Jun 10 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 at 16:55
1  
@Marc // is integer divison in python. You're thinking of `\\`, where one backslash escapes the other. –  undergroundmonorail Jun 10 at 22:28
1  
@steve Integer division is the default in python 2, in python 3 you specify it manually with //. –  undergroundmonorail Jun 10 at 22:29
1  
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 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

share|improve this answer
    
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 at 3:54
1  
Why hopping when you can use your both legs? :o) But I have to admit that your answer is better. –  cpri Jun 11 at 23:35
    
I like your analogy. +1 –  justhalf Jun 12 at 2:12

Golfscript, 16 characters

6,(;)1$-1%++' '*

I assume this is meant to be a code golf?

No variables. All data (two arrays and a number) is on the stack. The only loops are implicit ones.

Online demonstration: http://golfscript.apphb.com/?c=NiwoOykxJC0xJSsrJyAnKg%3D%3D

share|improve this answer

C++: Works finely in VC 11.0

#include <iostream>
#include <cstring>
#include <vector>
#include <conio.h>
#include <algorithm>

using namespace std;

bool called = false;
int main();
int f() {
    called = true;
    typedef vector<int>::iterator _v_interate;
    int l;
    static bool d;
    vector<int> iVector;
    for(l = 1; (true); (!d) ? l++ : l--) {
        _v_interate i = find(iVector.begin(), iVector.end(), 4);
        _v_interate i2 = find(iVector.begin(), iVector.end(), 3);
        _v_interate i3 = find(iVector.begin(), iVector.end(), 2);
        _v_interate i4 = find(iVector.begin(), iVector.end(), 1);
        _v_interate i5 = find(iVector.begin(), iVector.end(), 5);
        d =  (i != iVector.end()) &&  (i2 != iVector.end()) &&  (i3 != iVector.end()) &&  (i4 != iVector.end()) ? 1 : 0;
        iVector.push_back(l);
        cout << l << " ";
        (d && (l==1) ? main() : 0);
    }
    return 0;
}

int main() {
    !called ? f() : 0;
    _getch();
    exit(0); // Removing the exit(0) causes an infinite loop; I don't know why.
    return 0;
}

A simple solution:

#include <iostream>

void main() {
  cout << "1 2 3 4 5 4 3 2 1";
}
share|improve this answer
2  
Perhaps I'm mistaken on the count, but I count 10 variables in your first solution which is about 5x more than the maximum. And your second solution fails the "do not hardcode the output" stipulation. –  Kyle Kanos Jun 10 at 13:05

Delphi XE3

I dont think this requires much explaining right?

function p:string;
var
  i:integer;
begin
  for I:=1 to 4 do
    Result:=Format('%s%d ',[Result,I]);
  Result:=Format('%s%d%s',[Result,5,ReverseString(Result)]);
end;

In case it does. Function loops from 1 to 4, and keeps adding the number + [space].
Then it adds I again which became 5 which made it quit the loop and adds the reversed string as it is now.

Variation

function p:string;

const s='123454321' var i:integer; begin s:='123454321'; for I:=1to Length(s) do Result:=Format('%s %s',[Result,s[i]]); Exit(Trim(Result));
end; This might seem hardcoded but the constant doesnt have the spaces that are required.
Although it might seem impossible but there is a solution that is even lamer than this.

function p:string;
const
  s='123454321'
begin
  result:=Format('%s %s %s %s %s %s %s %s %s',[s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9]])  
  {or}  
  result:=Format('%s %s %s %s %s %s %s %s %s',[s[1],s[2],s[3],s[4],s[5],s[4],s[3],s[2],s[1]])
 {OR!}  
  result:=Format('%d %d %d %d %d %d %d %d %d',[1,2,3,4,5,4,3,2,1])
end;
share|improve this answer
    
I would argue that to reverse a string you require another loop. But let OP decide on this. –  justhalf Jun 10 at 9:56
    
hmm.. Fair point sir. But yes let the OP decide and hope he agrees with it :P ill see if I can come up with something else. –  Teun Pronk Jun 10 at 9:59

Perl

Version 1:

for(1..9){
    $x = ($_%18 - 5);
    print 5 - ($x, -$x)[$x < -$x] . " ";
}

Version 2:

for(1..9){
    $x = ($_%18 - 5);
    $x =~ s/-//;
    print 5 - $x . " ";
}

For both versions: 1 For loop, and 2 variables, $_ and $x, and I'm not using if or any other function.

share|improve this answer

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))
share|improve this answer
    
I get 107254321 jsfiddle.net/KnLJL –  Clyde Lobo Jun 10 at 15:28
    
what browser are you using? it works for me in firefox and chrome. –  koko Jun 10 at 15:32
1  
This answer is probably timezone-dependent. –  Josh Jun 10 at 16:16
1  
and hard-coded. –  MarcClintDion Jun 10 at 16:59
1  
Please add that to your answer –  Clyde Lobo Jun 11 at 9:22

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))) + " ");
      }
   }
}
share|improve this answer

Brainfuck, 83

+++++++[>+++++++>+++++++>+++++++>+++++++>+++++++<<<<<-]>.>+.>++.>+++.>++++.<.<.<.<.

Only 1 loop, no ifs (if you don't count the loop as an if). No int variables.

share|improve this answer

JavaScript

function f(){
  for ( var i=1,j=5; j>0; ++i>j&&(--i,--i,--j) )
    console.log(i);
}
share|improve this answer
    
for(a=b=0;b++<9;)console.log(a+=(b<6)-(b>5)) –  nderscore Jun 11 at 4:55

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

share|improve this answer

Ruby - 47 chars

(1..4).to_a.push((1..5).to_a.reverse).join ' '

Edit - 33 chars

[*(1..4),[*(1..5)].reverse]*' '
share|improve this answer
    
to_a can be simplified using splats since Ruby 1.9.x or so. Also, look up Array#* –  Jan Dvorak Jun 10 at 16:42
    
@JanDvorak Made it 33 chars –  bsd Jun 10 at 16:47

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))
share|improve this answer
    
Two range will constitute as two loops, which is against the rule, I guess. –  justhalf Jun 10 at 9:55
    
@justhalf I was rather relying on range not counting as a loop :p –  Tal Jun 10 at 9:57
1  
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 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!

share|improve this answer
    
Uses the function String.prototype.reverse –  MT0 Jun 10 at 15:48

As 2.0

var num:Int = 11111;
alert(num*num);
share|improve this answer

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?"":" ");}?>
share|improve this answer
1  
I think that the ternary operator would count as an if statement –  Peeyush Kushwaha Jun 11 at 4:41
    
Ah, you're right. I didn't notice that. –  bilde2910 Jun 12 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;
}
share|improve this answer

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
share|improve this answer

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.

share|improve this answer
    
Since I can't add an answer, another option would be "$(1..5+4..1)" –  Rynant Jun 11 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

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

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