17
\$\begingroup\$

Inputs:

Two single digits (let's call them m and n) and two chars (let's call them a and b) in your input format of choice.

Output:

For the walkthrough, pretend m=2, n=5, a='a', b='b'.

Your output will be a string built from your four inputs. Let's call the string result, with value "". First, concatenate a onto result m times, so concatenate a onto result 2 times. result now equals aa. Second, concatenate b onto result m times, so concatenate b onto result 2 times. result now equals aabb. Lastly, if result is already longer than n, truncate result so that it has length n. Otherwise, continue alternating with m length runs of a and b until result has length n. The final result is aabba, which has length 5.

Test Cases:

Input: m = 2, n = 4, a = A, b = B

Output: AABB

Input: m = 3, n = 8, a = A, b = B

Output: AAABBBAA

Input: m = 4, n = 3, a = A, b = B

Output: AAA

Input: m = 2, n = 10, a = A, b = B

Output: AABBAABBAA 

As all knows, lesser one will rule the world, so the smallest programs, in bytes, win! :)

\$\endgroup\$
11
  • \$\begingroup\$ What do you mean by "total char in output will be 'n'" and "lesser one will rule the world"? \$\endgroup\$ Jul 6, 2017 at 19:05
  • \$\begingroup\$ I basically rewrote the challenge, keeping what I believe was your original intent. You can rollback if you want, but in its original state it's not going to get reopened. \$\endgroup\$
    – Stephen
    Jul 6, 2017 at 19:13
  • \$\begingroup\$ @StepHen you saved my day:p gracias :) \$\endgroup\$
    – Durga
    Jul 6, 2017 at 19:16
  • \$\begingroup\$ @Durga no problem :) I'm glad it still says what you wanted. \$\endgroup\$
    – Stephen
    Jul 6, 2017 at 19:17
  • 2
    \$\begingroup\$ @Durga proposed test case : m=2,n=10,a=A,b=B \$\endgroup\$
    – Rod
    Jul 6, 2017 at 19:21

25 Answers 25

8
\$\begingroup\$

Python, 32 bytes

lambda m,n,a,b:((a*m+b*m)*n)[:n]

Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ Anonymous functions are allowed last I checked so you can remove the f= for -2 bytes. \$\endgroup\$
    – sporkl
    Jul 6, 2017 at 19:54
  • \$\begingroup\$ @ComradeSparklePony: Thanks for the heads up. That was leftover from the TiO; I'd actually already removed it from the byte count. \$\endgroup\$ Jul 6, 2017 at 20:01
  • 2
    \$\begingroup\$ You can put the f= in the header section of TIO, so you don't need to remove it manually. TIO \$\endgroup\$
    – ovs
    Jul 6, 2017 at 20:15
  • \$\begingroup\$ Ah, I always forget about backslashes. Thanks. \$\endgroup\$ Jul 6, 2017 at 20:28
  • 1
    \$\begingroup\$ To whoever suggested editing (a*m+b*m) -> (a+b)*m: this does not work. \$\endgroup\$ Jul 7, 2017 at 1:28
6
\$\begingroup\$

MATL, 5 bytes

Y"i:)

Inputs are a string with the two characters, then m, then n.

Try it online!

Explanation

Y"   % Implicit inputs: string and number m. Apply run-length decoding.
     % The second input is reused for each char in the first. Gives a
     % string
i    % Input number n
:    % Push vector [1 2 ... n]
)    % Index the string with the numbers in that vector. Indexing is
     % modular, so the chars are reused if necessary. Implicit display
\$\endgroup\$
5
\$\begingroup\$

Haskell, 44 40 bytes

f=(.cycle).take
(n#m)a=f n.(f m a++).f m

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Ruby, 29 characters

->m,n,a,b{((a*m+b*m)*n)[0,n]}

Sample run:

irb(main):001:0> ->m,n,a,b{((a*m+b*m)*n)[0,n]}[3, 8, 'A', 'B']
=> "AAABBBAA"

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Japt, 10 bytes

VîUçW +UçX

First try using a golfing language. Try it online!

Explanation

Vî          // repeat the following until it reaches length V (second input)
  UçW       // third input repeated U (first input) times
      +UçX  // plus the fourth input, repeated U times
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for using Japt, and well done :-) You could do VîWpU +XpU too, but both do the same thing. is perfect for this challenge. \$\endgroup\$ Jul 7, 2017 at 0:16
  • \$\begingroup\$ @ETHproductions Thanks, and thanks for making it! I really enjoy how everything transpiles nicely to JS code. \$\endgroup\$ Jul 7, 2017 at 0:39
