又是万圣节!


10

问题描述

我们都喜欢Twix(因为它是最好的糖果),但这是孩子们的第一个万圣节---我们必须为他们抓住每种糖果中的至少一种。每个万圣节,Numberline大街上的所有居民都会发送一封电子邮件,说明他们今年将赠送的糖果类型。

哦! 我们生活在一维世界中。

在某些方面(而不是其他方面)非常懒惰,我们绘制了房屋的地图,并给出了他们在街上的位置。我们还注意到了他们所拥有的糖果类型。这是我们今年制作的地图:

 [(-2, {"Kisses", "KitKats"}),
 (1, {"KitKats", "Peanut Butter Cups"}),
 (6, {"Kisses", "Twix"}),
 (9, {"Skittles"}),
 (10, {"Twix"})]

为了孩子们的小腿,我们需要找到从附近任何房子开始的最短步行路程,以至少收集每种糖果中的一种。

例子

在几个用户(包括Shaggy)的请求下,我将介绍一些可行的示例。希望这可以清除一切。:) 输入:

 [(-2, {"Kisses", "KitKats"}),
 (1, {"KitKats", "Peanut Butter Cups"}),
 (6, {"Kisses", "Twix"}),
 (9, {"Skittles"}),
 (10, {"Twix"})]

输出:

[1, 2, 3]

另一个地图和解决方案...

输入:

[(-3, {"KitKats", "Twix"}),
(-1, {"Hundred Grands"}),
(3, {"Kisses"}),
(12, {"Hundred Grands", "Twix", "KitKats"})]

输出

[0, 1, 2]

我们可以从坐标9的房屋收集糖果开始,到坐标6和1的房屋。这可以通过步行8个单位来填补糖果配额,但这是最短的解决方案吗?

规则

条目必须在示例中采用结构相似的单个参数,并以最短的解决方案输出要访问的房屋的索引。

高尔夫球规则适用典型代码:以字节为单位的最短正确解决方案将获胜!

PS:这是世界上最大的科技公司之一给我的面试问题。如果您不喜欢高尔夫,请尝试找到O(k * n)时间解,其中k是糖果类型的数量,n是房屋数量。

编辑

正如乔纳森·艾伦(Jonathon Allan)所指出的,在这种情况下,“指示”的含义存在一些混淆。我们要输出自变量列表中的房屋位置而不是车道上的坐标。


6
这需要一个可行的示例和一些测试用例。
毛茸茸的

2
我们可以接受两个论点吗?门牌号码列表和相应的糖果类型列表?
亚当

1
@KevinCruijssen既不:输出房屋的指数,在最短的解决方案访问
亚当

2
我假设“索引”和“位置”是同义词(即Numberline Avenue上的地址就是我们应该返回的地址),这是错误的吗?
乔纳森·艾伦,

1
@KevinCruijssen很好的问题!保证数字在输入中是有序的。而且我会假设字符串不包含数字,因为我所知道的所有带有数字的糖果都将其拼写出来(百大和三剑客)。:)
Qfwfq

Answers:


3

果冻,16 字节

ŒPṪ€ẎQLƲÐṀẎISƊÞḢ

Monadic Link接受列表中描述的输入,该列表按编号从最低到最高的Numberline Avenue房屋排序(如果我们需要接受任何订购,我们可以在前面加上),这会产生从最低编号的房屋开始并沿着Avenue行驶的最短路径。

在线尝试!

如果我们想找到所有这些最短路径替换尾随字节ÞḢ,用ÐṂ; 这也是16个字节。

怎么样?

ŒPṪ€ẎQLƲÐṀẎISƊÞḢ - Link: list of [index, candies]
ŒP               - power-set
        ÐṀ       - keep those for which this is maximal:
       Ʋ         -   last four links as a monad:
  Ṫ€             -     tail €ach -- this removes the candies lists from the current list
                 -                  and yields them for use now
    Ẏ            -     tighten (to a flat list of candies offered by these hoses)
     Q           -     de-duplicate (get the distinct candies offered)
      L          -     length (how many distinct candies are on offer)
              Þ  - sort (now just the indexes of remaining sets due to Ṫ) by:
             Ɗ   -   last three links as a monad:
          Ẏ      -     tighten (to a flat list of indexes since Ṫ leaves a list behind)
           I     -     incremental differences (distances between houses)
            S    -     sum
               Ḣ - head (get the first)

1
真好 为了您的解释,我认为您的意思是第二快速。
尼克·肯尼迪

是的,我做到了。
乔纳森·艾伦,

3

Python 2中133个 130 127字节

