字符串的十进制乘法


14

给定2个输入(一个字符串和一个十进制数字),输出字符串乘以该数字。

问题是数字可以是浮点数或整数。

您应该先输出字符串floor(n)时间,然后再输出前floor((n-floor(n))*len(string))几个字母。

其他说明:

  • 输入并不总是浮点数,可能是整数。因此1.5、1和1.0都是可能的。不过,它将始终以10为底,如果您希望例外,请发表评论。
  • 输入的字符串可能包含空格,引号和其他字符。没有换行符或控制字符。
  • 没有内置的直接字符串重复功能,甚至'a'*5不允许像python这样的字符串乘法。但是,允许添加字符串。

测试用例:

逗号和空格分隔输入。

test case, 1 -> test case

case, 2.5 -> casecaseca

(will add more later), 0.3333 -> (will(space)

cats >= dogs, 0.5 -> cats >

最后说明:

我看到许多使用内置字符串乘法或重复功能的答案。这不是允许的。@VTC的答案有效的,因为它不会乘以字符串,而只是乘以浮点输入。因此,最终的规则是:如果直接将字符串相乘,则无法执行。


措词被反复修改(我没有看到第一个修订版)。我建议删除direct重复的字符串(这是什么意思?)。但总而言之,您是对的
edc65 '16


@ Sp3000是的,我知道。我认为差异足够大。
Rɪᴋᴇʀ

“不允许直接字符串重复使用内置函数,甚至不允许使用字符串相乘,例如python'a'* 5。” 您无需解释它们之间的区别。他们对我来说听起来一样。
msh210 '16

@ edc65在Perl中,您可以执行列表重复,然后连接该列表的元素,这不是直接的字符串重复。在Perl 5:join "", ("case") x 2VS "case" x 2,在Perl 6 [~] "case" xx 2VS相同的"case" x 2
吉尔伯特b2gills

Answers:


4

果冻,5个字节

×L}Rị

不使用内置的重复。 在线尝试!

怎么运行的

×L}Rị  Main link. Left input: n (multiplier). Right input: S (string)

 L}    Yield the length of S.
×      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.

7

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]);}

接受char []和float并输出到STDOUT。基本循环。


3
良好的打高尔夫,甚至对于Java也是如此。:P
Rɪᴋᴇʀ

这也是我其他答案的建议,但我不认为我会这样做。在我看来,这并不正确。
Marky Markov

嗯,很公平。在这里可以识别,但是可以。:D
Addison Crump

我建议将您的语言声明为Java7。然后没人会告诉您使用lambda。
feersum

6

Pyth, 9 8

s@Lz*lzQ

感谢Pietu1998,节省了1个字节

floor(n * len(string))使用循环索引从字符串中获取字母。我相信这总是等于给定的公式。

测试套件


1
不,请不要马上从我这里拿走这个。xD
Addison Crump

@VoteToClose实际上我根本没有读过您的答案,侦察员荣誉:PI甚至都没有意识到不允许重复字符串,这比我想出的方式短了……
FryAmTheEggman

1
您甚至不需要第二个srange这样很有趣。
PurkkaKoodari'2

1
不!哭在角落里啊,哦,好。
Addison Crump

6

JavaScript(ES6),50个字节

多编辑 2个字节以包括功能的定义f。使用@manatwork的尖端少1个字节。注意:使用~我们有很多不必要的迭代,但这是代码高尔夫,甚至1字节计数

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

测试

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>


好的谢谢。到目前为止,大多数答案都没有问题,而且很容易解决。感谢您纠正它。
Rɪᴋᴇʀ

微小的错字:n>0在代码中与n>1在测试用例中。
manatwork '16

@manatwork谢谢。无论哪种方式都可以工作
edc65 '16

哦。确实。但是,为什么不只是~n呢?(真的只是一个问题。只尝试了给定的测试用例。)
manatwork

3
@ edc65 f您的解决方案在哪里定义?你不是想念f=吗?
andlrc

4

Vitsy,9个字节

期望单词作为参数,并且数字乘以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.

在线尝试!


忠实于您的话,您回答很快
Rɪᴋᴇʀ

@RikerW Martin退出了我的行列。
艾迪生·克伦普

为什么Grab all string argument input.然后Parse STDIN.又来?
Rɪᴋᴇʀ

@RikerW是双精度型的参数会被自动解析,并立即将其推入堆栈。处理占用的字节数超过其价值。
艾迪生·克伦普

哦好的。现在这更有意义。
Rɪᴋᴇʀ

3

CJam,10个字节

l_,l~*,\f=

字符串在STDIN的第一行提供,第二行提供浮点数。

在这里测试。

说明

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.

3

Python 2,71个字节

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

在这里尝试!

创建一个未命名的lambda,它将字符串作为第一个参数,将float作为第二个参数。返回重复的字符串。

如果允许字符串重复内置,则可能为46 :(


1
很难过 这样的字符串乘法规则。+1 A +代表蓬勃发展。
Addison Crump

3

Ruby,49个48个字符

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

样品运行:

2.1.5 :001 > ->s,n{(0...(n*l=s.size).to_i).map{|i|s[i%l]}*''}['case', 2.5]
 => "casecaseca" 

3

Perl 6的 46 41   39个字节

{([~] $^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具有字符串重复操作符x和列表重复操作符xx

由于规则不允许字符串重复,因此我们将其重复,就好像它是单个元素列表一样。然后,列表被串联在一起,并返回其子字符串。

用法:

# 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 >"

substr ([~] $^a xx$^b+1),0,$a.comb*$b}保存两个字符
raiph

2

osascript,173个字节

噢,我的日子比我想的还要糟。

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

返回字符串的值,这是使用循环索引的另一个答案。预期输入为"string" "repetitions"


Oh my days, this is worse than I thought.如此真实,如此真实。
Rɪᴋᴇʀ

一次设置多个var命令吗?即set x,y to a's items
Rɪᴋᴇʀ

@RikerW I don't think so. If there is, I'm seriously missing out.
Addison Crump

2

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.


2

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++;
}

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];
manatwork

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)
Samsquanch

“ PHP 5.3或更高版本,默认值为E_ALL&〜E_NOTICE&〜E_STRICT&〜E_DEPRECATED。” – error_reporting因此,我们更喜欢将解决方案基于默认配置,而不关心通知和其他良好习惯。例如忽视的初始化$z$i
manatwork '16

哦,酷。谢谢(你的)信息!
Samsquanch '16

2

R,59个字节

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

作为未命名的函数。这使用charToRaw将字符串拆分为raws向量。将其填充到一个长度为* l的数组中,然后转换回char并输出。
我本打算使用strsplit,但最终会更长。

测试

> 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 >
> 

2

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

1

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.


1

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


You can save a couple by removing spaces after the ) in the WITH clause and the final select.
MickyT

Another saving would be to replace FLOOR(FLOOR((:2-FLOOR(:2))*LENGTH(:1))) with MOD(:2,1)*LENGTH(:1)
MickyT

And one last one :), you can use LPAD rather than SUBSTR
MickyT

1

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

1

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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.