-4
\$\begingroup\$

Given an input array having minimum length 2 and maximum length 9 having any initial values output an array having length 2 consisting of the 1-based indexes of the array represented as either an integer or string in forward and reverse order.

The values of the array or string do not matter and are ignored. For example:

[undefined,null] -> [12,21]

Test cases

Input -> Output

["a","e","i","o","u"] -> [12345,54321] // valid
[{"a":1},{"b":2},{"c":3}] -> [123,321] // valid
[-1,22,33,44,55,66,77,88,99] -> ["123456789","987654321"] // valid
[0,1] -> [01,10] // invalid, not a 1-based index, `01` is not a valid integer
[1999,2000] -> [12,"21"] invalid, output either integers or strings

Winning criteria

Least bytes.

\$\endgroup\$
  • 11
    \$\begingroup\$ Isn't this just, "Count up to the array length, then back down?" \$\endgroup\$ – ATaco Oct 24 '18 at 7:41
  • \$\begingroup\$ Can we output an array containing 2 arrays? \$\endgroup\$ – Quintec Oct 24 '18 at 11:54
  • \$\begingroup\$ @Quintec Not ideally. That is an unnecessary complication. Though if that is the only way to achieve the approach that you are considering, then do so and provide a note to that caveat of the approach at the answer. \$\endgroup\$ – guest271314 Oct 24 '18 at 14:09
  • 1
    \$\begingroup\$ @guest271314 Well remember, this is code golf. If I can output a 2d array if saves me a few bytes. \$\endgroup\$ – Quintec Oct 24 '18 at 14:47
  • 4
    \$\begingroup\$ Although the question is boring and trivial, it should not be closed just because of that... \$\endgroup\$ – user202729 Oct 24 '18 at 15:07

20 Answers 20

7
\$\begingroup\$

Python 2, 53 bytes

n=len(input())+1
b=10**n/81-n/9
print[b,10**n/90*n-b]

Try it online!

For example, for \$n=5\$: \begin{align} 12345 &= 11111 + 1111 + 111 + 11 + 1 \\ &= (11111.\bar1 + 1111.\bar1 + \dots + 1.\bar1) - (0.\bar1 \times 5) \\ &= \frac{10}{9} \left( \sum_{k=0}^{n-1} 10^{k} \right) - \frac n9 \\ &= \frac{10}{9} \left( \frac{1-10^n}{1-10} \right) - \frac{n}{9} \\ &= \frac{10^{n+1}-1}{81}-\frac{n+1}{9} \end{align}

We use integer (floor) division, so the surplus \$\frac{1}{81}\$ gets rounded away.

For the descending part, if b=12345 we compute something like 66666-12345 == 54321.

\$\endgroup\$
  • \$\begingroup\$ Can you provide an explanation of the approach? \$\endgroup\$ – guest271314 Oct 24 '18 at 14:20
  • \$\begingroup\$ b=10**n/81-n/9 saves 2 \$\endgroup\$ – Jonathan Allan Oct 24 '18 at 22:11
6
\$\begingroup\$

Python 2, 44 bytes

s='123456789'[:len(input())]
print s,s[::-1]

Try it online!

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

Python 2, 55 52 bytes

a=''
for i in input():a+=`-~len(a)`
print[a,a[::-1]]

Try it online!

Explanation:

# initial value: empty string
a=''
# iterate over input
# will work with any iterable object: list, tuple, dict, set, string, etc.
for i in input():
# add to a string representation of its length+1
    a+=`-~len(a)`
# print list, composed from a and its reversed version
print[a,a[::-1]]

Python 2, 66 bytes

lambda i:`map(abs,range(-len(i),-~len(i)))`[1::3].split('0')[::-1]

Try it online!

Explanation:

lambda i:`map(abs,range(-len(i),-~len(i)))`[1::3].split('0')[::-1]

# unnamed lambda
# example input: ['q', 'w', 'e', 'r', 't']

# create range from minus length of input to length+1
# ['q', 'w', 'e', 'r', 't'] -> [-5,-4,-3,-2,-1,0,1,2,3,4,5]
                  range(-len(i),-~len(i))
# change every value in range to its absolute value
# [-5,-4,-3,-2,-1,0,1,2,3,4,5] -> [5,4,3,2,1,0,1,2,3,4,5]
          map(abs,range(-len(i),-~len(i)))
# get string representaion of list
# [5,4,3,2,1,0,1,2,3,4,5] -> '[5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5]'
         `map(abs,range(-len(i),-~len(i)))`
# get each third element from string, starting from index 1, returns string
# '[5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5]' -> '54321012345'
         `map(abs,range(-len(i),-~len(i)))`[1::3]
