Create an array with repeated numbers

19

3

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]

Optimizer

Posted 2014-12-19T17:29:10.737

Reputation: 25 836

Answers

6

APL, 4 characters

/⍨⍳⎕

How it works:

reads user input. As for output, APL by default prints the result from every line.

⍳n is the integers from 1 to n. Example: ⍳3←→ 1 2 3

/ means replicate. Each element from the right argument is repeated as many times as specified by its corresponding element from the left argument. Example: 2 0 3/'ABC'←→ 'AACCC'

is the commute operator. When it occurs to the right of a function, it modifies its behaviour, so it either swaps the arguments (A f⍨ B ←→ B f A, hence "commute") or provides the same argument on both sides (f⍨ A ←→ A f A, a "selfie"). The latter form is used in this solution.


Bonus:

6-∊⌽⍳¨⍳⎕ (8 characters, thanks @phil-h)

⍳5 (iota five) is 1 2 3 4 5.

⍳¨ ⍳5 (iota each iota five) is (,1)(1 2)(1 2 3)(1 2 3 4)(1 2 3 4 5), a vector of vectors. Each (¨) is an operator, it takes a function on the left and applies it to each item from the array on the right.

reverses the array, so we get (1 2 3 4 5)(1 2 3 4)(1 2 3)(1 2)(,1).

is enlist (a.k.a. flatten). Recursively traverses the argument and returns the simple scalars from it as a vector.

ngn

Posted 2014-12-19T17:29:10.737

Reputation: 11 449

How about a 4-character expression? /⍨⍳n – ngn – 2014-12-20T09:31:43.183

As you wish, sir, I've updated the text. But surely your objection must apply to other solutions that are not wrapped in functions? – ngn – 2014-12-20T11:17:48.247

If you write a full program, no need for a function name. But if you write a function, it has to be named. Most of the answers here are full programs (who read from STDIN and output to STDOUT) and all of which are functions, have names. – Optimizer – 2014-12-20T11:21:28.910

An expression is a full program. – ngn – 2014-12-20T11:23:21.767

A expression is not a full program if it requires you to edit the expression before running it. (for instance , to run your initial expression, one would have to add f← before and 5 after the expression) – Optimizer – 2014-12-20T11:26:54.570

I was referring to /⍨⍳n without the f← and 5. And, of course, instead of n I can use which means "ask the user for input". – ngn – 2014-12-20T11:30:48.270

Oh, if that was a full program taking input from user/STDIN and outputting/printing to STDOUT, then its fine. Obviously, I do not understand APL that much :) – Optimizer – 2014-12-20T11:55:25.537

Oh, I forgot to mention that APL by default prints the result of every expression, so the STDOUT bit is covered. Quad () asks for user input and evaluates it, so if the user types a number, will return that number. Unfortunately this can't be tested at tryapl.org as it runs in a restricted environment and is not available, but I've seen APL solutions to other challenges by other people that use for input. – ngn – 2014-12-20T12:12:04.953

The question said bytes. Assuming you're using UTF-8, this is 10 bytes. – nyuszika7h – 2014-12-20T12:43:03.167

3Dyalog APL comes in two flavours: "Classic" and "Unicode". The Classic version has existed for decades, since before the Unicode standard appeared, and uses a custom byte-per-character encoding for the APL character set. It is still supported, though its use is discouraged. So, I'd like to use this as an excuse. More broadly, I think in golfing we should be counting characters, not bytes. The fact that the lowest code points in Unicode are occupied by the English-centric ASCII is a historical accident that shouldn't matter today. Interestingly, APL was conceived before ASCII came out. – ngn – 2014-12-20T13:01:12.970

3

@ngn counting chars is not a good idea, as answers will generally become alphabet soup decodes. APL chars are counted as bytes because that encoding exists; this is well established on this site. This works with any byte encoding that existed prior to the question's asking.

– FryAmTheEggman – 2014-12-20T17:37:01.927

1@ngn: Can you explain your bonus answer? Because it can be done via: 5 4 3 2 1 5 4 3 2 5 4 3 5 4 5 or 6 minus each of 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1, which feels like it is not far from your initial answer. – Phil H – 2014-12-22T11:20:18.177

@phil-h Excellent idea, thank you! So, it can be done in 8 characters (6-∊⌽⍳¨⍳⎕) instead of my complicated 11... I'll update the answer and add an explanation later today.

