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.

Challenge

Your task in this question is to write a program or a named function which takes a positive integer n (greater than 0) as input via STDIN, ARGV or function arguments and outputs an array via STDOUT or function returned value.

Sounds simple enough ? Now here are the rules

  • The array will only contain integers from 1 to n
  • Each integer from 1 to n should be repeated x times where x is the value of each integer.

For example:

Input:

5

Output:

[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

The array may or may not be sorted.

This is so winner is shortest code in bytes.

Bonus

Multiply your score by 0.5 if no two adjacent integers in your output array are same.

For example for n = 5, one such configuration would be

[5, 4, 5, 4, 3, 4, 5, 2, 5, 3, 1, 2, 3, 4, 5]
share|improve this question

21 Answers 21

Pyth, 9 * 0.5 = 4.5 bytes

smrhQhdUQ

With help from @FryAmTheEggman

Try it online.


Explanation

s             reduce + on list
 m            map
  rhQhd       lambda d: reversed(range(d+1, Q+1)), over
       UQ     range(Q)

where Q is the input.

share|improve this answer
4  
Shouldn't have helped you :D –  FryAmTheEggman 6 hours ago

Ruby (recursive), 41 bytes * 0.5 = 20.5

def n(n,i=1);i>n ?[]:n(n,i+1)+[*i..n];end

Or using a lambda (as recommended by histocrat): 37 bytes * 0.5 = 18.5

$n=->n,i=1{i>n ?[]:$n[n,i+1]+[*i..n]}

(call using $n[argument])

share|improve this answer
2  
That's a really cool solution. You can save some bytes by making it a lambda instead of a method (n=->x,i=1{...n[x,i+1]...) and a few more with [*i..n]. –  histocrat 6 hours ago

C# - 81bytes (161bytes * 0.5)

Simple job in C#, hopefully gets the no-neibouring-numbers bonus. Reads an int from stdin, writes out an array like the example to stdout.

class P{static void Main(){int n=int.Parse(System.Console.ReadLine()),m=n-1,i;var R="["+n;for(;m-->0;)for(i=m;i++<n;)R+=", "+i;System.Console.WriteLine(R+"]");}}

More readable:

class P
{
    static void Main()
    {
        int n=int.Parse(System.Console.ReadLine()),m=n-1,i;
        var R="["+n;
        for(;m-->0;)
            for(i=m;i++<n;)
                R+=", "+i;
        System.Console.WriteLine(R+"]");
    }
}

Examples output:

n = 5
[5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5]
share|improve this answer
    
I'm really trying to figure out a shorter C# solution but I just can't seem to get it... well done –  Brandon 5 hours ago

C, 22 = 44 bytes * 0.5

The function h takes two parameters. The first is an int specifying n. The second is an int* which is the output buffer.

h(n,o)int*o;{for(n&&h(~-n,o+=n);*--o=n--;);}

Test program

main(){
int wow[999],*i;
memset(wow,0,sizeof(wow));
h(6, wow);
for(i=wow;*i;i++)printf("%d ", *i);
}
share|improve this answer

Python 2, 53 * 0.5 = 26.5 bytes

i=n=input()
x=[]
while i:x+=range(i,n+1);i-=1
print x

Shamelessly borrowed @VisualMelon's idea

share|improve this answer

Pyth - 15 10 * .5 = 5

smr-QdhQUQ

Try it online.

Expects input on stdin. Independently discovered algorithm. Thanks @Sp3000 for helping me stick the last Q in there :P Also, irony? XD

Explanation:

Q=eval(input())       : implicit
s                     : The sum of...
 m      UQ            : map(...,range(Q))
  r-QdhQ              : range(Q-d,Q+1)
share|improve this answer
    
Nice solution. Is there ever a situation in which Pyth wouldn't win code golf? :) –  Alex 6 hours ago
    
@Alex Depending on the nature of the problem, stack based golfing languages (Golfscript, CJam) can cream it, it can also lose to library stuff (cough bash cough) ;) –  FryAmTheEggman 6 hours ago

JavaScript, ES6, 41 bytes

f=i=>[...Array(i).fill(i),...i?f(--i):[]]

This creates a function f which can be called like f(6) and it returns the required array.

This uses a recursive approach, where each iteration creates an array of i elements all valued i and concatenates an array returned by f(i-1) with stopping condition of i==0.

Works on latest Firefox.

share|improve this answer

Haskell, 34 * 0.5 = 17 bytes

0%n=[]
i%n=[i..n]++(i-1)%n
g n=n%n

That's the first time I've ever used Haskell for golfing. Call with g <number>.

share|improve this answer

CJam, 12 15 bytes * 0.5 = 7.5

li_,f{),f-W%~}`

This is full STDIN-to-STDOUT program. It concatenates increasing suffixes of the 1 ... n range, which ensures that no two adjacent numbers are identical.

Test it here.

share|improve this answer

Haskell, 31 characters = 15.5 score

f n=[y|x<-[n,n-1..1],y<-[x..n]]

27 characters without the bonus

f n=[x|x<-[1..n],_<-[1..x]]
share|improve this answer
    
your first solution is not correct. A possible fix is g n = [y|x<-[n,n-1..1],y<-[x..n]] –  karakfa 4 hours ago
    
@karakfa oops :-/ and thanks for the fix –  Jan Dvorak 30 mins ago

vba, 76*0.5=38

Sub i(q)
For Z=1 To q:For x=q To Z Step -1:Debug.?x;",";:Next:Next
End Sub
share|improve this answer

GolfScript (14 bytes * 0.5 = score 7)

 ~:x,{~x),>~}%`

Online demo

I think this is probably similar to some existing answers in that it builds up the array concat( [n], [n-1, n], [n-2, n-1, n], ..., [1, 2, ..., n] )