# split string over '0', returns list of 2 values
# '54321012345' -> ['54321','12345']
         `map(abs,range(-len(i),-~len(i)))`[1::3].split('0')
# reverse list
# ['54321','12345'] -> ['12345','54321']
         `map(abs,range(-len(i),-~len(i)))`[1::3].split('0')[::-1]
\$\endgroup\$
  • \$\begingroup\$ Can you provide an explanation of the approach? \$\endgroup\$ – guest271314 Oct 24 '18 at 14:20
  • \$\begingroup\$ @guest271314 Done \$\endgroup\$ – Dead Possum Oct 24 '18 at 15:24
2
\$\begingroup\$

Jelly, 6 bytes

J,JṚ$Ḍ

Explanation

J      # Converts an array to [1, ...len(arr)]
 ,     # Paired with
  JṚ$  # The same array as before, reversed.
     Ḍ # Convert the digits to integers.

I'm no Jelly master, so likely sub-optimal.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Alternative equal answer: Jm0ŒHḌ \$\endgroup\$ – ATaco Oct 24 '18 at 7:49
  • \$\begingroup\$ Hint: can you remove the duplication in the code? \$\endgroup\$ – user202729 Oct 24 '18 at 9:39
  • \$\begingroup\$ Dunno why it works, but 5 bytes. \$\endgroup\$ – totallyhuman Oct 24 '18 at 16:39
  • \$\begingroup\$ @totallyhalloween because $ combines the two links to it's left into a monadic function, so it's a bit like let f(x)=[x,reverse(x)];v=J(leftArgument);v=f(v);v=fromDecimal(v) \$\endgroup\$ – Jonathan Allan Oct 24 '18 at 19:59
2
\$\begingroup\$

05AB1E, 4 bytes

ā‚J

Try it online or verify all test cases.

Explanation:

ā       # List in the range [1, length of (implicit) input-list]
        #  i.e. ["a","e","i","o","u"] → [1,2,3,4,5]
 Â      # Bifurcated (short for Duplicate & Reverse copy)
  ‚     # Pair both list into a single list of lists
        #  i.e. [1,2,3,4,5] and [5,4,3,2,1] → [[1,2,3,4,5],[5,4,3,2,1]]
   J    # Join the individual items of the inner lists together (and output implicitly)
        #  i.e. [[1,2,3,4,5],[5,4,3,2,1]] → ["12345","54321"]
\$\endgroup\$
1
\$\begingroup\$

Husk, 6 bytes

S¤,d↔ŀ

Try it online!

Explanation

S¤,d↔ŀ  -- input xs (list)
     ŀ  -- indices [1..length xs]
S   ↔   -- do the following with itself and itself reversed:
 ¤,d    -- | undigits and join as tuple
\$\endgroup\$
1
\$\begingroup\$

Java (JDK), 76 bytes

a->{String[]r={"",""};int i=1;for(var x:a){r[1]=i+r[1];r[0]+=i++;}return r;}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Tried to find something shorter, but to no avail.. Got 84 bytes by using substrings and 89 by using integer division and modulo. \$\endgroup\$ – Kevin Cruijssen Oct 24 '18 at 11:25
  • \$\begingroup\$ @KevinCruijssen Hmmm, I tried other versions as well before posting this one, but all used explicit loops. So your ideas were quite different from mine and that's nice :) \$\endgroup\$ – Olivier Grégoire Oct 24 '18 at 12:07
  • \$\begingroup\$ That's why I commented it. :) Normally I wouldn't really bother. I also tried oeis.org formulas like floor(10/81 * 10^n - n/9) or (10^n * (9*n-1)+1)/81, but as expected it's way too long due to all the casts and Math.pow: 104 bytes. \$\endgroup\$ – Kevin Cruijssen Oct 24 '18 at 12:19
1
\$\begingroup\$

MathGolf, 6 bytes

£╒y_xα

Try it online!

£╒y_xα
£       Length of input array
 ╒      Range from 1 to n
  y     Join
   _x   Duplicate and reverse
     α  Wrap top two elements in array
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 43 bytes

Returns an array of 2 strings.

a=>a.map(_=>(a+=++i,b=i+b),i=a=b='')&&[a,b]

Try it online!

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

Python 2, 64 60 bytes

a=''.join(map(str,range(1,-~len(input()))))
print[a,a[::-1]]

Try it online!

-1 with thanks to @KevinCruijssen

-3 with thanks to @DeadPossum