– ngn – 2014-12-22T16:58:57.833

11

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 and Ventero): 34 bytes * 0.5 = 17

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

(call using r[argument])

AlexRath

Posted 2014-12-19T17:29:10.737

Reputation: 139

2That'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 – 2014-12-19T18:47:12.780

1By inverting the logic, you can drop the whitespace in the ternary: r=->n,i=n{i>0?[*i..n]+r[n,i-1]:[]} – Ventero – 2014-12-20T10:39:08.493

11

Pyth, 9 bytes * 0.5 = 4.5

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.

Sp3000

Posted 2014-12-19T17:29:10.737

Reputation: 58 729

5Shouldn't have helped you :D – FryAmTheEggman – 2014-12-19T19:06:17.657

8

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]]

Beaten by Proud Haskeller

John Dvorak

Posted 2014-12-19T17:29:10.737

Reputation: 9 048

your first solution is not correct. A possible fix is g n = [y|x<-[n,n-1..1],y<-[x..n]] – karakfa – 2014-12-19T20:43:05.303

@karakfa oops :-/ and thanks for the fix – John Dvorak – 2014-12-20T01:08:52.050

My Haskell answer is just a tad lower than yours – proud haskeller – 2014-12-20T23:31:50.050

Should I link to it from my solution, to promote it? – John Dvorak – 2014-12-21T11:03:39.510

@JanDvorak I would like to, actually... – proud haskeller – 2014-12-23T07:45:16.817

7

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);
}

feersum

Posted 2014-12-19T17:29:10.737

Reputation: 29 566

I don't get it. Please explain? – bacchusbeale – 2014-12-31T09:34:07.767

@bacchusbeale Ok.. It recursively writes descending sequences from n to 0. Shorter sequences are written sooner, at a deeper level of recursion. If the argument n is 0, then n is falsey so there is no recursion, and only a 0 is written, which serves to mark the end of the array. – feersum – 2014-12-31T15:02:59.923

7

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)

FryAmTheEggman

Posted 2014-12-19T17:29:10.737

Reputation: 16 206

2Nice solution. Is there ever a situation in which Pyth wouldn't win code golf? :) – Alex A. – 2014-12-19T19:02:31.790

2@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 – 2014-12-19T19:03:38.650

6

Python 2, 53 bytes * 0.5 = 26.5

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

Shamelessly borrowed @VisualMelon's idea

Sp3000

Posted 2014-12-19T17:29:10.737

Reputation: 58 729

6

Haskell, 34 bytes * 0.5 = 17

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>.

Sp3000

Posted 2014-12-19T17:29:10.737

Reputation: 58 729

6

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.

Martin Ender

Posted 2014-12-19T17:29:10.737

Reputation: 184 808

5

C# - 81 (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]

VisualMelon

Posted 2014-12-19T17:29:10.737

Reputation: 3 810

I'm really trying to figure out a shorter C# solution but I just can't seem to get it... well done – Brandon – 2014-12-19T19:42:57.840

You could create a var of System.Console maybe – Mark Knol – 2014-12-20T11:32:28.830

1@MarkKnol System.Console is static, you can't assign it to a variable, but in C# 6 or whatever is next, you will be able to do using System.Console; (using System; doesn't pay in this instance), not sure how I feel about this feature, will affect a lot of old golf questions for this reason precisely ;) – VisualMelon – 2014-12-20T15:57:33.047

@VisualMelon Unless my math is wrong, using System; is 13 bytes and System.x2 is 14 bytes. You're saving 1 byte by using the using statement :) – Ichabod Clay – 2014-12-21T19:43:04.563

@IchabodClay quite right, how embarrassing... I'll change that if I do anymore golfing on this, 1byte probably doesn't warrant an edit ;) – VisualMelon – 2014-12-21T19:57:49.700

1@IchabodClay it gets worse, using C=System.Console saves 3 bytes, and is probably what @MarkKnol meant (sorry!), shameful negligence on my part. – VisualMelon – 2014-12-21T22:13:51.663

1

Also, according to the rules, you could just have the method itself instead of creating a complete program. Something like... this. (114 bytes with whitespaces and such removed. 57 bytes with bonus.)

– Ichabod Clay – 2014-12-21T22:28:08.767