3
\$\begingroup\$

05AB1E, 5 bytes

×J×I£

Try it online!

Explanation

×      # repeat a and b m times each
 J     # join to string
  ×    # repeat the string n times
   I£  # take the first n characters
\$\endgroup\$
1
  • \$\begingroup\$ Exactly what I got without checking first :P \$\endgroup\$ Jul 13, 2017 at 14:17
3
\$\begingroup\$

Jelly, 6 4 bytes

xFṁ⁵

Try it online!

Thanks to Jonathan Allan for better input format (-2).

\$\endgroup\$
2
  • \$\begingroup\$ 4 bytes as a full program with a different input format \$\endgroup\$ Jul 6, 2017 at 20:06
  • \$\begingroup\$ @JonathanAllan Heh I usually try to avoid using the third argument but this time it makes my answer way shorter. \$\endgroup\$ Jul 7, 2017 at 9:05
3
\$\begingroup\$

V, 13 bytes

ÀäjÀäêÍî
À|lD

Try it online!

a and b are taken on separate lines in the input, m and n are taken as argument, reversed (so n is the first argument and m is the second)

Explanation

Àäj      ' duplicate the inputs [arg 1] times
a -> a
b    b
     a
     b
     ...
   Àäê   ' duplicate everything straight down [arg 2] times - À cycles arguments
a -> aaa
b    bbb
a    aaa
b    bbb
...  ...
      Íî ' remove all newlines
-> aaabbbaaabbb...
À|lD     ' delete from the [arg 1] + 1 column onwards
-> aaabbbaa
\$\endgroup\$
3
\$\begingroup\$

Haskell, 36 35 29 bytes

Yet another Haskell solution (expects the characters given as a list):

