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


# 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
}


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


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

• 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) Dec 21, 2014 at 7:53
• 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. Dec 21, 2014 at 9:43

# 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[])

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


# Python, 53 bytes ÷ 2 = 26.5

lambda n:[n-i%-~n%(i//n-~n)for i in range(n*~n//2,0)]

Attempt This Online!

#### Python 2 version, 51 bytes ÷ 2 = 25.5

lambda n:[n-i%-~n%(i/n-~n)for i in range(n*~n/2,0)]

Attempt This Online!

This uses ranges like many other answers here but groups them in pairs (longest,shortest);(2nd longest,2nd shortest) etc. That way we can use a closed form expression inside a flat loop.

# Factor + grouping.extras, 35 * 0.5 = 17.5 bytes

[ [1,b] tail-clump reverse concat ]


Try it online!

           ! 5
[1,b]      ! { 1 2 3 4 5 }
tail-clump ! { { 1 2 3 4 5 } { 2 3 4 5 } ... }
reverse    ! { { 5 } { 4 5 } { 3 4 5 } ... }
concat     ! { 5 4 5 3 4 5 2 3 4 5 1 2 3 4 5 }


# JavaScript (V8), 44 bytes

y=x=>x-1?y(x-1).concat(Array(x).fill(x)):[1]


Try it online!

Could probably be golfed more and probably similar to some other answers but might as well post it.

# Vyxal, 86 4 bytes

ƛẋ;f


Try it Online!

### Explained

ƛẋ;f
ƛ    # mapping lambda
ẋ   # Repeat
;  # end lambda
f # flatten

• I think you mean Try it Online! Oct 14, 2022 at 7:51
• Also, Try it Online! for 4 bytes Oct 14, 2022 at 7:53

{$_,|flat (1..$_-1)X..$_}  Try it online! This generates the list consisting of the input number n, and the flattened list of ranges 1 .. (n-1), 2 .. (n-1), ..., n-2 .. n-1, n-1 .. n-1. # K (ngn/k), 12 bytes ,/{x#x}'1+!:  Try it online! Short and sweet. Explanations: ,/{x#x}'1+!: Main function. Takes implicit input x via Right (:) ! Create a range between 0 to x (exclusive) 1+ + 1 to each of them ' For each of the numbers in the range { } Execute a function that x Takes the number as implicit argument x x# And duplicate by themselves' amount of times ,/ Join together  # 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

• On second thought, only the [] are required. You can get rid of the , Dec 19, 2014 at 21:57

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

• Are you sure about <!-- language=lang-perl -->? The result doesn't seem right. Dec 20, 2014 at 10:31
• I know. $" makes the syntax highlight crazy :) Dec 20, 2014 at 10:32 • Can you rename the variable? Switch to lang-none? Dec 20, 2014 at 10:33 # 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] # 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  ## 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);}}  • OK then I removed the aim statement, submission now aligns with the criteria. Dec 23, 2014 at 15:31 • minified to comply with rules. Dec 23, 2014 at 15:40 • Most of the modifiers on your variables aren't needed. Dec 23, 2014 at 16:16 ## CoffeeScript, 57 f=(n)->i=0;a=[];(j=0;a.push i while(j++<i))while(i++<n);a  # 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  • I 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 ;-) Dec 20, 2014 at 9:15 • 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. Dec 20, 2014 at 16:48 # 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. # Tcl, 36 bytes time {time {putsi} [incr i]} \$argv


Try it online!

# 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)


# 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

# 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}


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.

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

# GolfScript, 14 bytes

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


Try it online!

L,Rdz£XbF


Try it online!

In most other languages, it might be worth going for the bonus by using things like prefixes etc. Not in add++.

## Explained

L,Rdz£XbF
L,        # create a lambda that:
R       # pushes the range [1...n] to the stack
dz     # ... zips that with itself
£X   # ... reduces each item by item repetition
bF # ... and flattens that


# brainf***, 98 bytes

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


Try it online!

Takes input as first cell on tape and outputs onto the tape. I'm not sure if this is allowed but input and output is really painful in brainf*** so I'm presuming it's allowed. The example on TIO has header and footer code to print the values out because I couldn't find a way to dump the memory into the output.

If you consider that each brainf*** character only contains 3 bits of information (as there are only 8 possible characters), then it's only 98 * (3/8) = 36.75 bytes of information.

I would put an explanation but I wrote the code yesterday and have forgotten how it works since then.

# MathGolf, score: 2 (4 bytes$$\\times \frac{1}{2}\$$ bonus)

╒╒x─


Try it online.

Explanation:

╒     # Push a list in the range [1, (implicit) input]
╒    # Map each value to an inner list in the range [1, value]
x   # Reverse this list of lists
─  # Flatten
# (after which the entire stack is output implicitly as result)


# GeoGebra, 44 33 bytes * 0.5 bonus = 22 16.5

n=4
l=Flatten(Zip(1…a,a,n…1))


Try It On GeoGebra!

My first time code golfing with GeoGebra :D and I gotta say, GeoGebra has a ton more built-in functions than Desmos. I think I'll start trying out GeoGebra a little bit more, it definitely has a lot of features. It's also surprisingly golfy, especially when it comes to lists!

But, I couldn't figure out how to get functions working properly in GeoGebra for some reason, so the input has to be changed by editing the value of n, and then pressing Enter. The code currently has a default input of n=4.

# APOL, 14 bytes

⭳(Ƒ(⧣ Ƒ(∈ ⋒)))

Explanation:

         Implicit print
⭳(       Flatten list
Ƒ(     One-indexed list-builder for loop
⧣    Integer input
Ƒ(   One-indexed list-builder for loop
∈  Loop item (of parent loop in this case)
⋒  For iterator (what's being iterated through)
)
)
)


# Japt, 5 bytes * 0.5 = 2.5

õõU c


Try it

õõU c #
õ     # For all numbers X in the range [1, input]:
õU   #  Generate the range [input, X]
c # Flatten


A cheatier 3 byte version produces the same visible output, but that's only because Japt's default string representation of 2D arrays isn't very clear. Using the -Q flag reveals the real output.