1@IchabodClay indeed; I prefer submitting full programs to functions, no good reason, IO just seems like part of the fun (I don't tend to use argv, either). Feel free to post a better scoring answer without these daft constraints! – VisualMelon – 2014-12-21T22:53:17.273

5

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}

Digital Trauma

Posted 2014-12-19T17:29:10.737

Reputation: 64 644

5

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.

Peter Taylor

Posted 2014-12-19T17:29:10.737

Reputation: 41 901

4

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.

Optimizer

Posted 2014-12-19T17:29:10.737

Reputation: 25 836

4

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

SeanC

Posted 2014-12-19T17:29:10.737

Reputation: 1 117

you can lose 1 (0.5, technically) byte(s) by condensing For Z=1 To to For Z=1To – Taylor Scott – 2017-03-25T20:55:38.783

you can also condense Next:Next to Next x,Z – Taylor Scott – 2017-11-01T12:04:47.683

4

Haskell, 14 = 28 bytes / 2

f n=n:[1..n-1]>>= \r->[r..n]

example output:

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

24 bytes without the bonus:

f n=[1..n]>>= \r->[r..n]

proud haskeller

Posted 2014-12-19T17:29:10.737

Reputation: 5 866

could =<< help avoid the whitespace? I feel like it could, but I'd be surprised if you hadn't already considered that. – John Dvorak – 2014-12-20T16:53:11.983

@JanDvorak If I would have used =<< I would need parentheses for the lambda – proud haskeller – 2014-12-20T16:55:01.203

I'm confused on when exactly lambdas need parentheses. Does the lambda header have the same fixity as >>=? – John Dvorak – 2014-12-20T17:01:24.830

@JanDvorak They have no fixity; I'm not sure how accurate this rule is, but lambdas can only appear where operators can't (disregarding sections): after (, [, =, ,, after any operators, and the like – proud haskeller – 2014-12-20T17:13:14.017

I guess neither lambdas nor operators can appear as patterns? let \x->y = (2+) in (x,y) seems kinda impossible. – John Dvorak – 2014-12-20T17:37:27.510

@JanDvorak Operators can, if you consider function declarations as patterns. Remember let 2*5=1 in 2*5? – proud haskeller – 2014-12-20T17:38:55.180

@JanDvorak And operators which are constructors can be patterns: data M=Int :- Int ; let a :- b = ... – proud haskeller – 2014-12-20T17:42:53.403

4

Haxe, 53 bytes

function l(v)return[for(i in 0...v)for(j in 0...i)i];

Works with l(6); because of array comprehension.
Test online http://try.haxe.org/#741f9

Mark Knol

Posted 2014-12-19T17:29:10.737

Reputation: 141

2

perl ,26 bytes

for(1..$n){print"$_ "x$_;}

michael501

Posted 2014-12-19T17:29:10.737

Reputation: 191

1Please post your score. Also, since this is code golf, you can save bytes by removing the extra spaces and the definition of $n. – Alex A. – 2014-12-19T19:01:10.177

This doesn't run for me under Perl 6. – Alex A. – 2014-12-19T19:09:41.530

@Alex , what is the error , works under 5.10 – michael501 – 2014-12-19T19:13:52.580

Unable to parse postcircumfix:sym<{ }>, couldn't find final '}' at line 3. Tried it on ideone.com. – Alex A. – 2014-12-19T19:14:56.837

@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 – 2014-12-19T19:20:21.683

Doesn't work on ideone.com, which uses Perl 6, but it works on my local machine, which is running Perl 5. Your original also works on my local machine. It probably doesn't matter much, but if you felt so inclined, you could specify Perl 5 in your post. Anyway, nice work. – Alex A. – 2014-12-19T19:40:25.400

You should print in the following format : [1, 2, 2, 3, 3, 3] . Not space separated values – Optimizer – 2014-12-19T20:20:38.370

2

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

MickyT

Posted 2014-12-19T17:29:10.737

Reputation: 11 735

What ? No TSQL ? – Optimizer – 2014-12-19T19:32:42.730

@Optimizer maybe later:) – MickyT – 2014-12-19T19:34:37.923

2

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.

apsillers

Posted 2014-12-19T17:29:10.737

Reputation: 3 632

2

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

MickyT

Posted 2014-12-19T17:29:10.737

Reputation: 11 735

2

Mathematica, 34 * 0.5 = 17

