3
\$\begingroup\$

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!

\$\endgroup\$
14
  • 3
    \$\begingroup\$ I think the function you're looking for is abs. Python: for i in range(1, 10): print 5-abs(5-i), \$\endgroup\$
    – primo
    Jun 10, 2014 at 9:04
  • 11
    \$\begingroup\$ Just to give folks some background this was a "do my homework" question on SO 10 min ago... \$\endgroup\$
    – monocell
    Jun 10, 2014 at 9:10
  • 1
    \$\begingroup\$ This question appears to be off-topic because it looks too much like a homework assignment or "brain twister". \$\endgroup\$
    – user15259
    Jun 10, 2014 at 15:39
  • 4
    \$\begingroup\$ 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. \$\endgroup\$
    – cjfaure
    Jun 10, 2014 at 16:41
  • 1
    \$\begingroup\$ for(x=11111;x<=11111;x*=x);printf("%d\n", x); \$\endgroup\$ Jun 10, 2014 at 18:50

21 Answers 21

10
\$\begingroup\$

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),
\$\endgroup\$
5
  • \$\begingroup\$ 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 \$\endgroup\$ Jun 10, 2014 at 15:29
  • \$\begingroup\$ 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. \$\endgroup\$ Jun 10, 2014 at 16:55
  • 1
    \$\begingroup\$ @Marc // is integer divison in python. You're thinking of `\\`, where one backslash escapes the other. \$\endgroup\$ Jun 10, 2014 at 22:28
  • 1
    \$\begingroup\$ @steve Integer division is the default in python 2, in python 3 you specify it manually with //. \$\endgroup\$ Jun 10, 2014 at 22:29
  • 1
    \$\begingroup\$ 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! \$\endgroup\$
    – justhalf
    Jun 11, 2014 at 3:51
5
\$\begingroup\$

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

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

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

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.

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

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

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

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";
}
\$\endgroup\$
1
  • 4
    \$\begingroup\$ 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. \$\endgroup\$
    – Kyle Kanos
    Jun 10, 2014 at 13:05
3
\$\begingroup\$

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;
\$\endgroup\$
2
  • \$\begingroup\$ I would argue that to reverse a string you require another loop. But let OP decide on this. \$\endgroup\$
    – justhalf
    Jun 10, 2014 at 9:56
  • \$\begingroup\$ 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. \$\endgroup\$
    – Teun Pronk
    Jun 10, 2014 at 9:59
3
\$\begingroup\$

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.

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

Ruby - 47 chars

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

Edit - 33 chars

[*(1..4),[*(1..5)].reverse]*' '
\$\endgroup\$
2
  • \$\begingroup\$ to_a can be simplified using splats since Ruby 1.9.x or so. Also, look up Array#* \$\endgroup\$ Jun 10, 2014 at 16:42
  • \$\begingroup\$ @JanDvorak Made it 33 chars \$\endgroup\$
    – bsd
    Jun 10, 2014 at 16:47
2
\$\begingroup\$

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))) + " ");
      }
   }
}
\$\endgroup\$
2
\$\begingroup\$

Brainfuck, 83

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

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

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

JavaScript

function f(){
  for ( var i=1,j=5; j>0; ++i>j&&(--i,--i,--j) )
    console.log(i);
}
\$\endgroup\$
2
  • \$\begingroup\$ for(a=b=0;b++<9;)console.log(a+=(b<6)-(b>5)) \$\endgroup\$
    – nderscore
    Jun 11, 2014 at 4:55
  • \$\begingroup\$ How does this work? ++i>j&&(--i,--i,--j) \$\endgroup\$ Jan 12, 2015 at 14:18
2
\$\begingroup\$

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

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

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))
\$\endgroup\$
3
  • \$\begingroup\$ Two range will constitute as two loops, which is against the rule, I guess. \$\endgroup\$
    – justhalf
    Jun 10, 2014 at 9:55
  • \$\begingroup\$ @justhalf I was rather relying on range not counting as a loop :p \$\endgroup\$
    – Tal
    Jun 10, 2014 at 9:57
  • 1
    \$\begingroup\$ And by the way the fastest solution in Python should be print '1 2 3 4 5 4 3 2 1' :D \$\endgroup\$
    – justhalf
    Jun 10, 2014 at 10:07
1
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ Uses the function String.prototype.reverse \$\endgroup\$
    – MT0
    Jun 10, 2014 at 15:48
1
\$\begingroup\$

As 2.0

var num:Int = 11111;
alert(num*num);
\$\endgroup\$
1
\$\begingroup\$

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?"":" ");}?>
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I think that the ternary operator would count as an if statement \$\endgroup\$ Jun 11, 2014 at 4:41
  • \$\begingroup\$ Ah, you're right. I didn't notice that. \$\endgroup\$
    – bilde2910
    Jun 12, 2014 at 13:04
1
\$\begingroup\$

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;
}
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

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

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

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

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