(m#n)c=take n$cycle$c<*[1..m]

Try it online!

Thanks @Laikoni for -1 byte.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can save a byte with (m#n)a b=. \$\endgroup\$
    – Laikoni
    Jul 13, 2017 at 7:20
3
\$\begingroup\$

R, 41 39 bytes

function(d,m,n)cat(d[gl(2,m,n)],sep='')

An anonymous function; prints the result to stdout. Takes the characters as a vector d=c(a,b). gl generates factors (integers) of (in this case) 2 levels of run length m with total length n! cat concatenates and prints them as a string.

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ I think function(d,m,n)rep(d,e=m,l=n) would be a valid submission. \$\endgroup\$
    – ovs
    Jul 8, 2017 at 12:27
  • \$\begingroup\$ @ovs unfortunately rep will result in a vector of characters rather than a single string \$\endgroup\$
    – Giuseppe
    Jul 12, 2017 at 19:49
2
\$\begingroup\$

Javascript, 55 bytes

(m,n,a,b)=>(a[r='repeat'](m)+b[r](m))[r](n).substr(0,n)

Example code snippet:

f=

(m,n,a,b)=>(a[r='repeat'](m)+b[r](m))[r](n).substr(0,n)

console.log(f(2, 4, 'A', 'B'))
console.log(f(3, 8, 'A', 'B'))
console.log(f(4, 3, 'A', 'B'))
console.log(f(2, 9, 'A', 'B'))

\$\endgroup\$
2
\$\begingroup\$

Javascript, 53 bytes

(m,n,a,b)=>a.repeat(n).replace(/./g,(i,j)=>j/m&1?b:i)
\$\endgroup\$
2
\$\begingroup\$

Husk, 3 bytes

Direct Port of my Haskell answer, except that the argument order is different:

↑¢Ṙ

Try it online!

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

Haskell, 48 43 bytes

(m#n)a|r<-(<$[1..m])=take n.cycle.(r a++).r

Try it online!

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

QBIC, 37 27 bytes

[:|G=;+G+;][:|G=G+G]?_sG,d

Explanation

          This takes its arguments as frequency m, A, B, length n
          For example: 2, A, B, 8
 :        Read a cmd line arg as number 'b' ('a' is used by the FOR declaration as loop counter)
[ |       Start a FOR loop, from 1 to b
G=  G     Set G to hold itself
  ;+      prepended by a cmd line arg read as strig and assigned to A$
     +;   and followed by a cmd line arg read as strig and assigned to B$
]         At the end of the FOR loop, G has had A added to the front twice, and B t the end x2: G$ = AABB
[:|       FOR c = 1 to n
G=G+G]      Add G to itself          G$ = AABBAABBAABBAABBAABBAABBAABBAABB
?_sG,d    PRINT the first n chars of G$   AABBAABB

Previous attempt:

(37b)  {Z=Z+;┘_LZ|~a=:|_X]~a%:|\C=A┘A=;┘B=C
Takes its arguments as `A, length n, frequency m, B`.
Basically adds A to Z until length % freq = 0, then swaps A for B. Loops until lengtn = n
\$\endgroup\$
1
\$\begingroup\$

PHP>=7.1, 77 bytes

for([,$x,$l,$f,$s]=$argv;$l-=$z;)echo str_repeat(++$i&1?$f:$s,$z=min($l,$x));

PHP Sandbox Online

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

Java (OpenJDK 8), 75 bytes

void f(int m,int n,char[]s){for(int i=0;i<n;)System.out.print(s[i++/m%2]);}

Try it online!

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

Cubix, 63 58 bytes

.rr.@u:s?.\.sw).i|>v:.\nB;?(q:Is...;rr/s.uw/....sIB/\/?(qo

Try it online!

watch the interpreter

Takes input like ab*m*n where the * can be any non-digit character.

Cube version:

        . r r .
        @ u : s
        ? . \ .
        s w ) .
i | > v : . \ n B ; ? ( q : I s
. . . ; r r / s . u w / . . . .
s I B / \ / ? ( q o . . . . . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .
  • i|is : read in the chars, and swap them (so a is on top)
  • I:q : read in m, dup, and push to bottom (stack is now m,b,a,m)
  • ) : decrement
  • ? : turn right if positive, go straight if zero (duplicates a)
  • positive branch (loop)
    • s:rur(/w : swap, dup, move m-i to the top of the stack, decrement m-i
  • zero branch
    • B : reverse stack (which now has m copies of a: a... b m)
    • n : negate m (so we can use ? to turn left)
    • ) : increment
    • ? : go straight if zero, turn left if negative
  • negative branch (duplicates b)
    • s:r\/rw)\ basically the same as the positive branch but with increment and left turns.
  • zero branch (prints the output)
    • >v; : pop the 0 off the stack (looks like a...b...)
    • /B : reverse the stack
    • I : read n
    • s : swap print loop:
  • oq : print and push to bottom of stack now looks like: ab...a...n
  • ( decrement n
  • ? : turn right if positive, go straight if zero
  • If right, : /su : swap top of stack and continue the loop
  • if zero, / reflects down and the code evaluated is Iru@; @ terminates the program.
\$\endgroup\$
0
\$\begingroup\$

Charcoal, 10 bytes

…⁺×ζIθ×εNN

Try it online! Link is to verbose version of code and includes fourth example. (Annoyingly the deverbosifer won't remove the separator if I add one before the last InputNumber().)

\$\endgroup\$
2
  • \$\begingroup\$ What do you mean by the separator? (Can you give an example) \$\endgroup\$
    – ASCII-only
    Jul 27, 2017 at 3:12
  • \$\begingroup\$ @ASCII-only With the comma before the last InputNumber(), notice that the generated code has an unnecessary separator: Try it online! \$\endgroup\$
    – Neil
    Jul 27, 2017 at 7:51
0
\$\begingroup\$

Mathematica , 61 bytes

T=Table;StringTake[""<>Flatten@T[{#3~T~#,#4~T~#},⌈#2/#⌉],#2]&

input

[2,10,"A","B"]

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

Mathematica, 44 bytes

StringPadRight[x={##3}~Table~#<>"",#2,x]&

Explanation

is the three byte private use character U+F3C7, representing the postfix \[Transpose] operator in Mathematica. No TIO link because Mathics does not support , \[Transpose] has the wrong operator precedence, the second argument to Table is required to be a list, and most importantly, StringPadRight is not implemented.

                                         & (* Function *)
                 {##3}                     (* which takes the third and fourth arguments *)
                      ~Table~#             (* repeats them a number of times equal to the first argument *)
                                          (* takes the tranpose *)
                               <>""        (* then joins the strings with the empty string *)
               x=                          (* sets x equal to that string *)
StringPadRight[                            (* then pads x *)
                                   ,#2     (* to a length equal to the second argument *)
                                      ,x]  (* with x. *)
\$\endgroup\$
0
\$\begingroup\$

APL (Dyalog), 5 bytes

⎕⍴⎕/⎕

Try it online!

Takes the two chars in a string as the first input, followed by m and then n.

Explanation

Let the example input be 'ab', 2, 10.

⎕/⎕                 Replicate the two-char string `m` times
                    2/'ab' => 'aabb'
⎕⍴                  Shape it so that its length is `n`
                    10⍴'aabb' => 'aabbaabbaa'
\$\endgroup\$
0
\$\begingroup\$

Pyth, 13 bytes

KE<*+*EQ*EQKK

Try it online!

Explanation

                 # Implicitly store m to Q
KE               # Store n to K
     *EQ         # Perform a * m
        *EQ      # Perform b * m
    +            # Concatenate the two strings
   *       K     # Multiply by n
  <         K    # Take the first n characters of the string
\$\endgroup\$
0
\$\begingroup\$

k, 10 bytes

{y#,/x#'z}

Try it online!

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

Chip, 588 bytes

*Z~vZ.*ZZZs  z. z. z. z. z. z. z. z.
  ,'|`-. ZZ--#<,#<,#<,#<,#<,#<,#<,#<
a/mAM/a| `~S `x'`x'`x'`x'`x'`x'`x'`x.
b/mBM/b|  *.)/')/')/')/')/')/')/')/'|
c/mCM/cZv--x^x-^x-^x-^x-^x-^x-^x-^x-'
d/mDM/d||A~#M',-',-',-',-',-',-',-'
e/mEM/e||B~#M-',-',-',-',-',-',-'
f/mFM/f||C~#M--',-',-',-',-',-'
g/mGM/g||D~#M---',-',-',-',-'
h/mHM/h||E~#M----',-',-',-'
 `v~v' ||F~#M-----',-',-'
* `mz  ||G~#M------',-'
Z  `---x'H~#M-------'
Z,--z--^----'
Z|z. z. z. z. z. z. z. z.
Zx#<,#<,#<,#<,#<,#<,#<,#<
 |`x'`x'`x'`x'`x'`x'`x'`xT
 |A| B| C| D| E| F| G| H|
 )\')\')\')\')\')\')\')\'
 `--^--^--^--^--^--^--'

Try it online!

Takes input as a 4-character string. The first two are the characters a and b, followed by the byte value m, and then the byte value n. For example, the TIO includes input ab<tab>2, this corresponds to 'a', 'b', 9, 50. (Since the codes for <tab> and 2 are 9 and 50.

How?

This answer is a bit of a behemoth, but here's the highlights:

The upper left block, with the lowercase a-h, is the storage mechanism for the characters a and b, one line per bit. At its bottom, with the v~v and mz is the switching mechanism, to swap between the two.

In the middle is a column with a bunch of ~#M's. This reads in m and stores its negative. The big triangle to the right is just wires to bring this value into the upper accumulator.

The upper right block is the accumulator for m. It increments every cycle (starting from -m) until it reaches zero. When this happens, the output character is swapped, and counting restarts from -m.

Meanwhile, there is the lower block, which is the n accumulator. Since n is only read once, we don't need a bank of memory (M and m) to store this value. We simply negate it and start counting. When this value reaches zero, the whole shebang is simply terminated.

All the other guff is delays (Z and z), wiring (-, |, ...), and other miscellany.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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