f=Join@@Table[x,{y,#},{x,#,y,-1}]&

alephalpha

Posted 2014-12-19T17:29:10.737

Reputation: 23 988

2

JavaScript(readable), 131 bytes

I'm new to Code Golf so this isn't the best

function f(n) {
    var arr = [];
    for(var i = 1; i <= n; i++) {
        for(var j = 0; j < i; j++) {
            arr.push(i);
        }
    }
    return arr;
}

JavaScript(less readable), 87 bytes

Minified using jscompress.com

function f(e){var t=[];for(var n=1;n<=e;n++){for(var r=0;r<n;r++){t.push(n)}}return t}

SirPython

Posted 2014-12-19T17:29:10.737

Reputation: 178

2

TECO, 25 bytes * 0.5 = 12.5

a\+1%a%b<qauc-1%b<-1%c=>>

The above barely beats the non-bonus version at 13 bytes:

a\%a<%b<qb=>>

feersum

Posted 2014-12-19T17:29:10.737

Reputation: 29 566

2

C#, 114 99 * 0.5 = 49.5 bytes

(With a little help from VisualMelon's answer) Edit: and James Webster's comment

int[]A(int n){int m=n,i,c=0;var a=new int[n*(n+1)/2];while(m-->0)for(i=m;i++<n;)a[c++]=i;return a;}

Ungolfed:

int[] FooBar(int n)
{
    int altCounter = n, i, arrayCounter = 0;
    var returnArray = new int[n * (n + 1) / 2];
    while(m-->0)
        for(i = altCounter; i++ < n; )
            returnArray[arrayCounter++]=i;
    return returnArray;
}

There is an unsafe version that I shamelessly took from feersum's C answer, but I'm not 100% sure it fits within the rules since you have to allocate the memory before calling the method.

C# (unsafe), 82 * 0.5 = 41 bytes

unsafe void A(int n,int*p){int*z=p;int m=n,i;while(m-->0)for(i=m;i++<n;)z++[0]=i;}

Called as follows:

int n = 5, length = (int)((n / 2f) * (n + 1));
int* stuff = stackalloc int[length];
int[] stuffArray = new int[length];
A(n, stuff);
System.Runtime.InteropServices.Marshal.Copy(new IntPtr(stuffArray), stuffArray, 0, stuffArray.Length);
//stuffArray == { 5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5 }

Per VisualMelon's suggestion (thanks!), the unsafe code can be re-made with safe code which reduces the size even further! Still poses the question if the creation of the final result array is allowed to be done outside of the method.

C#, 72 * 0.5 = 36 bytes

void A(int n,int[]p){int z=0,m=n,i;while(m-->0)for(i=m;i++<n;)p[z++]=i;}

Ichabod Clay

Posted 2014-12-19T17:29:10.737

Reputation: 121

Nice work! For the per-allocated version, it's much cheaper to go safe and pass it the int[] straight off void A(int n,int[]p){int z=0,m=n,i;while(m-->0)for(i=m;i++<n;)p[z++]=i;} - I would agree it's probably a bit iffy, regarding the rules ;) – VisualMelon – 2014-12-22T21:25:30.780

You shouldn't need to create a local pointer for the unsafe version, which cuts a good 8bytes out. Also, I might be missing the point, but should the last line of the unsafe calling code be System.Runtime.InteropServices.Marshal.Copy(new IntPtr(stuff), stuffArray, 0, length); ? – VisualMelon – 2014-12-22T21:47:34.763

@VisualMelon That's what I get for not rechecking the names of variables after I rename them. Thanks for the heads up :D. Edited the answer to account for the shorter version in your comment. – Ichabod Clay – 2014-12-23T00:23:53.240

You can chop a little off the safe version by inlining the length var a=new int[(int)((n/2f)*(n+1))]; I think that takes it down to 109 – James Webster – 2014-12-23T16:46:03.973

One more off by rewriting the calc as: (n*(n+1)/2) – James Webster – 2014-12-23T16:50:17.497

@JamesWebster The outer parentheses can also be done away with. 2 more bytes! Thanks for the hints, I'll add them to the answer! – Ichabod Clay – 2014-12-23T22:13:15.427

Are you sure that will be casting what you need @IchabodClay. I think I played around with that, but was left with integer division – James Webster – 2014-12-23T22:15:15.013

@JamesWebster It should be fine, since n * (n + 1) is evaluated first, it will always be an even number that is divided by 2. – Ichabod Clay – 2014-12-23T22:23:05.510

It's not though.. BODMAS/BIDMAS/etc, whichever you use... The division is done first. – James Webster – 2014-12-23T22:28:54.907

@JamesWebster According to this MSDN article (near the bottom), operations are performed left to right. So, multiplication would be performed before division in this case.

– Ichabod Clay – 2014-12-23T22:40:57.990

That's interesting! – James Webster – 2014-12-23T23:01:46.420

1

C#, 108 bytes * 0.5 = 54

List<int> f(int n){var r=new List<int>();int m=n-1,i;r.Add(n);for(;m-->0;)for(i=m;i++<n;)r.Add(i);return r;}

Thanks to VisualMelon for doing the hard work! I thought I'd try to squeeze it down as much as possible.

(114 bytes * 0.5 = 57, if you insist on using .ToArray() to return int[])

Romen

Posted 2014-12-19T17:29:10.737

Reputation: 161

1

C#, 116 115 + 33 = 148 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();
}

ProgramFOX

Posted 2014-12-19T17:29:10.737

Reputation: 8 017

1

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

pgy

Posted 2014-12-19T17:29:10.737

Reputation: 830

Great idea! I stole it and golfed it significantly

– Digital Trauma – 2014-12-19T19:56:36.920

1

J, 23 * 0.5 = 11.5

   f=.-;@(<@|.@i."0@>:@i.)
   f 5
5 4 5 3 4 5 2 3 4 5 1 2 3 4 5

J, 11

   f=.#~@i.@>:
   f 5
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

randra

Posted 2014-12-19T17:29:10.737

Reputation: 19

123 * 0.5 is 11.5, not 10.5. – ProgramFOX – 2014-12-20T10:34:08.267

@ProgramFOX good catch. Are you going to edit, or should I? Not a great reason to downvote IMO. – John Dvorak – 2014-12-20T10:35:35.167

@JanDvorak Just edited it. And I didn't downvote, I upvoted it even before I saw the mistake. – ProgramFOX – 2014-12-20T10:37:21.077

Now that the mistake has been fixed, should the bonus solution be moved to the bottom? – John Dvorak – 2014-12-20T10:40:47.853

-1 Byte: f=.-[:;<@|.@i."0@>:@i., making the scores equal! – Bolce Bussiere – 2018-04-15T21:54:51.043

1

ECMAScript6, 67 * 0.5 = 33.5 bytes

f=n=>{a=[],b=0;while(c=n+b,n--){while(c-b)a.push(c--);b++}return a}

Pretty happy with this one...It's about a quarter the size of my original.

f(4) returns:

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

Old answer:

f=i=>{a=b=Array;while(i)a=a.concat(b.apply(null,b(i)).map(e=>i)),i--;return a}

This is my first shot at code golf...I still want to get that 0.5x bonus. Any suggestions are welcomed!

Called with f(n).

binormal

Posted 2014-12-19T17:29:10.737

Reputation: 11

You must be pretty new to JavaScript it self :) . (1) Remove brackets around argument d, (2) a=b=c=[] in for declaration part, (3) c[a].map(e=>a) (4) b.push(...c) – Optimizer – 2014-12-21T07:53:11.720

I made a shorter version before reading your comment, which I'll put in my post.

My experience with JS is mostly limited to DOM/style manipulation for simple web apps...and I've hardly used any of the new ES6 features until today. – binormal – 2014-12-21T09:43:50.657

1

JavaScript (ES6) 29 (58 * 0.5)

Edit remove ; thx @Optimizer

Q=o=>(m=>{for(n=o,r=[];n>m||++m<(n=o);)r.push(n--)})(0)||r

Test in FireFox/FireBug console

Q(9)

Output

[9, 8, 7, 6, 5, 4, 3, 2, 1, 9, 8, 7, 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 9, 8, 7, 6, 5, 4, 9, 8, 7, 6, 5, 9, 8, 7, 6, 9, 8, 7, 9, 8, 9]

Ungolfed

Q=o=>{
  for(m=0,r=[];m<o;++m)
    for(n=o;n>m;)
      r.push(n--);
  return r
}

edc65

Posted 2014-12-19T17:29:10.737

Reputation: 31 086

0

Tcl, 36 bytes

time {time {puts $i} [incr i]} $argv

Try it online!

sergiol

Posted 2014-12-19T17:29:10.737

Reputation: 3 055

0

Stax, 4 bytes * 0.5 = 2

R|]r

Run and debug it online! Note: To verify that is does indeed work, you'll need to step through the execution, as the values are printed as characters rather than numbers.

Explanation:

R|]r
R       Range [1..n].     Example: [1, 2, 3, 4]
 |]     List of suffixes: Example: [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]
   r    Reverse.          Example: [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]]
        Implicit flatten and print (treating numbers as characters and concatenating).

