最常见的倍数


28

不要与最小公倍数相混淆。

给定具有多个元素的正整数列表,则返回数组中两个元素的最常见乘积。

例如,列表的MCM [2,3,4,5,6]12,产品表为:

    2  3  4  5  6
  ---------------
2 | #  6  8  10 12
3 | #  #  12 15 18
4 | #  #  #  20 24
5 | #  #  #  #  30
6 | #  #  #  #  #

感谢DJMcMayhem的桌子

由于12出现的次数最多(两倍2*63*4)。请注意,我们不包括的元素,本身的产品,所以2*2还是4*4不不会出现在这个列表中。但是,相同的元素仍将相乘,因此该表[2,3,3]如下所示:

    2  3  3
  ----------
2 | #  6  6 
3 | #  #  9
3 | #  #  #

随着MCM的存在6

如果出现平局,则可以返回任何已绑定的元素,或所有它们的列表。

测试用例:

[2,3,4,5,6] -> 12
[7,2] -> 14
[2,3,3] -> 6
[3,3,3] -> 9
[1,1,1,1,2,2] -> 2
[6,200,10,120] -> 1200
[2,3,4,5,6,7,8,8] -> 24
[5,2,9,10,3,4,4,4,7] -> 20
[9,7,10,9,7,8,5,10,1] -> 63, 70, 90 or [63,70,90]


5
建议的测试用例:所有元素都相同的测试用例(即[3,3,3] -> 9)。使用您当前的所有测试用例,筛选出元素相同的任何对(即使对于[2,3,3]包含相同值的测试用例)仍将保持正确的测试结果,但对于该测试用例将失败,因为在过滤后将不再保留任何结果。
凯文·克鲁伊森

@Kevin好建议,补充
Jo King

Answers:


11

Brachylog,11个字节

{⊇Ċ×}ᶠọtᵒth

在线尝试!

说明

{   }ᶠ          Find all:
 ⊇Ċ×              Product of a subset of 2 elements
      ọtᵒ       Order by occurrences
         th     Take the last element and discard the number of occurrences

我不知道代码高尔夫通常如何工作,但是这些字符是否不在标准256个代码点之外,因此每个字符都为多个字节吗?
Holloway


11

R54 50 41字节

order(-tabulate(combn(scan(),2,prod)))[1]

在线尝试!

另外,对于54 53 44字节:

names(sort(-table(combn(scan(),2,prod))))[1]

在线尝试!

原则上,即使没有names功能,后一种版本也会输出相关结果,但随后会列出此类最常用产品的数量,因此不需要...

多亏了CrimealVulgar的-4和-1,以及Giuseppe的-9两者。


1
在第二个上,您可以使用-table()来代替-1的下降= TRUE。我真的很喜欢第一个的聪明。编辑:刚意识到您还可以将其应用于-4的第一个,所以就是这样。在线尝试!
刑事

1
combn(scan(),2,prod)而不是使用作品apply
朱塞佩


7

Pyth,12个字节

eo/QN=*M.cQ2

测试套件

首先,我们采用输入的所有2个元素组合,而不用替换(.cQ2)。然后,我们将这些对中的每对映射到其乘积(*M)。接下来,我们用产品列表(=)覆盖输入变量。接下来,我们按照产品列表(o/QN)中出现的次数对产品列表进行排序。最后,采用已排序列表(e)的最后一个元素。


7

MATL8 7字节

2XN!pXM

在线尝试!

(使用@Mr。Xcoder的Jelly答案中的方法来获得-1个字节。)

2XN     % nchoosek - get all combinations of 2 elements from input
!p      % get the product of each combination
XM      % 'mode': get the most common value from that

较旧的答案:

8字节

&*XRXzXM

在线尝试!

&*    % multiply input by its transpose,
      %  getting all elementwise products
XR    % take the upper-triangular portion of that,
      %  zeroing out repetitions and mainly self-multiplications
Xz    % remove the zeroed out parts
XM    % 'mode' calculation - get the most common value from that

6

05AB1E8 6 字节

æ2ùP.M

-2个字节,感谢@Kaldo

在线尝试验证所有测试用例

说明:

æ         # Take the powerset of the input-list
          #  i.e. [2,3,3] → [[],[2],[3],[3],[2,3],[2,3],[3,3],[2,3,3]]
 2ù       # Leave only the inner lists of size 2:
          #  i.e. [[],[2],[3],[3],[2,3],[2,3],[3,3],[2,3,3]] → [[2,3],[2,3],[3,3]]
   P      # Take the product of each remaining pair
          #  i.e. [[2,3],[2,3],[3,3]] → [6,6,9]
    .M    # Only leave the most frequent value(s) in the list
          #  i.e. [6,6,9] → [6]

1
æ2ùP.M6个字节
卡尔多

@Kaldo谢谢!完全忘记了ù
凯文·克鲁伊森

6

Mathematica,32个字节

-17个字节(和一个修复程序),感谢JungHwan Min

Commonest[1##&@@@#~Subsets~{2}]&

纯功能。将数字列表作为输入,并返回MCM列表作为输出。


实际上,我们俩都似乎错读了这个问题。输入失败{3, 3, 3}。固定:Commonest[1##&@@@#~Subsets~{2}]&
JungHwan Min

@JungHwanMin Huh。我认为Subsets没有将重复视为单独的元素。看来确实如此,所以谢谢!
LegionMammal978 '18

5

MATLAB,43个字节

I=input('');i=I'*I*1-eye(nnz(I));mode(i(:))

这也是一种绕口令!

说明

I=input('');           % Takes an input like "[2,3,4,5,6]"
i=I'*I                 % Multiplies the input by its own transverse
      *1-eye(nnz(I));  % Multiplies by 1-identity matrix to remove diagonal
mode(i(:))             % Calculates most common value and prints it

1
我不知道你需要做的I'*I*1-eye为什么不I'*I-eye
aaaaa说恢复莫妮卡




4

随员,59字节

Last##~SortBy#`&&:`~##{Flat[UpperTriangle&1!Table&_!`*]^^0}

在线尝试!

仍然需要打高尔夫球,但对于我选择的方法,我认为这几乎是最佳的。

说明

这是三个功能的组合:

  1. {Flat[UpperTriangle&1!Table&_!`*]^^0}
  2. SortBy#`&&:`~
  3. Last

第一个函数执行大部分计算:

{Flat[UpperTriangle&1!Table&_!`*]^^0}
{                                   }    anonymous lambda; input: _ (e.g.: [2,3,4,5,6])
                      Table&_!`*         shorthand for Table[`*, _]
                                         this creates a multiplication table using the input
                                         e.g.:
                                           4  6  8 10 12
                                           6  9 12 15 18
                                           8 12 16 20 24
                                          10 15 20 25 30
                                          12 18 24 30 36

      UpperTriangle&1!                   takes the strict upper triangle of this matrix
                                         e.g.:
                                          0 6  8 10 12
                                          0 0 12 15 18
                                          0 0  0 20 24
                                          0 0  0  0 30
                                          0 0  0  0  0
Flat[                           ]^^0     flattens this list and removes all 0s
                                         e.g.: [6, 8, 10, 12, 12, 15, 18, 20, 24, 30]

第二个有点复杂,但做起来却很简单。首先,知道这f&n是一个函数,当使用参数调用该函数时会...x返回,将很有用f[...x, n]f&:n相似,返回f[n, ...x]。现在,让我们分解一下:

( ~SortBy ) # (`& &: `~)

首先,f#g创建一个叉子。输入n后返回f[n, g[n]]。但是,在这种情况下f是函数~SortBy~f反转函数的参数。这表示~f#g等于f[g[n], n]SortBy[(`& &: `~)[n], n]

`& &: `~遵循以下形式f&:n。但是什么是`&`~?它们是“运算符引号”,并返回与被引用的运算符等效的函数。因此,在这种情况下,`&与相同${ x & y }。考虑到这一点,对于二进制运算符,此表达式等效于以下表达式:

f&:n   <=>   ${ f[n, x] }
       <=>   ${ (`&)[`~, x] }
       <=>   ${ `~ & x }