\$\endgroup\$
  • 1
    \$\begingroup\$ You can remove the space at print[a] to save a byte. \$\endgroup\$ – Kevin Cruijssen Oct 24 '18 at 9:38
  • 2
    \$\begingroup\$ 60 bytes \$\endgroup\$ – Dead Possum Oct 24 '18 at 10:00
  • \$\begingroup\$ @KevinCruijssen - I shouldn't have missed that one :-/ \$\endgroup\$ – ElPedro Oct 24 '18 at 12:03
1
\$\begingroup\$

Python 2, 52 bytes

x=0
for _ in input():x=x*10+x%10+1
print x,`x`[::-1]

Try it online!

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

Haskell, 42 bytes

-4 bytes thanks to ovs.

((,)=<<reverse).(`take`"123456789").length

Try it online!

\$\endgroup\$
  • \$\begingroup\$ ((,)=<<reverse).(`take`"123456789").length works for 42 bytes. \$\endgroup\$ – ovs Oct 24 '18 at 17:17
  • 1
    \$\begingroup\$ ((,)<*>reverse).map fst.zip['1'..] \$\endgroup\$ – nimi Oct 24 '18 at 17:26
  • \$\begingroup\$ That's a fairly different approach, you can go ahead and post that. \$\endgroup\$ – totallyhuman Oct 24 '18 at 17:31
  • 1
    \$\begingroup\$ Nah, not that different, feel free to edit it in your post. \$\endgroup\$ – nimi Oct 24 '18 at 17:35
1
\$\begingroup\$

Jelly, 4 bytes

JṚƬḌ

Try it online!

How?

JṚƬḌ - Link: list L    e.g. ['ant','bee','cat','dog','elk','frog']
J    - range of length      [1,2,3,4,5,6]
  Ƭ  - 'till (collect up until results are no longer unique):
 Ṛ   -   reverse                         1:[6,5,4,3,2,1] , 2:[1,2,3,4,5,6]=1st
     -                  ->  [[1,2,3,4,5,6],[6,5,4,3,2,1]]
   Ḍ - from base ten        [123456,654321]
\$\endgroup\$
  • 5
    \$\begingroup\$ Whoever downvoted all the answers: poor show. \$\endgroup\$ – Jonathan Allan Oct 24 '18 at 20:20
1
\$\begingroup\$

Japt, 9 8 bytes

Êõ ¬pÔò¶

Try it


Explanation

Ê            :Length
 õ           :Range [1,Ê]
   ¬         :Join
    p        :Concatenate
     Ô       : Reverse
      ò      :Partition
       ¶     : Between equal characters
\$\endgroup\$
  • 2
    \$\begingroup\$ @Downvoter, please have the decency to leave a comment. \$\endgroup\$ – Shaggy Oct 24 '18 at 20:59
  • 1
    \$\begingroup\$ Whoever did it downvoted every single answer, so they don't have a reason except being a jerk.. \$\endgroup\$ – Kevin Cruijssen Oct 25 '18 at 7:24
0
\$\begingroup\$

Charcoal, 10 bytes

⟦⭆θ⊕κ⮌⭆θ⊕κ

Try it online! Link is to verbose version of code. Explanation:

  θ    θ    Input array
 ⭆    ⭆     Map over elements and join
    κ    κ  Current index (0-indexed)
   ⊕    ⊕   Increment
     ⮌      Reverse
⟦           Collect into an array
\$\endgroup\$
0
\$\begingroup\$

PowerShell, 39 bytes

-join(1..($x=$args.count));-join($x..1)

Try it online!

Takes input via splatting, which on the command-line prompt looks like, e.g., $a=(4,3,2); .\array-to-indices.ps1 @a, and on TIO manifests as separate arguments for each entry.

We take the .count of the input $args, store that into $x. Then construct a range .. from 1 up to $x and -join it into a string. Finally we -join the range the other direction. Those two strings are left on the pipeline and output is implicit.

\$\endgroup\$
0
\$\begingroup\$

Clean, 53 bytes

import StdEnv
$l#n=take(size l)['1'..]
=[n,reverse n]

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Scala (60 bytes)

def%(s:Seq[Any])={val a=(1 to s.size)mkString;(a,a.reverse)}

Try it online

\$\endgroup\$
0
\$\begingroup\$

J, 15 bytes

4(,:|.)@u:48+#\

Try it online!

How it works

4(,:|.)@u:48+#\
             #\  Generate 1-based indices of given array
          48+    Convert digits to ASCII value
4      @u:       Convert to string
 (,:|.)          Append its reverse
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 58 bytes

_=>[_.map((_,i)=>t.unshift(++i),t=[]),t].map(_=>+_.join``)

Try it online!

Pass current index of array plus 1 to .unshift() to fill first array with a second array's .length, .join() each resulting array without any characters separating elements and convert to integer. Returns an array of two integers.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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