Without the bonus (3 bytes):

R|]

or

R|[     (This does what you expect)

Khuldraeseth na'Barya

Posted 2014-12-19T17:29:10.737

Reputation: 2 608

0

Jelly, 3 × 0.5 = 1.5 bytes

rRF

Try it online!

Explanation

rRF
r      Range from {input} to 
 R       each number from 1 to {input}
  F    Flatten

For example, with input 3, the rR gives us a range from 3 to 1 (i.e. [3, 2, 1], then a range from 3 to 2 (i.e. [3, 2]), then a range from 3 to 3 (i.e. [3, 3]). Flattening that gives [3, 2, 1, 3, 2, 3]), which meets the problem specifications and has no adjacent numbers.

ais523

Posted 2014-12-19T17:29:10.737

Reputation: 11

0

K (oK), 4 bytes

Solution:

&!1+

Try it online!

Examples:

&!1+5
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
&!1+6
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6

Explanation:

&!1+ / the solution
  1+ / add one to the input, 1+5 => 6
 !   / til, !6 => 0 1 2 3 4 5
&    / where, &0 1 2 3 4 5 => 1 2 2 3 3 3...

streetster

Posted 2014-12-19T17:29:10.737

Reputation: 3 635

0

Java 8, 109 bytes (score: 54.5 bytes)

import java.util.*;

n->{List l=new Stack();l.add(n);for(int i=0,j;i<n-1;i++)for(j=i;j++<n;)l.add(j);return l;}

That's a lambda from int to List<Object>. The members are, of course, Integers.

Try It Online

Jakob

Posted 2014-12-19T17:29:10.737

Reputation: 2 428

0

Pyth, 6 bytes

smrQdU

Try it online!

hakr14

Posted 2014-12-19T17:29:10.737

Reputation: 1 295

0

Golang, 80 bytes

func n(a int)(r[]int){for i:=0;i<=a;i++{for j:=0;j<i;j++{r=append(r,i)}};return}

Ungolfed and readable:

func n(a int) (r []int){
    for i := 0; i <= a; i++ {
        for j := 0; j < i; j++ {
            r = append(r, i)
        }
    }
    return
}

Try it online!

Pretty straightforward solution and probably pretty bad.

Dust

Posted 2014-12-19T17:29:10.737

Reputation: 131

0

Pyth, 17 bytes x 0.5 = 8.5

FbQ=+Y-SQSb)+eYPY

