16
\$\begingroup\$

Given two inputs, a string \$s\$ and a decimal number \$n\$, output the string multiplied by that number.

The catch is that the number can be a float or an integer.

You should output the string \$\lfloor n \rfloor\$ times and then the first \$\lfloor (n - \lfloor n \rfloor) \cdot |,円s,円|)\rfloor\$ characters again.

Other notes:

  • The input will not always be a float, it may be an integer. So 1.5, 1, and 1.0 are all possible. It will always be in base 10 though, and if you wish an exception please comment.
  • The string input may contain white space except newlines, quotes and other characters. Control characters are excluded, too, if this helps.
  • No built-ins for direct string repetition are allowed. That means for instance Python’s 'a'*5 is forbidden. Nevertheless string concatenation (frequently denoted by the + sign) is allowed.

Test cases

\$s\$ \$n\$ result
test case 1 test case
case 2.5 casecaseca
(will add more later) 0.3333 (will
cats >= dogs 0.5 cats >

Final Note

I am seeing a lot of answers that use builtin string multiplication or repetition functions. This is not allowed. The rule is: If it directly multiplies the string, you cannot do it.

Kai Burghardt
1,2042 gold badges11 silver badges15 bronze badges
asked Feb 8, 2016 at 15:42
\$\endgroup\$
7
  • \$\begingroup\$ The wording was modified repeatedly (I did not see the first revision). I suggest to remove direct string repeating (what does this mean?). But all in all you're right \$\endgroup\$ Commented Feb 8, 2016 at 16:10
  • 1
    \$\begingroup\$ Related quine version \$\endgroup\$ Commented Feb 8, 2016 at 16:47
  • \$\begingroup\$ @Sp3000 yeah, I know. I think the difference is significant enough. \$\endgroup\$ Commented Feb 8, 2016 at 17:18
  • \$\begingroup\$ "No built-ins for direct string repeating, even string multiplication like the python 'a'*5 are allowed." You don't explain the difference between these. They sound the same to me. \$\endgroup\$ Commented Feb 8, 2016 at 20:50
  • \$\begingroup\$ @edc65 In Perl you can do list repetition then concatenate the elements of that list, which isn't direct string repetition. In Perl 5: join "", ("case") x 2 vs "case" x 2, in Perl 6 [~] "case" xx 2 vs the same "case" x 2 \$\endgroup\$ Commented Feb 8, 2016 at 20:59

23 Answers 23

7
\$\begingroup\$

Java 7, 89

void g(char[]a,float b){for(int i=0,l=a.length;i<(int)(l*b);)System.out.print(a[i++%l]);}

takes char[] and float and outputs to STDOUT. basic looping.

answered Feb 8, 2016 at 16:31
\$\endgroup\$
4
  • 3
    \$\begingroup\$ Good golfing, even for java. :P \$\endgroup\$ Commented Feb 8, 2016 at 16:33
  • \$\begingroup\$ this was suggested on my other answer too, but i don't think i will do this. it does not seem right to me. \$\endgroup\$ Commented Feb 8, 2016 at 16:44
  • \$\begingroup\$ Eh, fair enough. It is recognized here, but alright. :D \$\endgroup\$ Commented Feb 8, 2016 at 16:44
  • \$\begingroup\$ I recommend declaring your language as Java 7. Then no one can tell you to use lambdas. \$\endgroup\$ Commented Feb 8, 2016 at 16:46
6
\$\begingroup\$

Pyth, (削除) 9 (削除ここまで) 8

s@Lz*lzQ

Saved 1 byte thanks to Pietu1998

This takes floor(n * len(string)) letters from the string, using cyclical indexing. I believe this is always equivalent to the given formula.

Test Suite

answered Feb 8, 2016 at 15:56
\$\endgroup\$
4
  • 1
    \$\begingroup\$ No plz don't take this from me this soon. xD \$\endgroup\$ Commented Feb 8, 2016 at 16:02
  • \$\begingroup\$ @VoteToClose I actually didn't read your answer at all, scouts honour :P I didn't even realise that string repetitions were disallowed, this was just shorter that what I came up with that way... \$\endgroup\$ Commented Feb 8, 2016 at 16:14
  • 1
    \$\begingroup\$ You don't even need the second s. range is funny like that. \$\endgroup\$ Commented Feb 8, 2016 at 19:47
  • 1
    \$\begingroup\$ NOO! cries in a corner Ah, oh well. \$\endgroup\$ Commented Feb 8, 2016 at 19:54
6
\$\begingroup\$

JavaScript (ES6), 50 bytes

Edit 2 bytes more to include definition of function f. 1 byte less using the tip of @manatwork. Note: using ~ we have more iterations than necessary, but this is code golf and even 1 byte counts

f=(s,n,l=s.length*n)=>~n?f(s+s,n-1,l):s.slice(0,l)

TEST

f=(s,n,l=s.length*n)=>~n?f(s+s,n-1,l):s.slice(0,l)
//TEST
console.log=x=>O.textContent+=x+'\n'
;[
 ['test case', 1, 'test case'],
 ['case', 3.5, 'casecasecaseca'],
 ['(will add more later)', 0.3333, '(will '],
 ['cats >= dogs', 0.5, 'cats >']]
.forEach(t=>{
 var s=t[0],n=t[1],x=t[2],r=f(s,n);
 console.log("«"+s+"» "+n+' => «'+r+'» '+(x==r?'OK':'FAIL expected '+x));
 })
<pre id=O></pre>

Riker
7,9284 gold badges40 silver badges73 bronze badges
answered Feb 8, 2016 at 15:52
\$\endgroup\$
5
  • \$\begingroup\$ Okay, thanks. So far most of the answers have had no problem, and it is really easy to fix. Thanks for correcting it. \$\endgroup\$ Commented Feb 8, 2016 at 16:28
  • \$\begingroup\$ Tiny typo: n>0 in the code vs. n>1 in the test case. \$\endgroup\$ Commented Feb 8, 2016 at 16:38
  • \$\begingroup\$ Oh. Indeed. But then why not just ~n? (Really just a question. Tried only the given test cases.) \$\endgroup\$ Commented Feb 8, 2016 at 17:42
  • 3
    \$\begingroup\$ @edc65 Where is f defined in your solution? Aren't you missing f=? \$\endgroup\$ Commented Feb 8, 2016 at 18:38
  • \$\begingroup\$ @dev-null oh oh oh you'r perfectly right, this is recursive. My fault. Thanks for pointing it out \$\endgroup\$ Commented Feb 8, 2016 at 21:21
4
\$\begingroup\$

Jelly, 5 bytes

×ばつL}Rị

