Вам надається рядок, щоб зробити і, починаючи з порожнього рядка, зробити його, використовуючи вартість додавання та клонування


17

Ваше завдання - створити заданий цільовий рядок. Починаючи з порожнього рядка, вам доведеться додати символи до нього, поки ваша рядок не буде такою, як ми хочемо. Ви можете додати символ до кінця рядка вартістю x, або можете клонувати рядок вартістю y. Те, що ми хочемо, це найдешевший спосіб зробити це.

Випробування

targetString , appendcost, clonecost -> totalcost

"bb", 1, 2 -> 2
"bbbb", 2, 3 -> 7
"xzxpcxzxpy", 10, 11 -> 71
"abababab", 3, 5 -> 16
"abababab", 3, 11 -> 23

1
Як визначаються витрати? Чи є натуральними цілими числами?
Арнольд

1
Я думаю, що ви просто хочете зробити кодовий гольф (найкоротший код) викликом, тому я зняв виклик коду та програмування головоломки, які вказують на якийсь альтернативний спосіб підрахунку.
xnor

7
Я думаю, що це допомогло б мати більше тестових випадків, оскільки, мабуть, хтось міг би написати програму з хорошою евристикою, яка працює для всіх тестових випадків, але в цілому не є оптимальною. Зокрема, жоден із тестових випадків не має декількох клонів або клонів підрядків, які не є на початку. Я думаю, також було б добре мати приклад, коли зміна лише витрат змінює вихід.
xnor

6
Приємний перший виклик, до речі!
Ерік Аутгольфер

Чи клонування однієї літери все ще вважається операцією з клонуванням?
digEmAll

Відповіді:


2

Лушпиння , 25 байт

φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0

Спробуйте в Інтернеті!

Вхідні дані складаються з порядку додавання вартості, вартості клонування, цілі.

Пояснення

φ?ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ0  Two explicit inputs and one implicit.
                           Example: 2, 3, s="abab"
φ                          Make a recursive function and call it on s:
 ?                      0   If s is empty, return 0.
  ö▼z+:⁴∞²m⁰§:h§δf`€otṫḣ    Otherwise do this.
                       ḣ    Prefixes: ["a","ab","aba","abab"]
                    otṫ     Suffixes except the first one: ["bab","ab","b"]
               §δf`€        Keep those prefixes that have the corresponding suffix as substring: ["ab","aba"]
            §:h             Prepend s minus last character: ["aba","ab","aba"]
          m⁰                Recurse on each: x=[6,4,6]
        ∞²                  Repeat the clone cost: [3,3,3,..
      :⁴                    Prepend append cost: [2,3,3,3,..
    z+                      Add component-wise to x: [8,7,9]
   ▼                        Minimum: 7


1

JavaScript (ES6), 123 111 байт

Вводиться як " (x)(y)(s).

x=>y=>m=g=([s,...r],o='',c=0)=>s?[...r,g(r,o+s,c+x)].map(_=>s+=r.shift(~o.search(s)&&g(r,o+s,c+y)))|m:m=m<c?m:c

Спробуйте в Інтернеті!

Прокоментував

x => y =>                    // x = 'append' cost; y = 'clone' cost
m =                          // m = minimum cost, initialized to a non-numeric value
                             //     this is what will eventually be returned
g = (                        // g = recursive function taking:
  [s,                        //   - the input string split into s = next character
      ...r],                 //     and r[] = array of remaining characters
  o = '',                    //   - o = output string
  c = 0                      //   - c = current cost
) =>                         //
  s ?                        // if s is defined:
    [ ...r,                  //   split a copy of r
      g(r, o + s, c + x)     //   do a recursive call with an 'append' operation
    ].map(_ =>               //   iterate as many times as there are remaining characters
                             //   in r[], + 1
      s +=                   //     append to s
        r.shift(             //     the next character picked from the beginning of r[]
          ~o.search(s) &&    //     if s is found in o,
          g(r, o + s, c + y) //     do a recursive call with a 'clone' operation
        )                    //     (note that both s and r are updated *after* the call)
    ) | m                    //   end of map(); return m
  :                          // else:
    m = m < c ? m : c        //   update m to min(m, c)

1

R , 192 185 байт

f=function(s,a,c,k=0,x="",R=substring,N=nchar,p=R(s,1,1:N(s)))'if'(!N(s),k,{y={};for(i in c(R(s,1,1),p[mapply(grepl,p,x)]))y=min(y,f(R(s,N(i)+1),a,c,k+'if'(any(y),c,a),paste0(x,i)));y})

Спробуйте в Інтернеті!

Нерозкручений код та пояснення:

# s is the current remaining string (at the beginning is equal to the target string)
# a is the append cost
# c is the clone cost
# k is the current cost (at the beginning is zero)
# x is the partially constructed string (at the beginning is empty)
f=function(s,a,c,k=0,x=""){
  # store in p all the possible prefixes of s
  p = substring(s,1,1:nchar(s))
  # if s is empty return the current cost k
  if(!nchar(s))
    k
  else{
    y={}
    # prepend the first letter of s (=append operation) to  
    # the prefixes in p that are contained in x (=clone operations)
    for(i in c(substring(s,1,1),p[mapply(grepl,p,x)])){
      # perform first the append then the clone operations and recurse, 
      # storing the cost in y if lower than previous
      # (if y is NULL is an append operation otherwise is a clone, we use the right costs)
      y = min(y,f(substring(s,nchar(i)+1),a,c,k+'if'(any(y),c,a),paste0(x,i)))
    }
    # return the current cost
    y
  }
}
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.