Possibly golfable. Explanation:

FbQ=+Y-SQSb)+eYPY
FbQ                For b in range(int(input()))
     Y             A variable containing an empty list
   =+              +=
      -            The set difference of
       SQ          [1, 2, ..., input()]
         Sb        [1, 2, ..., b]
           )       End function
            +eY    Append to the last element of Y
               PY  All but the last element of Y

So for example, putting 3 through the loop would yield [1,2,3,2,3,3], then the last five characters will transpose that final 3 to the beginning so no two numbers touch each other.

ericeschnei

Posted 2014-12-19T17:29:10.737

Reputation: 71

0

GolfScript, 14 bytes

~),1>{.[()]*}%

Try it online!

user85052

Posted 2014-12-19T17:29:10.737

Reputation:

0

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 

KJP

Posted 2014-12-19T17:29:10.737

Reputation: 131

On second thought, only the [] are required. You can get rid of the , – Optimizer – 2014-12-19T21:57:18.633

0

JAGL Alpha 1.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

globby

Posted 2014-12-19T17:29:10.737

Reputation: 1 132

2I can see this is your own language, mere two hours older than the question. I guess this is just a test of the language? Note you won't be able to use v 1.2 for this challenge, and it wouldn't be a good test of your language anyways. Oh, and the documentation needs to be vastly improved before a public release ;-) – John Dvorak – 2014-12-20T09:15:56.093

