| Bytes | Lang | Time | Link |
|---|---|---|---|
| 147 | APLNARS | 250708T075232Z | Rosario |
| 178 | Julia | 250705T212515Z | Joss |
| 005 | Vyxal 3 | 250704T141501Z | Themooni |
| 032 | CJam | 150128T234737Z | Martin E |
| 142 | Python 2 | 150131T035124Z | FryAmThe |
| 033 | Pyth | 150129T224206Z | FryAmThe |
| 151 | Ruby | 150130T000209Z | britisht |
| 163 | JavaScript | 150129T172007Z | edc65 |
| 166 | Matlab | 150129T123132Z | Luis Men |
| 164 | J | 150129T204342Z | joebo |
| 034 | CJam | 150129T172014Z | jimmy230 |
| 192 | Scala | 150129T145813Z | gilad ho |
| 418 | C# | 150129T135700Z | Krzyszto |
| 179 | Python 2 | 150128T233118Z | KSFT |
APL(NARS), 147 chars
r←a f w;i;c;q
→0×⍳0=≢r←⎕av⍳a⋄r←∊{(8⍴2)⊤¯1+⍵}¨r⋄i←1⋄q←,w
→0×⍳i>≢q⋄c←q[i]
→4×⍳∼c='u'⋄r←⌽r
→5×⍳∼c='f'⋄r←∼r
→6×⍳∼c='l'⋄r←1⌽r
→7×⍳∼c='r'⋄r←¯1⌽r
i+←1⋄→2
This could be ok for subset has <=8 bits as address of AV array.
for the few test exercise has is almost sure some error.
Julia (204 178 bytes)
f(p,i)=reduce(∘,reverse([[x->x[end]*x[1:end-1],x->x[2:end]*x[1],x->string([Char('a'-c) for c in x]...),reverse][l-'0'] for l in i]))(string([bitstring(UInt8(c)) for c in p]...))
r, l, f and u are inputted as 1, 2, 3 and 4 respectivley.
It's 177 characters, but the functional chaining operator is outside of ASCII. Also note that reduce cannot handle an empty list of functions, so f("something", "") will error.
(Slightly) Ungolfed:
cmd_lst = [x -> x[end] * x[1:end-1],
x -> x[2:end] * x[1],
x -> string([Char('a' - ch) for ch in x]...),
reverse]
f(plaintext, instructions) = reduce(∘, reverse([cmd_lst[instruction - '0'] for instruction in instructions]))(string([bitstring(UInt8(ch)) for ch in plaintext]...))
(Edited to replace the dictionary command lookup with a list, now placed inline inside the reverse() call.)
Vyxal 3, 5 bytes
Bf?ᴥ“
lis↺ris↻fiseuis⇄
turns out, vyxal has the exact commands needed if you're a bit creative.
Bf?ᴥ“
Bf # convert input to binary string
?ᴥ # execute second argument as vyxal code
“ # join result
💎
Created with the help of Luminespire.
<script type="vyxal3">
Bf?ᴥ“
</script>
<script>
args=[["b","↻e⇄"],["AB",""],["AB","↺"],["AB","↻"],["AB","e"],["AB","⇄"]]
</script>
<script src="https://themoonisacheese.github.io/snippeterpreter/snippet.js" type="module"/>
CJam, 34 32 bytes
1l+256b2b1>l{~"11W:mm%!<>">4%~}/
It uses the following characters for instructions:
0: left rotation
1: right rotation
2: reverse
3: flip
The input is taking from STDIN with the word on the first line and the instruction string on the second line.
Explanation
Getting the bit string is really just a matter of interpreting the character codes as the digits of a base-256 number (and getting its base-2 representation). The tricky thing is that the latter base conversion won't pad the result with 0s on the left. Therefore, I add a leading 1 to the initial input, and then split off that 1 again in the binary representation. As an example, if the input is ab, I turn that into an array [1 'a 'b], interpret that as base-256 (characters are automatically converted to character codes), which is 90466 and the to base-2, which is [1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0]. Now if I just remove that leading 1 I've got the bitstream I'm looking for.
That's what this part of the code does:
1l+256b2b1>
Now I read the list of instructions and execute a block for each character in the instruction string:
l{...}/
The first thing to do is to evaluate the character and actual integers0, 1, 2 or 3. Now the real golfy magic... depending on the instruction I want to run a short piece of code that implements the operation:
Integer: Code Operation
0 1m< "Left rotation";
1 1m> "Right rotation";
2 W% "Reverse";
3 :! "Flip each bit";
I could store these in an array of blocks and choose the right block to run, but encoding them in a string is actually shorter:
"11W:mm%!<>">4%~
First, I use the integer associate with the instruction to slice off the beginning of the string. So for left rotation, the string is unchanged, for right rotation the first character is discarded and so on. Then I select every fourth character from the string, starting from the first, with 4%. Notice how the four code snippets are distributed throughout the string. Finally I just evaluate the string as code with ~.
The bit string is printed automatically at the end of the program.
Python 2, 142
j="".join
f=lambda S,I:reduce(lambda s,i:[s[1:]+s[0],s[-1]+s[:-1],s[::-1],j([`1^int(c)`for c in s])][int(i)],I,j([bin(ord(c))[2:]for c in S]))
Similar to my pyth answer in approach: I build a list of all the strings and index into it based on the value of the instruction string that I iterate over using reduce.
Uses:
0 -> Rotate left
1 -> Rotate right
2 -> Reverse order
3 -> Invert bits
Pyth 33
jku@[+eGPG+tGhG_Gms!dG)sHwsmjCk2z
Uses:
0 : rotate right
1 : rotate left
2 : reverse order
3 : flip values
This is a program that takes the string as it's first argument and the string of commands as the second argument. In the online version, you should give the strings separated by a newline, like so:
AbC
0321
Explanation:
: z=input() (implicit)
jk : join("", ...)
u@[ )sHw : reduce(select from [...] the value at int(H), input(), ...)
+eGPG : [ G[-1] + G[:1],
+tGhG : G[1:] + G[1],
_G : G[::-1],
ms!dG : map(lambda d: int(not(d)), G) ]
smjCk2z : first arg = sum(map(lambda k:convert_to_base(ord(k),2),z)
Something I couldn't quite squeeze in: Pyth's reduce automatically uses G for the previous value, and H for the next value.
Ruby, 151
f=->i,s{s.chars.inject(i.unpack("B*")[0]){|a,c|
a.reverse! if c==?u
a.tr!"01","10" if c==?f
a<<a.slice!(1..-1) if c==?l
a<<a.slice!(0..-2) if c==?r
a}}
Fairly straightforward. Loops trough the characters in s and performs an action for any of them.
JavaScript (E6), 163 167
Fully using the input flexibility, a named function with 2 array parameters.
- First parameter, array of bytes corresponding to 7 bit character codes
- Second parameter, array of bytes corresponding to ascii characters 'F','L','R','U' --> 70, 76, 82, 85
The function returns a character string composed of '1' and '0'
F=(a,s,r='')=>
a.map(c=>r+=(128|c).toString(2).slice(-7))-
s.map(c=>a=c<71?a.map(c=>1-c):c<77?a.concat(a.shift):c<83?[a.pop(),...a]:a.reverse(),a=[...r])
||a.join('')
Example f("b", "rfu") translate to F([98],[82,70,85]), result is 0111001
Note using character strings is so much longer in javascript! Byte count 186
F=(a,s,r='')=>
[for(c of a)r+=(128|c.charCodeAt()).toString(2).slice(-7)]-
[for(c of(a=[...r],s))a=c<'G'?a.map(c=>1-c):c<'M'?a.concat(a.shift):c<'S'?[a.pop(),...a]:a.reverse()]
||a.join('')
Example F("b", "RFU"), result is 0111001 again
Matlab (166 bytes)
This uses letters abcd instead of lrfu respectively.
function D=f(B,C)
D=dec2bin(B,8)';
D=D(:);
g=@circshift;
for c=C
switch c-97
case 0
D=g(D,-1);
case 1
D=g(D,1);
case 2
D=char(97-D);
case 3
D=flipud(D);
end
end
D=D';
Some tricks used here to save space:
- Using
abcdletters lets me subtract97once, and then the letters become0,1,2,3. This saves space in theswitch-caseclauses. - Defining
circshiftas a one-letter anonymous function also saves space, as it's used twice. - Since
Dconsists of'0'and'1'characters (ASCII codes48and49), the statementD=char(97-D)corresponds to inversion between'0'and'1'values. Note that this97has nothing to do with that referred to above. - Complex-conjugate transpose
'is used instead of transpose.'.
J, 164
([: >@:}. (([: }. >&{.) ; >@:{.@:>@:{. 128!:2 >@:}.)^:({.@:$@:>@:{.))@:(>@:((<;._1 ' 1&|."1 _1&|."1 -. |."1') {~ 'lrfu' i. 0&({::)@:]) ; ;@:([: (8$2)&#: a. i. 1&({::)))
Formatted:
nextop=:([: }. >&{.)
exec=: (>@:{.@:>@:{.) apply"1 >@:}.
times=: ({.@:$@:>@:{.)
gapply=: [: >@:}. (nextop ; exec)^:(times) f.
tobin=: ;@:([: (8#2)&#:(a.i.1&{::))
g=:'1&|.';'_1&|.';'-.';'|.'
tog =: g {~ ('lrfu' i. 0&{::@:])
golf=: gapply @: (>@:tog;tobin) f.
Example
golf ('rfu';'b')
0 1 1 1 0 0 1 1
golf ('lruuff';'b')
0 1 1 0 0 0 1 0
(8#2)#: 98
0 1 1 0 0 0 1 0
golf ('lruuff';'AB')
0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0
tobin '';'AB'
0 1 0 0 0 0 0 1 0 1 0 0 0 0 1 0
CJam, 34 bytes
Another approach in CJam.
1l+256b2b1>l_S/,1&@f=_,,@f{W%~}\f=
The input text is on the first line and the instructions are on the second line.
Instructions:
) Rotate left.
( Rotate right.
(space) Flip.
~ Reverse.
Scala - 192
def f(i:String,l:String)=(i.flatMap(_.toBinaryString).map(_.toInt-48)/:l){
case(b,'l')⇒b.tail:+b.head
case(b,'r')⇒b.last+:b.init
case(b,'f')⇒b.map(1-_)
case(b,'u')⇒b.reverse}.mkString
C#, 418 bytes
using System;using System.Collections.Generic;using System.Linq;class P{string F(string a,string o){var f=new Dictionary<char,Func<string,IEnumerable<char>>>{{'l',s=>s.Substring(1)+s[0]},{'r',s=>s[s.Length-1]+s.Substring(0,s.Length-1)},{'u',s=>s.Reverse()},{'f',s=>s.Select(c=>(char)(97-c))}};return o.Aggregate(string.Join("",a.Select(c=>Convert.ToString(c,2).PadLeft(8,'0'))),(r,c)=>new string(f[c](r).ToArray()));}}
Formatted:
using System;
using System.Collections.Generic;
using System.Linq;
class P
{
string F(string a, string o)
{
// define string operations
var f = new Dictionary<char, Func<string, IEnumerable<char>>>
{
{'l', s => s.Substring(1) + s[0]},
{'r', s => s[s.Length - 1] + s.Substring(0, s.Length - 1)},
{'u', s => s.Reverse()},
{'f', s => s.Select(c => (char) (97 - c))}
};
// for each operation invoke f[?]; start from converted a
return o.Aggregate(
// convert each char to binary string, pad left to 8 bytes and join them
string.Join("", a.Select(c => Convert.ToString(c, 2).PadLeft(8, '0'))),
// invoke f[c] on result of prev operation
(r, c) => new string(f[c](r).ToArray())
);
}
}
Python 2 - 179
b="".join([bin(ord(i))[2:]for i in input()])
for i in input():b=b[-1]+b[:-1]if i=="r"else b[1:]+b[0]if i=="l"else[str("10".find(j))for j in b]if i=="f"else b[::-1]
print"".join(b)