Doesn't use a repetition built-in. Try it online!

How it works

×ばつL}Rị Main link. Left input: n (multiplier). Right input: S (string)
 L} Yield the length of ×ばつ Multiply it with n.
 R Range; turn n×ばつlen(S) into [1, ... floor(n×ばつlen(S))].
 ị Retrieve the elements of S at those indices.
 Indices are 1-based and modular in Jelly, so this begins with the first and
 jump back after reaching the last.
answered Feb 8, 2016 at 20:06
\$\endgroup\$
0
4
\$\begingroup\$

Vitsy, 9 bytes

Expects the word as an argument, and the number to multiply by through STDIN.

zlW*\[DO{]
z Grab all string argument input.
 l Get the length of the stack.
 W Parse STDIN.
 * Multiply the top two items (length of string and the number of repetitions)
 \[ ] Do the stuff in the loop.
 DO{ Output one char at a time, making sure to duplicate first.

Try it online!

answered Feb 8, 2016 at 15:47
\$\endgroup\$
5
  • \$\begingroup\$ True to your word, you answered fast. \$\endgroup\$ Commented Feb 8, 2016 at 15:48
  • \$\begingroup\$ @RikerW Martin out FGITW'd me. \$\endgroup\$ Commented Feb 8, 2016 at 15:51
  • \$\begingroup\$ Why do you Grab all string argument input. and then Parse STDIN. again? \$\endgroup\$ Commented Feb 8, 2016 at 16:08
  • \$\begingroup\$ @RikerW Arguments that are doubles are automatically parsed, pushing them to the stack immediately. Handling that takes more bytes than it's worth. \$\endgroup\$ Commented Feb 8, 2016 at 16:09
  • \$\begingroup\$ Oh okay. That makes more sense now. \$\endgroup\$ Commented Feb 8, 2016 at 16:10
3
\$\begingroup\$

CJam, 10 bytes

l_,l~*,\f=

The string is supplied on the first line of STDIN, the float on the second.

Test it here.

Explanation

l e# Read string.
_, e# Duplicate and get its length.
l~ e# Read second line and evaluate.
* e# Multiply them. If the result, N, was floored it would give us the number of
 e# characters in the required output.
, e# Get range [0 1 ... ⌊N⌋-1].
\f= e# For each character in that range, fetch the corresponding character from the
 e# string using cyclic indexing.
answered Feb 8, 2016 at 15:46
\$\endgroup\$
3
\$\begingroup\$

Python 2, 71 bytes

lambda s,x:"".join(s for i in range(int(x)))+s[:int(len(s)*(x-int(x)))]

Try it here!

Creates an unnamed lambda which takes the string as first argument and the float as second. Returns the repeated string.

This could be 46 if string repetition builtins were allowed :(

answered Feb 8, 2016 at 16:08
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Much sad. Such string multiplication rules. +1 A+ for effurt. \$\endgroup\$ Commented Feb 8, 2016 at 16:15
3
\$\begingroup\$

Ruby, (削除) 49 (削除ここまで) 48 characters

->s,n{(0...(n*l=s.size).to_i).map{|i|s[i%l]}*''}

Sample run:

2.1.5 :001 > ->s,n{(0...(n*l=s.size).to_i).map{|i|s[i%l]}*''}['case', 2.5]
 => "casecaseca" 
answered Feb 8, 2016 at 16:21
\$\endgroup\$
3
\$\begingroup\$

Perl 6, (削除) 46 41 (削除ここまで) 39 bytes

{([~] $^a xx$^b)~$a.substr(0,$a.chars*($b%1))} # 46 bytes
{substr ([~] $^a xx$^b+1),0,$a.chars*$^b} # 41 bytes
{substr ([~] $^a xx$^b+1),0,$a.comb*$b} # 39 bytes

Perl 6 has both a string repetition operator x and a list repetition operator xx.

Since the rules disallow string repetition, we repeat it as if it was a single element list instead. Then the list gets concatenated together, and a substring of it is returned.

Usage:

# give it a lexical name
my &code = {substr ([~] $^a xx$^b+1),0,$a.chars*$^b}
# {substr ($^a x$^b+1),0,$a.chars*$^b}
say code('test case', 1).perl; # "test case"
say code('case', 2.5).perl; # "casecaseca"
say code('(will add more later)', 0.3333).perl; # "(will "
say code('cats >= dogs', 0.5).perl; # "cats >"
answered Feb 8, 2016 at 20:18
\$\endgroup\$
1
  • \$\begingroup\$ substr ([~] $^a xx$^b+1),0,$a.comb*$b} saves two chars \$\endgroup\$ Commented Feb 10, 2016 at 4:31
2
\$\begingroup\$

osascript, 173 bytes

Oh my days, this is worse than I thought.

on run a
set x to a's item 1's characters
set y to a's item 2
set o to""
set i to 1
set z to x's items's number
repeat y*z
set o to o&x's item i
set i to i mod z+1
end
o
end

Returns the value of the string, another answer using cyclical indexing. Expects input as "string" "repetitions".

answered Feb 8, 2016 at 16:26
\$\endgroup\$
3
  • \$\begingroup\$ Oh my days, this is worse than I thought. So true, so true. \$\endgroup\$ Commented Feb 8, 2016 at 16:28
  • \$\begingroup\$ Is there a multiple var set at once command? ie set x,y to a's items? \$\endgroup\$ Commented Feb 8, 2016 at 16:29
  • \$\begingroup\$ @RikerW I don't think so. If there is, I'm seriously missing out. \$\endgroup\$ Commented Feb 8, 2016 at 16:34
2
\$\begingroup\$

Haskell, 44 bytes

c x=x++c x
s#n=take(floor$n*sum[1|a<-s])$c s

Usage example: "(will add more later)" # 0.3333 -> "(will ".

How it works: c concatenates infinite copies of the string x. It behaves like the built-in cycle. sum[1|a<-s] is a custom length function that works with Haskell's strict type system as it returns a Double (the built-in length returns an Int which cannot be multiplied with n). # takes floor (n * length(s)) characters from the cycled string s.

answered Feb 8, 2016 at 16:59
\$\endgroup\$
2
\$\begingroup\$

PHP 5, (削除) 96 (削除ここまで) 87

9 bytes saved thanks to @manatwork

<?for($i=$z=0;$i++<floor(strlen($a=$argv[1])*$argv[2]);$z++)echo$a[$z]?:$a[$z=0‌​];

Pretty straight forward looping answer.

Ungolfed

<?
$a=$argv[1];
$z=0;
for($i=0; $i < floor(strlen($a)*$argv[2]); $i++) {
 // if the string offset is not set
 // then reset $z back to 0 so we can
 // echo the beginning of ths string again
 @$a[$z] ?: $z=0;
 echo $a[$z];
 $z++;
}
answered Feb 8, 2016 at 17:16
\$\endgroup\$
4
  • \$\begingroup\$ Not sure when should that error suppression help, for me seems to work without @ too: <?for($i=$z=0;$i++<floor(strlen($a=$argv[1])*$argv[2]);$z++)echo$a[$z]?:$a[$z=0]; \$\endgroup\$ Commented Feb 8, 2016 at 17:26
  • \$\begingroup\$ I was getting a notice on case #2 which caused the output to render incorrectly, which is when I added in the suppression. (running in CLI mode) \$\endgroup\$ Commented Feb 8, 2016 at 17:30
  • \$\begingroup\$ "PHP 5.3 or later, the default value is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED." – error_reporting So we prefer to base our solutions on default configuration and not to care about notices and other good habits. For example ignoring the initialization of $z and $i. \$\endgroup\$ Commented Feb 8, 2016 at 17:37
  • \$\begingroup\$ Oh, cool. Thanks for the info! \$\endgroup\$ Commented Feb 8, 2016 at 18:05
2
\$\begingroup\$

R, 59 bytes

function(s,l)cat(rawToChar(array(charToRaw(s),nchar(s)*l)))

As an unnamed function. This uses charToRaw to split the string into a vector of raws. This is filled into an array of length * l, converted back to char and output.
I was going to use strsplit, but it ended up being longer.

Test

> f=
+ function(s,l)cat(rawToChar(array(charToRaw(s),nchar(s)*l)))
> f('test case', 1) # -> test case
test case
> f('case', 2.5) # -> casecaseca
casecaseca
> f('(will add more later)', 0.3333) # -> (will(space)
(will 
> f('cats >= dogs', 0.5) # -> cats >
cats >
> 
answered Feb 8, 2016 at 18:24
\$\endgroup\$
2
\$\begingroup\$

Perl, 51 + 3 = 54 bytes

$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]

Requires: -n, -l and -M5.010 | -E:

 $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'test case\n1'
 test case
 $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'case\n2.5'
 casecaseca
 $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'(will add more later)\n0.3333'
 (will 
 $ perl -nlE'$l=<>*y///c;for$i(1..$l){push@a,/./g}say@a[0..$l-1]' <<< $'cats >= dogs\n0.5'
 cats >

Explanation:

$l=<>*y///c; # Calculate output length (eg. 2.5 * input length)
for$i(1..$l){push@a,/./g} # Push a lot of chars from input into @a
say@a[0..$l-1] # Slice @a according to output length
answered Feb 8, 2016 at 18:23
\$\endgroup\$
1
\$\begingroup\$

c (preprocessor macro), 71

j,l;
#define f(s,m) l=strlen(s);for(j=0;j<(int)(l*m);)putchar(s[j++%l])

Not much tricky here. Just need to make sure l*m is cast to an int before comparing to j.

Try it online.

answered Feb 8, 2016 at 19:23
\$\endgroup\$
1
\$\begingroup\$

Oracle SQL 11.2, (削除) 154 (削除ここまで) 152 bytes

WITH v(s,i)AS(SELECT SUBSTR(:1,1,FLOOR(FLOOR((:2-FLOOR(:2))*LENGTH(:1)))),1 FROM DUAL UNION ALL SELECT :1||s,i+1 FROM v WHERE i<=:2)SELECT MAX(s)FROM v;

Un-golfed

WITH v(s,i) AS
(
 SELECT SUBSTR(:1,1,FLOOR(FLOOR((:2-FLOOR(:2))*LENGTH(:1)))),1 FROM DUAL 
 UNION ALL 
 SELECT :1||s,i+1 FROM v WHERE i<=:2
)
SELECT MAX(s) FROM v;

I went the recursive way, with the initialisation select taking care of the decimal part.

Saved 2 bytes thanks to @MickyT

answered Feb 8, 2016 at 19:33
\$\endgroup\$
3
  • \$\begingroup\$ You can save a couple by removing spaces after the ) in the WITH clause and the final select. \$\endgroup\$ Commented Feb 8, 2016 at 19:44
  • \$\begingroup\$ Another saving would be to replace FLOOR(FLOOR((:2-FLOOR(:2))*LENGTH(:1))) with MOD(:2,1)*LENGTH(:1) \$\endgroup\$ Commented Feb 8, 2016 at 20:56
  • \$\begingroup\$ And one last one :), you can use LPAD rather than SUBSTR \$\endgroup\$ Commented Feb 8, 2016 at 21:07
1
\$\begingroup\$

Seriously, 24 bytes

,╗,mi@≈╜n╜l(*≈r`╜E`MΣ)kΣ

Try it online!

Explanation:

,╗,mi@≈╜n╜l(*≈r`╜E`MΣ)kΣ
,╗ get first input (string) and push it to register 0
 ,mi@≈ get input 2 (x), push frac(x) (f), int(x) (n)
 ╜n push n copies of the string
 ╜l(*≈ push length of string, multiply by f, floor (substring length) (z)
 r`╜E`MΣ push s[:z]
 )kΣ move fractional part of string to bottom, concat entire stack
answered Feb 8, 2016 at 21:31
\$\endgroup\$
1
\$\begingroup\$

Pyth, 9 bytes

V*Elzp@zN

Basically just doing

 z = input()
V*Elz for N in range(evaluatedInput()*len(z)): # flooring is automatic
 p@zN print(z[N], end="") # modular indexing
answered Feb 8, 2016 at 23:10
\$\endgroup\$
1
\$\begingroup\$

Nim, 75 bytes

func r[S,F](s:S,n:F):S=
 for i in 0..<int n*s.len.float:result&=s[i%%s.len]

Attempt This Online!

answered Sep 10, 2023 at 10:58
\$\endgroup\$
0
\$\begingroup\$

Pascal, 138 B

This full program requires a processor compliant with ISO standard 10206 "Extended Pascal". Trivial cases have been excluded: It is presumed that the input string s is non-empty and n is positive. NB: The golfed version caps s at a reasonable length of 999.

program p(input,output);var s:string(999);n:real;begin
read(s,n);while n>1 do begin n:=n-1;write(s)end;write(s[1..trunc(length(s)*n)])end.

Ungolfed:

program decimalMultiplicationOfStrings(input, output);
 var
 { `string` is a schema data type defined by Extended Pascal.
 The `string(maxInt)` discriminates the schema data type.
 Henceforth the specific `string` has a capacity of `maxInt`. }
 s: string(maxInt);
 n: real;
 begin
 { You can specify `real` as well as `integer` literals for `n`.
 An `integer` value is automatically promoted to `real`. }
 read(s, n);
 { The `string` subrange notation used below in the last line
 may not specify an empty range (e. g. `1..0` is illegal).
 Therefore the `while` loop’s condition is `n > 1`.
 If `n = 1`, the one copy is printed via the final line. }
 while n > 1 do
 begin
 n ≔ n − 1;
 write(s);
 end;
 { The subrange notation is defined by Extended Pascal.
 It cannot be used for strings that are `bindable`. }
 write(s[1..trunc(length(s) * n)]);
 end.

Input is end-of-line separated. s can otherwise contain any character from chr(0) to (the implementation-defined) maxChar range.

answered Sep 10, 2023 at 10:00
\$\endgroup\$
0
\$\begingroup\$

Scala, 68 bytes

Golfed version. Try it online!

(s,n)=>{val l=s.length;(0 to (n*l).toInt-1).map(i=>s(i%l)).mkString}

Ungolfed version. Try it online!

object Main {
 def repeatString(s: String, n: Double): String = {
 val len = s.length
 val repeatLen = (n * len).toInt
 (0 until repeatLen).map(i => s(i % len)).mkString
 }
 def main(args: Array[String]): Unit = {
 println(repeatString("case", 2.5))
 }
}
answered Sep 13, 2023 at 7:24
\$\endgroup\$
0
\$\begingroup\$

SAKO, 211 bytes

PODPROGRAM:F(X,*W)
CALKOWITE:*W,I,J
STRUKTURA(9):W
J=-1
2)J=J+1
GDYW(J)=58:1,INACZEJ2
1)GDYENT(X)=0:3,INACZEJ4
*4)DRUKUJWIERSZ:W
POWTORZ:I=1(1)ENT(X)
*3)W(I)=0
POWTORZ:I=ENT((X-ENT(X))×ばつJ)(1)9
DRUKUJWIERSZ:W
WROC

