# Create a shifter

To "shift" over a number n places, do the following:

• Remove the last n digits
• Add n copies of the first digit to the beginning of the number

For example, to shift the number 31415 three places, take out the last three digits to get 31, and then add three more copies of the first digit, 3, to the end, giving 33331.

If the number is negative, digits should be taken from the left instead, and the first digit should be "filled in" from the right. For example, the string 31415 shifted over -3 places gives 15555.

If the number is 0, no change should be made.

If the shift is more than the length of the program, then digits that were filled in might start to be removed. This means that if the number given is more than the length of the string, no further changes will be made after the entire string becomes a single digit.

## The challenge

Given two numbers, n and s, return n shifted over s places.

## Test cases

   n,  s -> result
7243,  1 -> 7724
452, -1 -> 522
12,  1 -> 11
153,  4 -> 111


This is , so the shortest valid submission (measured in bytes) wins.

• What's the winning criterion? Jul 18, 2017 at 22:14
• I don't think I understand what the "shifting" does. This is tagged [binary], which makes me think it has something to do with binary shifts. Maybe it would help to also display the numbers in binary in the test cases? Jul 18, 2017 at 22:19
• It's shifting and "stretching" the first or last digit. What's unclear? Jul 18, 2017 at 22:29
• yeah its pretty clear what they're asking Jul 18, 2017 at 22:33
• Shifting is well defined: integer multiplication or division by a power of the base. But none of the test cases work, so this question appears to use an idiosyncratic definition and not say what it is. Jul 19, 2017 at 6:54

# APL (Dyalog), 32 bytes

Anonymous function which takes the sift as left argument and the number (as a string) as right argument.

{a←|⍺⋄(≢⍵)↑(a-⍺)↓(a⍴⊃⍵),⍵,a⍴⊃⌽⍵}


Try it online!

{ anonymous function where and are left and right arguments

|⍺ the absolute value of the shift

a← store in a

⋄ then

⌽⍵ reverse the number

⊃ pick the first (i.e. last) digit

a⍴reshape it to length a

⍵, prepend the number

(), prepend the following:

⊃⍵ the first digit

a⍴reshape it to length a

()↓ drop the following number of characters:

a-⍺a minus the shift

()↑ take the following number of characters:

≢⍵ the length of the original number

# Python 2, 50 bytes

lambda n,s:(n[0]*s+n+n[-1]*-s)[-s*(s<0):][:len(n)]


Try it online!

## Haskell, 69 bytes

s#n|l<-[1..abs n]=take(length s)$drop(-2*n)$(s!!0<$l)++s++(last s<$l)


Takes the number as a string. Try it online!

How it works:

s#n                         -- s: input number as a string
-- n: shift amount

(s!!0<$l)++s++(last s<$l)   -- make a string:
-- n times the first digit, the whole number, n times the last digit
-- e.g. "567" 2 -> 5556777
drop(-2*n)                  -- drop the first (-2 * n) chars, i.e. 0 if n>0
take(length s)              -- take as may chars as there are in s


# MATL, 12 bytes

tn:i-yn1&Xl)


Inputs are: number to be shifted as a string; amount of shifting as a number.

Consisder inputs '452 and '-1'.

t     % Implicitly input string. Duplicate
% STACK: '452', '452'
n     % Number of elements
% STACK: '452', 3
:     % Range
% STACK: '452', [1 2 3]
i     % Input number
% STACK: '452', [1 2 3], -1
-     % Subtract, element-wise
% STACK: '452', [2 3 4]
y     % Duplicate from below
% STACK: '452', [2 3 4], '452'
n     % Number of elements
% STACK: '452', [2 3 4], 3
1     % Push 1
% STACK: '452', [2 3 4], 3, 1
&Xl   % Clamp, with three inputs. Applies min function, then max
% STACK: '452', [2 3 3]
)     % Reference indexing. Implicitly display
% STACK: '522'

• This is by far the least amount of bytes good job! Jul 19, 2017 at 19:44
• @KSplitX Thanks! BTW I just added an explanation Jul 19, 2017 at 21:17

# J, 37 bytes

This was one of those situations in J where an explicit verb seemed like the right (the only?) choice, but I would love to know if there's a tacit rewrite of this:

4 :'(-x)(|.!.((x>0)&{({:,{.)":y))":y'


J's built in shift verb allows you to configure the "fill" character:

|.!.f  NB. f is the fill character


The logic to determine whether to use the first or last char as the fill character is straightforward

(x>0)&{ ({: , {.)


Try it online!

# J, 23 bytes

(_&(]{.,],{:)~|)}.~_2*]


Input n and the output are strings containing the numbers.

Try it online!

## Explanation

(_&(]{.,],{:)~|)}.~_2*]  Input: 'integer n' as a string (LHS), integer s (RHS)
(              )         Extend 'n' by copying its head and tail 's' times
|            Abs(s)
_&(]       )~             Nest 'Abs(s)' times on 'n'
{:                 Tail
],                   Append the tail to itself
,                     Prepend the head to the previous
_2*]  Multiply 's' by -2
}.~      Drop abs(-2*s) from the head if 's' < 0 else from the tail

• beautiful. i suspected there was a better approach than mine... Jul 19, 2017 at 13:58
• although i notice you take n as a string which (possibly incorrectly ) id assumed was not allowed. though it would have saved me only 4 chars... Jul 19, 2017 at 14:12

# Retina, 61 bytes

\d+¶
$*1¶ +(?<!-).¶(.)(.*). ¶$1$1$2
-

+.¶.(.*)(.)$¶$1$2$2


Try it online!

# 05AB1E, 16 bytes

0‹©iR}¹ÄF¨¬ì}®iR


Try it online!

Explanation

0‹                 # input_1 is negative
©                # store a copy in register
iR}             # if true (input_1 is negative), reverse input_2
¹ÄF          # abs(input_1) times do
¨         # remove the last element
¬ì       # prepend the head
}      # end loop
®iR   # if input_1 was negative, reverse result


# Python 2, 87 bytes

f=lambda n,s:s<0and f(n[::-1],-s)[::-1]or n[0]*min(len(n),s)+n[:[0,len(n)-s][len(n)>s]]


Try it online!

Takes the number as a string, and the shift as an integer. Returns a string.

I tried embedding the reversal inside the function rather than making a recursive call, but I couldn't seem to get it right.

# Python 3, 73 bytes

f=lambda s,i:(f(s+1,i[1:]+i[-1])if s<0else f(s-1,i[0]+i[:-1]))if s else i


Try it online!

# Haskell, 108 bytes

Oh well, this went worse than I thought..

n#s=print$show n&s r=reverse n&s|s<0=r$r n&abs s|(a:b,c)<-splitAt s n=take(length n)$(a<$[0..s])++b++c|1>0=n


Try it online!

### Ungolfed

n # s = print \$ show n & s
n & s
| s < 0                = reverse (reverse n & abs s)
| (a:b,c)<-splitAt s n = take (length n) (replicate s a ++ b ++ c)
| otherwise            = n


## Clojure, 121 bytes

#(let[T(if(pos? %2)reverse vec)](apply str(concat(repeat %2(first %))(T(drop(Math/abs %2)(T %)))(repeat(- %2)(last %)))))


Ouch, nasty to deal with negative inputs as well.

# Pyth, 28 bytes

AQ=Y<+*hJ?K<0HG_GHJlJ?KY_Y


Explanation

AQ=Y<+*hJ?K<0HG_GHJlJ?KY_Y
AQ                           | Split Q into 2 parts, G and H.
J?K<0HG_G          | If 0 < H, J = str(G). Else, J = reverse(str(G)). Return J
h                     | Find 1st element
*            H         | Repeat H times
+              J        | Concatenate with J
<                lJ      | Find 1st length(J) elements
=Y                         | Assign to Y.
?KY_Y | If K, implicit print Y. Else implicit print reverse(Y).


# 05AB1E, 33 bytes

ÄF¹0‹©i¨ë¦}}²®i¤ë¬}sg¹Ä‚Ws\×®i«ëì


Try it online!

05AB1E is not so hot with conditionals.

# JavaScript, 80 bytes

(n,s,k=n.length,p=s<=0)=>n.slice(p*-s,p?k:-s)[p?"padEnd":"padStart"](k--,n[p*k])


Takes input as a string representation of the number and a numerical "shift" amount. Returns a string.

## Test Snippet

let f=
I.value="31415";J.value="3";D.oninput()
<div id=D oninput="O.value=I.value.length&J.value.length?f(I.value,+J.value):''">n: <input id=I size=10> s: <input id=J size=2><br><input id=O disabled>