def f(l):r=range(len(l));v,c=zip(*l);print min((v[j]-v[i],r[i:j+1])for i in r for j in r if s(*c)==s(*c[i:j+1]))[1]
s={0}.union

在线尝试!


2

05AB1E,22 字节

æʒ€θ˜I€θ˜åP}€€нD€¥OWQÏ

假设输入列表中的数字从低到高排序。
如果找到多个解决方案,它将全部输出。

在线尝试。

说明:

æ            # Get the powerset (all possible combinations) of the (implicit) input-list
 ʒ           # Filter this list of combinations by:
  €θ         #  Get the last items of each (the list of strings)
    ˜        #  Flatten the list
  I          #  Get the input-list again
   €θ˜       #  Get the last items of each (the list of strings) flattened as well
      å      #  Check for each if it is in the list of strings of this combination
       P     #  Check if all are present
 }           # Close the filter (we now have all combinations, containing all unique strings)
  €€н        # Only leave the first items of each item in the combination (the integers)
     D       # Duplicate this list
      €¥     # Get the deltas (forward differences) of each
        O    # Sum these deltas
         W   # Get the lowest sum (without popping the list)
          Q  # Check for each if it's equal to this minimum
           Ï # And only leave the list of integers at the truthy indices
             # (which are output implicitly as result)


0

Haskell中343个 372字节

多亏了@ ASCII-only的改进,他在评论中还提出了一个271字节的变体 :)

import Data.List
import Data.Function
f s=subsequences(map(\a@(x,y)->(x,y,[(a`elemIndices`s)!!0]))s)
g f s=if f*s<=0 then f+abs f+abs s else f+abs(f-s)
h=foldl(\(a,b,c)(d,e,f)->(g a d,nub(b++e),c++f))(0,[],[])
i s=map h(filter(not.null)s)
l m=filter(\(_,x,_)->length x==(maximum$map(\(_,x,_)->length x)m))m
m=minimumBy(compare`on`(\(p,_,_)->p))
n s=(\(_,_,l)->l)$m$l$i$f s

在线尝试!


不打高尔夫球

import Data.List
import Data.Function

allPaths :: [(Integer, [String])] -> [[(Integer, [String], [Int])]]
allPaths xs = subsequences(map (\a@(x,y) -> (x,y,[(a`elemIndices`s) !! 0])) s)

pathLength :: Integer -> Integer -> Integer
pathLength f s = if f*s <= 0 then f + abs f + abs s else f + abs(f - s)

traversePath :: [(Integer, [String], [Int])] -> (Integer, [String], [Int])
traversePath = foldl (\(n1, a1, c1) (n2, a2, c2) -> (pathLength n1 n2, nub (a1 ++ a2), c1 ++ c2)) (0, [], [])

allTraversedPaths :: [[(Integer, [String], [Int])]] -> [(Integer, [String], [Int])]
allTraversedPaths xs = map traversePath (filter (not . null) xs)

getCompletePaths :: [(Integer, [String], [Int])] -> [(Integer, [String], [Int])]
getCompletePaths m = filter (\(_,x,_) -> length x == ( maximum $ map (\(_,x,_) -> length x) m)) m

getFastestPath :: [(Integer, [String], [Int])] -> (Integer, [String], [Int])
getFastestPath = minimumBy (compare `on` (\(p, _, _) -> p))

getPath :: [(Integer, [String])] -> (Integer, [String], [Int])
getPath xs = (\(_,_,l) -> l) getFastestPath $ getCompletePaths $ allTraversedPaths $ allPaths xs

第一次尝试


您应该只返回该元组的第三个元素,并且在导入后会有多余的换行符
ASCII码,仅适用

315?(尽管仍然必须仅返回第三个元素)
ASCII码,仅ASCII


所以是的,您不能对长度进行硬编码
ASCII码,仅ASCII


0

O(k * n)时间解,具有O(k * n)空间

xii0i<nxicii

i1j1i0<i1i0j0i0j0

因此,我们的算法是:

// A[k] is the number of each candy we get from the first k houses
A := array of n bags
A[0] := {}
for k := 0 to n - 1
  A[k] := A[k - 1] + c[k - 1]
end
best_distance := ∞
best_i := -1
best_j := -1
// Find the range [i, j] such that we get all candy types
j := n
for i := n - 1 to 0
  while j > i and (A[j - 1] - A[i]) has all candy types
    j := j - 1
  end
  if (A[j] - A[i]) does not have all candy types then continue end
  distance = x[j - 1] - x[i]
  if distance < best_distance then
    best_distance = distance
    best_i = i
    best_j = j
  end
end
return best_i ..^ best_j

AO(k)O(nk)nnnO(n)O(nk)O(k)O(nk)

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.