I'll work on that. I haven't had much time to make the full documentation yet, but that will be the next step.

The language itself is a few days old, but the most recent update was released just a couple hours before the question. – globby – 2014-12-20T16:48:17.587

0

Perl 48 * 0.5 = 24

$i=<>;$"=", ";@a=map{-$_..$i}-$i..-1;print"[@a]"

Test run:

$ ./repeated.pl <<< 5
[5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5]

core1024

Posted 2014-12-19T17:29:10.737

Reputation: 1 811

Are you sure about <!-- language=lang-perl -->? The result doesn't seem right. – John Dvorak – 2014-12-20T10:31:29.683

I know. $" makes the syntax highlight crazy :) – core1024 – 2014-12-20T10:32:33.713

Can you rename the variable? Switch to lang-none? – John Dvorak – 2014-12-20T10:33:36.317

0

Erlang, 56 Bytes * 0.5 = 28

f(I)->L=lists,L:flatten([L:seq(X,I)||X<-L:seq(I,1,-1)]).

Using a list comprehension, reverses the list using lists:seq(UpperBound, 1, -1) and for each element, creates a sequence using lists:seq(CurrentValue, UpperBound). The eventual list is then flattened.

Expanded:

f(I) ->
    lists:flatten([lists:seq(X, I) || X <- lists:seq(I, 1, -1)]).

Input: module_name:f(9).

Output: [9,8,9,7,8,9,6,7,8,9,5,6,7,8,9,4,5,6,7,8,9,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]

c.P.u1

Posted 2014-12-19T17:29:10.737

Reputation: 1 049

0

Perl 5: 30 bytes / 2 = 15

Added one byte for the -p flag.

#!perl -p
$_=join$",map-$_..$',-$_..-//

Takes parameter on the input:

$ perl int.pl <<<5
5 4 5 3 4 5 2 3 4 5 1 2 3 4 5

nutki

Posted 2014-12-19T17:29:10.737

Reputation: 3 634

0

Java (adjacent equals ok): 276 bytes

public class a{public static int[]b(final int c){final int d=(c+1)*c/2;final int[]e=new int[d];int f=1;int g=0;for(int i=0;i<d;i++){if(g==f){f++;g=0;;}
e[i]=f;g++;}
return e;}
public static void main(String[]args){final int q=new java.util.Scanner(System.in).nextInt();b(q);}}

Java (adjacent equals not ok): 442 * 0.5 = 221 bytes

public class a{private static int h=1;public static int[]j(final int k){final int[]l=new int[k+1];for(int i=1;i<=k;i++){l[i]=i;}
final int m=(k+1)*k/2;final int[]n=new int[m];for(int i=1;i<n.length;i++){n[i]=o(l,k);}
n[0]=k;return n;}
private static int o(final int[]p,final int q){if(h>q){h=1;}
while(p[h]==0){h++;}
p[h]=p[h]-1;return h++;}
public static void main(String[]args){final int q=new java.util.Scanner(System.in).nextInt();j(q);}}

PoweredByRice

Posted 2014-12-19T17:29:10.737

Reputation: 171

OK then I removed the aim statement, submission now aligns with the criteria. – PoweredByRice – 2014-12-23T15:31:07.170

minified to comply with rules. – PoweredByRice – 2014-12-23T15:40:41.697

Most of the modifiers on your variables aren't needed. – James Webster – 2014-12-23T16:16:25.447

0

CoffeeScript, 57

f=(n)->i=0;a=[];(j=0;a.push i while(j++<i))while(i++<n);a

rink.attendant.6

Posted 2014-12-19T17:29:10.737

Reputation: 2 776

0

Matlab, 44 * 0.5 = 22

function r=f(n);r=[];for i=1:n;r=[i:n,r];end

f(4) == [4 3 4 2 3 4 1 2 3 4]

Javascript, 63 * 0.5 = 31.5

F=n=>{r=[m=n];while(--n){r=r.slice(0,m-n).concat(n,r)}return r}

F(4) == [ 4, 3, 2, 1, 4, 3, 2, 4, 3, 4 ]

Nothing fancy, just concatenating arrays.

zabalajka

Posted 2014-12-19T17:29:10.737

Reputation: 71