这将产生函数`~&x,这x是第一个函数的结果。n ~ a计算nin 的出现a。因此,这将返回一个函数,该函数对函数1的计算数组中参数的出现进行计数。

回到 SortBy,根据数组中每个元素出现的次数。

最后,Last选择最常出现的元素。领带被排序算法打断。


是否需要UpperTriangle部分?您能把桌子弄平并整理一下吗?
svavil

@svavil是的,它是必需的;[5, 2, 9, 10, 3, 4, 4, 4, 7] -> 16而不是20没有它。
科纳·奥布莱恩

4

JavaScript(ES6),72 70字节

a=>a.map(m=o=(y,Y)=>a.map(x=>Y--<0?m=(o[x*=y]=-~o[x])<m?m:o[r=x]:0))|r

在线尝试!


@tsh问题是主要对角线,根本不应该计算倍数。因此,对于倒数第二个测试用例,它失败了,其中三个16 在主对角线上,使其得分足够高,可以返回而不是预期 20
Arnauld

3

木炭,24字节

WθF×⊟θθ⊞υκI⊟Φυ⁼№υι⌈Eυ№υλ

在线尝试!链接是详细版本的代码。说明:

Wθ

当输入数组为非空时...

×⊟θθ

...弹出最后一个元素,并将数组的其余部分乘以该元素...

F...⊞υκ

...并将结果推送到预定义的空列表。

⌈Eυ№υλ

计算每种产品出现在列表中的次数,并以最大次数...

Φυ⁼№υι...

...然后过滤计数等于该最大值的产品...

I⊟

...然后弹出最后一个元素并转换为字符串以进行隐式打印。


3

外壳,7个字节

Ṡ►#mΠṖ2

在线尝试!

说明

Ṡ►#mΠṖ2  -- example input [3,3,3]
     Ṗ2  -- subsequences of length 2: [[3,3],[3,3],[3,3]]
   mΠ    -- map product: [9,9,9]
Ṡ        -- apply 
  #      -- | count occurences in list
 ►       -- to maxOn that list: [9]

3

APL(Dyalog Unicode)29 27 19字节

{⌈/⊢/⊣¨⌸∊⍵}⍳∘≢↓¨⊢×⊂

在线尝试!

默契

感谢Adám的默认版本和2个字节。

感谢ngn提供8个字节!

怎么样:

{⌈/⊢/⊣¨⌸∊⍵}⍳∘≢↓¨⊢×⊂
                ⊢×⊂    Multiply each element with the entire argument, then
           ⍳∘≢↓¨       Remove 1 from the first, two from the next etc. (removes repeated multiplications);
                       The result is then fed into the function:
{       ∊⍵}            Flatten the result;
     ⊣¨⌸               Key; creates a matrix in which each row corresponds to a unique product;
   ⊢/                  Get the rightmost column of the matrix;
 ⌈/                    Get the highest value.

1
只有27岁
亚当


3

CJam70 68字节

q',/S*~_,(:L{LX-,0a\+[{X1++}*](;{_X=\_Y=@*\}fY}fX]~;]_{\_@e=}$\;_,(=

在线尝试!

说明

q',/S*~                                                                  Turn input string into a valid CJam array
       _,(                                                               Find the length of the array and subtract 1
          :L                                                             Assign the result to L
            {                                 }fX                        Outer for loop
             LX-,0a\+[{X1++}*](;                                         Create an array with all the array indexes bigger than X
                                {          }fY                           Inner for loop
                                 _X=\_Y=@*\                              Create a multiple of array[X] and array[Y] (Guaranteed to be from a unique combination of factors)
                                                 ~;]                     Casts away all stack items except for an array of the multiples
                                                    _{\_@e=}$\;          Sorts array by number of occurrences (largest number of occurences at the end)
                                                               _,(=      Gets the last element of the array

由于代码很长,您将需要向右滚动以查看说明以及说明。


这绝对是一场噩梦。CJam没有电源设置功能(与其他众多高尔夫语言不同-我个人来说是个不错的选择),这意味着我必须手动找到电源设置。但是,这给了我机会来忽略任何无效数量的因子,这与其他带有幂集函数的答案不同。

考虑到我在CJam表现糟糕,这应该可以打高尔夫球。


变化:

海伦切断了2个字节!

旧:q',/S*~_,1-:L{LX-,0a\+[{X1++}*](;{_X=\_Y=@*\}fY}fX]~;]_{\_@e=}$\;_,1-=
新:q',/S*~_,(:L{LX-,0a\+[{X1++}*](;{_X=\_Y=@*\}fY}fX]~;]_{\_@e=}$\;_,(=

通过将1-s 更改为简单,(我们可以获得相同的效果,但字节数更少。





2

SQL Server, 93 bytes

SELECT TOP 1a.a*b.a
FROM @ a
JOIN @ b ON a.i<b.i
GROUP BY a.a*b.a
ORDER BY COUNT(a.a*b.a)DESC

Input is assumed to come from a table of the form

DECLARE @ TABLE (A int, i int identity);

Example table population:

INSERT INTO @ VALUES (9), (7), (10), (9), (7), (8), (5), (10), (1);

Explanation:

I assume a "list of integers" will have an index associated with them, which in my case is the column i. The column a contains the values of the list.

I create products of every pair, where the left pair comes in the list earlier than the right pair. I then group on the product, and sort by the most populous number.

I'm a little sad I didn't get to use any cte or partitioning clauses, but they were just too long. SELECT is a very expensive keyword.

Alternative, 183 bytes

WITH c
AS(SELECT a,ROW_NUMBER()OVER(ORDER BY a)r
FROM @),d AS(SELECT a.a*b.a p,COUNT(a.a*b.a)m
FROM c a
JOIN c b ON a.r<b.r GROUP BY a.a*b.a)SELECT TOP 1p
FROM d
ORDER BY m DESC

If SQL doesn't get to have a separate index column, here is a solution where I create an index using the ROW_NUMBER function. I personally don't care about the order, but an order is required and using the a column is the shortest.



2

Burlesque - 8 bytes

Jcp)pdn!

J        duplicate
 cp      cross product
   )pd   map . product
      n! most common element

Try it online here.

(and yes, Burlesque also has a command for "least common element")


2

C# (Visual C# Interactive Compiler), 95 bytes

x=>x.SelectMany(y=>(x=x.Skip(1)).Select(z=>y*z)).GroupBy(y=>y).OrderBy(y=>y.Count()).Last().Key

Try it online!

Less golfed code:

// x is a list of integers
x=>
  // iterate over each integer and
  // return a list per element.
  // flatten the list of lists to 1 list
  x.SelectMany(y=>
    // skip the current value and save
    // newly offset list to x so that it
    // can be incrementally offset
    // again next pass
    (x=x.Skip(1))
      // compute the product
      .Select(z=>y*z))
    // get the unique products
    .GroupBy(y=>y)
    // sort the products by number
    // of occurrences
    .OrderBy(y=>y.Count())
    // pick the product with the
    // greatest number of occurrences
    .Last().Key

1

PHP, 91 bytes

while($c=$argv[++$i])for($k=$i;--$k;)$r[$c*$argv[$k]]++;asort($r);echo end(array_flip($r));

takes input from command line arguments; run with -nr or try it online.

Use PHP 7 to avoid STRICT MODE warning.


1

J, 29 25 24 23 bytes

(0{~.\:1#.=)@(</#&,*/)~

Try it online!

how

(~. {.@\: 1 #. =)@(</ #&, */)~
                  (</ #&, */)~  NB. all products, dups removed:
                          */    NB. create the times table
                   </           NB. lower triangular ones matrix
                       &,       NB. flatten each and
                      #         NB. filter based on lower triangle
                 @              NB. pass that result to
(~. {.@\: 1 #. =)               NB. get the most frequent list item:
       \:                       NB. sort down
 ~.                             NB. the uniq elements
          1 #. =                NB. by their count
    {.@                         NB. and take the first element


0

APL(NARS), 53 chars, 106 bytes

{0=l←↑⍴⍵:⍵⋄t⊃⍨q⍳⌈/q←{+/t=⍵}¨t←×/¨(∊(⍳l)∘.<⍳l)/,⍵∘.,⍵}

Test:

  p←{0=l←↑⍴⍵:⍵⋄t⊃⍨q⍳⌈/q←{+/t=⍵}¨t←×/¨(∊(⍳l)∘.<⍳l)/,⍵∘.,⍵}
  p 9
9
  p 1 3
3
  p 2 3 4 5 6
12
  p 7 2
14
  p 2 3 3
6
  p 3 3 3
9
  p 1 1 1 1 2 2
2
  p 6 200 10 120
1200
  p 2 3 4 5 6 7 8 8
24
  p 5 2 9 10 3 4 4 4 7
20
  p 9 7 10 9 7 8 5 10 1
63
  p 3 3
9
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.