Десяткове множення рядків


14

Дано 2 входи, рядок і десятковий номер, виведіть рядок, помножений на це число.

Зрозуміло, що число може бути поплавком або цілим числом.

Ви повинні вивести строковий floor(n)час, а потім перші floor((n-floor(n))*len(string))літери знову.

Інші примітки:

  • Вхід не завжди буде поплавком, це може бути int. Отже, 1,5, 1 і 1,0 можливі. Це завжди буде в базі 10, але якщо ви хочете виключення, будь ласка, прокоментуйте.
  • Введення рядка може містити пробіли, лапки та інші символи. Немає нових ліній або контрольних символів, однак.
  • Не 'a'*5допускаються ніякі вбудовані модулі для прямого повторення рядків, навіть множення рядків на зразок пітона . Однак додавання рядків дозволено.

Тестові приклади:

Кома та пробіл розділяють входи.

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


@ Sp3000 так, я знаю. Я думаю, що різниця досить значна.
Rɪᴋᴇʀ

"Немає вбудованих модулів для прямого повторення рядків, навіть множення рядків, як python 'a' * 5, не допускається." Ви не пояснюєте різницю між ними. Вони мені звучать однаково.
msh210

@ edc65 У Perl ви можете зробити повторення списку, а потім об'єднати елементи цього списку, що не є прямим повторенням рядків. У Perl 5: join "", ("case") x 2vs "case" x 2, в Perl 6 [~] "case" xx 2проти того ж"case" x 2
Бред Гілберт b2gills

Відповіді:


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

Ява 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 [] і плаває і виводить в STDOUT. основні петлі.


3
Хороший гольф навіть для Java. : P
Rɪᴋᴇʀ

це було запропоновано і на моїй іншій відповіді, але я не думаю, що я це зроблю. мені це не здається правильним.
Маркі Марков

Е, досить справедливо. Тут визнано, але добре. : D
Аддісон Кримп

Я рекомендую оголосити вашу мову Java 7. Тоді ніхто не може сказати вам використовувати лямбда.
feersum

6

Pyth, 9 8

s@Lz*lzQ

Збережено 1 байт завдяки Pietu1998

Для цього потрібні floor(n * len(string))літери з рядка, використовуючи циклічну індексацію. Я вважаю, що це завжди рівнозначно даній формулі.

Тестовий сюїт


1
Ніхто не пізніше цього не візьме у мене. xD
Addison Crump

@VoteToClose Я насправді взагалі не прочитав вашої відповіді, честь розвідників: PI навіть не зрозумів, що повторення рядків заборонені, це було лише коротше, що я придумав таким чином ...
FryAmTheEggman

1
Вам навіть не потрібна друга s. rangeсмішно так.
PurkkaKoodari

1
НЕ! кричить у кутку Ах, ой добре.
Аддісон Кримп

6

JavaScript (ES6), 50 байт

Відредагуйте ще 2 байти, щоб включити визначення функції f. На 1 байт менше, використовуючи підказку @manatwork. Примітка: за допомогою у ~нас більше ітерацій, ніж потрібно, але це код гольфу і навіть 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 спасибі Це повинно працювати в будь-якому випадку
edc65

Ой. Справді. Але тоді чому не просто ~n? (Дійсно, лише питання. Пробував лише наведені тестові випадки.)
маніпуляція

3
@ edc65 Де fвизначено у вашому рішенні? Ви не пропали f=?
andlrc

4

Віци, 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 out FGITW'd мене.
Аддісон Кримп

Чому ти 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)))]

Спробуйте тут!

Створюється неназвана лямбда, яка приймає рядок як перший аргумент, а поплавок - як другий. Повертає повторний рядок.

Це може бути 46, якщо дозволено вбудовані рядкові повтори :(


1
Дуже сумно. Такі правила множення рядків +1 A + для ефурту.
Аддісон Кримп

3

Рубі, 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 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 >"

substr ([~] $^a xx$^b+1),0,$a.comb*$b} saves two chars
raiph

2

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


Oh my days, this is worse than I thought. So true, so true.
Rɪᴋᴇʀ

Is there a multiple var set at once command? ie 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 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.
manatwork

Oh, cool. Thanks for the info!
Samsquanch

2

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

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
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.