Sadly I wasn't able to golf any further the arguably more elegant:

~:x]{{,{x\-}/}%}2*`

which puts the input x into an array and then twice applies {,{x\-}/}%, which maps each element in an array to a count down of that many elements from x.

share|improve this answer

perl ,26 bytes

for(1..$n){print"$_ "x$_;}
share|improve this answer
    
Please post your score. Also, since this is code golf, you can save bytes by removing the extra spaces and the definition of $n. –  Alex 6 hours ago
    
This doesn't run for me under Perl 6. –  Alex 6 hours ago
    
@Alex , what is the error , works under 5.10 –  michael501 6 hours ago
    
Unable to parse postcircumfix:sym<{ }>, couldn't find final '}' at line 3. Tried it on ideone.com. –  Alex 6 hours ago
    
@Alex , try this : C:\Windows\system32>perl -e "$n=5;for(1..$n){print qq($_ )x$_;};" 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 –  michael501 6 hours ago

Bash with seq, expr and xargs = 59 / 2 = 29.5

Save it and run with the number as the first argument.

seq $1|xargs -n1 seq|xargs -n1 expr $1 + 1 -|sed 1d;echo $1
share|improve this answer
    

Bash + coreutils, 28/2 = 14

Shamelessly stealing @pgy's idea and golfing:

seq -f"seq %g $1" $1 -1 1|sh

Pure bash (no coreutils), 30/2 = 15

Eval, escape and expansion hell:

eval eval echo \\{{$1..1}..$1}
share|improve this answer

T-SQL, 176 * 0.5 = 88

Since you seemed to miss the T-SQL @Optimizer, here it is in all it's verbose glory :).

A couple of function options, a Scalar and a Inline Table Valued function. The Scalar function uses while loops to recurse and returns a string of numbers, where the Inline Table Valued function uses a recursive CTE for a sequence and returns a table. Of course these will never be competitive, so I haven't spent a lot of time golfing.

Inline Table Valued Function, 176 * .5

CREATE FUNCTION F(@ INT)RETURNS TABLE RETURN WITH R AS(SELECT @ N UNION ALL SELECT N-1FROM R WHERE N>0)SELECT B.N FROM R CROSS APPLY(SELECT TOP(R.N)N FROM R A ORDER BY N DESC)B

Called as follows

SELECT * FROM dbo.F(5)

SQLFiddle example

Scalar Function, 220 * .5

CREATE FUNCTION G(@ INT)RETURNS VARCHAR(MAX)AS BEGIN DECLARE @S VARCHAR(MAX),@N INT=1,@I INT,@C INT WHILE @N<=@ BEGIN SELECT @I=@N,@C=@ WHILE @C>=@I BEGIN SELECT @S=CONCAT(@S+',',@C),@C-=1 END SET @N+=1 END RETURN @S END

Called as follows

SELECT dbo.G(5)

SQLFiddle example

share|improve this answer

C#, 116 + 33 = 149 bytes

Not the shortest code, but... it works anyway :P

int[]l(int m){List<int>i=new List<int>();for(int j=1;j<= m;j++){for(int x=0;x<j;x++){i.Add(j);}}return i.ToArray();}

Requires this at the top of the file (33 bytes):

using System.Collections.Generic;

Un-golfed version:

int[] RepatedNumberList(int m)
{
    List<int> intList = new List<int>();
    for (int j = 1; j <= m; j++)
    {
        for (int x = 0; x < j; x++)
        {
            intList.Add(j);
        }
    }
    return initList.ToArray();
}
share|improve this answer

R, 44 *.5 = 22

f=function(n){r=0;for(i in 1:n)r=c(r,n:i);r}

A quick test

> f(1)
[1] 1
> f(2)
[1] 2 1 2
> f(3)
[1] 3 2 1 3 2 3
> f(4)
 [1] 4 3 2 1 4 3 2 4 3 4
share|improve this answer
    
What ? No TSQL ? –  Optimizer 6 hours ago
    
@Optimizer maybe later:) –  MickyT 6 hours ago

JavaScript, ES6, 66 bytes * 0.5 = 33

f=i=>(g=n=>[...Array(n).fill().map((v,x)=>i-x),...n?g(n-1):[]])(i)

Building on Optimizer's recursive approach, we can build descending runs of decreasing length, like [4,3,2,1, 4,3,2, 4,3, 4].

Instead of making same-value subarrays with Array(i).fill(i), we make undefined-filled subarrays of the appropriate length with Array(n).fill() and then change the values to a descending run using .map((v,x)=>i-x). Also, we define and recurse over an inner function g; the outer function f exists only to store the value of i while g recurses.

share|improve this answer

Perl, 57 * 0.5 = 28.5

This entry is a subroutine named "l" (for "list"?)

sub l{$d=$n=shift;while($d){for($d--..$n){@a=(@a,$_)}}@a}

You can test it like this:

$"=", ";
@a=l(3);
print "[@a]\n"; # prints "[3, 2, 3, 1, 2, 3]"
@a=();          # needed because the function does not re-initialize @a
@a=l(5);
print "[@a]\n"; # prints "[5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5]"

A prior solution is shorter (45 characters), but doesn't print the output prettily so it was disqualified

$d=$n=<>;while($d){for($d--..$n){print"$_ "}}

For an input of 3, this one prints (with a trailing space):

3 2 3 1 2 3 
share|improve this answer
    
On second thought, only the [] are required. You can get rid of the , –  Optimizer 3 hours ago

JAGL V1.1 - 15 bytes

1Ti[r{d()+S*}/E

Explanation:

1Ti               Push 1, take input, and convert to integer
   [r             Increment and make a range
     {d()+S*}     Push a block that makes an array with x occurrences of x
             /E   Map over list and flatten
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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