Explanation:

  1. We get our S (here W) and N (here X)
  2. We count how many characters there are in X and store it in J.
  3. We check if \$\lfloor X \rfloor\$ is zero and if yes skip the next loop.
  4. We loop for \$\lfloor X \rfloor\$ times and print the string.
  5. We check how many is \$\lfloor (X - \lfloor X \rfloor) \cdot |,円J,円|)\rfloor\$.
  6. We replace all characters after that with zeroes.
  7. We print our shortened string.

Note: This will work only in KW6 encoding system, for other adjust the value in the first if statement. We also guess that the string is 9 characters long + string ending for lessening the bytes. It can be increased indefinitely according to specific needs.

Full programme version, 227 bytes

CALKOWITE:*W,I,J
BLOK(9):W
W(=I)=0
CZYTAJ:X
CZYTAJWIERSZ:W
J=-1
2)J=J+1
GDYW(J)=58:1,INACZEJ2
1)GDYENT(X)=0:3,INACZEJ4
*4)DRUKUJWIERSZ:W
POWTORZ:I=1(1)ENT(X)
*3)W(I)=0
POWTORZ:I=ENT((X-ENT(X))×ばつJ)(1)9
DRUKUJWIERSZ:W
STOP1
KONIEC
answered Mar 25 at 16:37
\$\endgroup\$
0
\$\begingroup\$

Perl 5 -lF, 43 + 2 = 45 bytes

$b=@F*<>;@F=(@F,@F)for 0..$b;say@F[0..$b-1]

Try it online!

answered Mar 25 at 18:22
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.