自我识别坐标


27

编写一个程序或函数,给定一个整数n,该程序或函数构造一个长度为n维的数组n,其中每个元素都是其自身坐标的标识符。也就是说,从一个数组开始,向其中填充n数组,其中每个n数组包含更多数组,深度为n-1。最深数组的元素是描述它们在完整数组中的位置的坐标。

一些例子,以防我的解释令人困惑。

n = 1

["1"]

n = 2

[
 ["11", "12"],
 ["21", "22"]
]

n = 3

[
  [
    ["111","112","113"],
    ["121","122","123"],
    ["131","132","133"]
  ],
  [
    ["211","212","213"],
    ["221","222","223"],
    ["231","232","233"]
  ],
  [
    ["311","312","313"],
    ["321","322","323"],
    ["331","332","333"]
  ]
]

在此,“ 321”表示它是第三数组第二元素的第一元素。

规则:

  • 坐标和尺寸(n)可以为0或1索引
  • 您可以假设n两个索引选项的位数都为10以下,以防止产生歧义
  • IO是灵活的。
    • 特别是,坐标可以是数组,字符串等,只要它们清楚即可。“ 321” => [3,2,1]
    • 输出可以是以10为底的整数,带或不带前导零。
    • 如果需要,坐标可以相反,只要一致即可。“ 321” =>“ 123”
    • 输出不一定必须是您语言中的数组结构。只要在数组的开头,数组的结尾和元素的分隔之间有明确的标记即可。
    • 的输出n=1只能是1
    • 如果您的输出是非典型的,请确保说明格式。
  • 这是因此每种语言中最短的解决方案是成功的!

沙盒(已删除)
Jo King

在意识到类型系统无法实现之前,我在用Haskell编写代码时遇到了麻烦。
小麦巫师

@CatWizard:您总是可以定义一个新的数据结构来解决这个问题,例如。data L a = L [L a] | E a
ბიმო


1
@ToddSewell您不能拥有一个函数的类型取决于输入。该功能可以有型Int -> [String]Int -> [[String]]等等,根据输入是什么
H.PWiz

Answers:



10

Python 3,56个字节

f=lambda n,*l:len(l)//n*l or[f(n,*l,k)for k in range(n)]

在线尝试!

Xcoder先生节省了2个字节,切换到Python 3进行加星标解压缩。


3
如果您切换到Python≥3.5,则f=lambda n,*l:len(l)//n*l or[f(n,*l,k)for k in range(n)]适用于56个字节。
Xcoder先生18年


6

J,18个字节

,"1/^:(]{:)~@,.@i.

在线尝试!

迭代解决方案,没有内置的笛卡尔积。这就是峰J的样子。

                       input                                    2
                i.     range                                 0, 1
             ,.@       reshape each element
                       into a one-dimensional array        [0],[1]   (A)
    ^:(]{:)            (input−1) times...             (1 iteration)
,"1/       ~@             prepend the contents of each 1d array in A    |
                          to every 1d array from the previous iteration,|  
                          assembling the results for each A[n] into     |!CANTEXPLAINTHIS!
                          a larger array                                |
                                                         [ [0,0],       |
                                                           [0,1] ],     |
                                                         [ [1,0],       |
                                                           [1,1] ]      |

起初,较高的字节数使我失望,但这确实是美丽的J
约拿(Jonah)'18

6

果冻8 7字节

ṗ³s³$³¡

在线尝试!

说明

以参数2为例。

ṗ³s³$³¡   
ṗ        Cartesian power with power
 ³       2 (the argument). Autoranges the left arg.
         Yields [[1,1],[1,2],[2,1],[2,2]]
    $³¡  Do 2 times:
  s³     Split into segments of length 2. 
         This last step molds the array of indices into the proper shape.

如果¡没有变化,那么对于二元组的迭代来说是正确的参数,那么这将是4个字节:ṗs³¡


对我来说,这似乎是一个完整的程序。您确定输出(STDOUT)1有效吗?
暴民埃里克(Erik the Outgolfer)'18年

@EriktheOutgolfer我可以接受1的输出
Jo King

@JoKing但是,在这种情况下,没有“为数组的开始,数组的结尾清除明显的标记”。您要编辑问题吗?(很多答案实际上并没有包含它们)
Outgolfer的埃里克(Erik the Outgolfer

5

J,13个字节

[:{[;/@$,:@i.

在线尝试!

有趣的是,这比APL答案要长得多(尽管这可能是我无法看到更好的翻译)

说明

[: { [ ;/@$ ,:@i.


     [                NB. the argument
            ,:@i.     NB. range 0..arg, considered as one item: ,: is "itemize" 
          $           NB. repeat the right range the left number of times
       ;/@            NB. and then put boxes around them. so, eg, if we had
                      NB. an arg of 3, now we have the list of boxes 
                      NB. [0 1 2][0 1 2][0 1 2]
[: {                  NB. { is "Catalog", it creates the cartesian product
                      NB. in exactly the format we desire.


@FrownyFrog使用挂钩来避免#.inv非常聪明,+ 1。
科尔

@FrownyFrog现在,我已经研究了您的“不同基础上的费用”解决方案,我认为这种方法足够不同,您应该自己将其添加为另一篇文章。这是一个非常好的解决方案。
约拿(Jonah)'18年

乔纳,@ cole谢谢您
FrownyFrog

5

MATLAB,92 89 55字节

重新阅读挑战规则后,我有一个不同的答案,但是由于它与众不同,并且看起来仍然很有趣,因此我将下面的尝试留在下面。

reshape(string(dec2base(0:n^n-1,n+(n<2))),[~(1:n)+n 1])

说明

                        0:n^n-1                        % [0,1,...,n^n-1]
               dec2base(       ,n+(n<2))               % Put into base n (base 2 if n=1)
        string(                         )              % Convert to strings
                                          [~(1:n)+n 1] % Dimension array [n,n,...,n] (length n)
reshape(                                 ,            )% Use dim array to reshape

这将输出索引为0的字符串的n维数组。

上一个答案(89字节)

我的第一个高尔夫!这可能可以减少更多,但我想我应该发布一下。

x=(1:n)';for d=2:n;y=((1:n)*10^(d-1));o=[];for p=1:nnz(y);o=cat(d,o,(x+y(p)));end;x=o end

说明

x=(1:n)';                       % Create array x=[1,2,...n]'
for d=2:n                       % d for dimension
    y=((1:n)*10^(d-1));         % Creates an array for each d where
                                %   y=[10,20,30,...] for n=2
                                %   y=[100,200,...] for n=3 etc.
    o=[];                       % o for output
    for p=1:nnz(y)              % For each value of y
        o=cat(d,...             % Concatenate in the dth dimension:
            o,...               % - The current output
            x+y(p));            % - The sum of
                                %   - The array from the last dimension
                                %   - The current value in y (e.g. 100)
    end
    x=o                         % Send the output to x for the next loop
end

在末尾输出x以给出解

与其他MATLAB文章类似,输出是一个n维数组,不同之处在于它使用数字显示坐标。它适用于任何值,尽管由于MATLAB中循环不好,它在n = 8附近开始显着减慢。

编辑:-2字节感谢路易斯·门多。还删除了最后的分号以打印输出。


4
欢迎来到PPCG!
毛茸茸的

我想你可以替换length通过nnz节约几个字节。另外,按照PPCG规则,代码必须产生一些实际输出,通常是通过在STDOUT中显示它(将输出存储在变量中是不够的),或者它必须是返回输出的函数
Luis Mendo

5

201 176 167 166 154字节

enum L{S(String),L(Vec<L>)}fn
h(n:u8,d:u8,s:&str)->L{if
d<1{L::S(s.into())}else{L::L((0..n).map(|i|h(n,d-1,&format!("{}{}",s,i))).collect())}}|n|h(n,n,"")

在线尝试!

由于语言是严格类型的,因此输出类型是具有两个变体的求和类型。它可以是L,可以是包含此求和类型的列表类型,也S可以是结果类型(字符串)。结果看起来像这样。

L::L([
 L::L([ L::S("00"), L::S("01") ]),
 L::L([ L::S("10"), L::S("11") ]),
])

另外,使用rustfmt以下命令重新格式化:

enum L {
    S(String),
    L(Vec<L>),
}
fn h(n: u8, d: u8, s: &str) -> L {
    if d < 1 {
        L::S(s.into())
    } else {
        L::L(
            (0..n)
                .map(|i| h(n, d - 1, &format!("{}{}", s, i)))
                .collect(),
        )
    }
}
|n| h(n, n, "")

4

R,102字节

function(n,m=array(T,rep(n,n)))`if`(n<2,'1',{m[]=apply(which(m,T)[,`[<-`(1:n,1:2,2:1)],1,toString);m})

在线尝试!

  • 1索引,反向
  • 不幸的是,R按列存储矩阵,否则我们可以减少到73个字节
  • @Giuseppe建议使用which数组索引,节省了-9个字节

您的76个字节的答案可能是73个字节,这是我在检查是否已经有R答案之前实现的方式。但是,您也许可以更改某些方法?不太确定。
朱塞佩

1
@Giuseppe:which我一直在寻找数组索引,谢谢!已保存9个字节
digEmAll

4

Java 10,144个字节

解决方法是方法f。它产生数组的字符串表示形式。

String h(int n,int d,String s){if(d<1)return s;var r="[";for(int i=0;i++<n;)r+=h(n,d-1,s+i)+",";return r+"]";}String f(int n){return h(n,n,"");}

在线试用

不打高尔夫球

String h(int n, int d, String s) {
    if (d < 1)
        return s;
    var r = "[";
    for (int i = 0; i++ < n;)
        r += h(n, d - 1, s + i) + ",";
    return r + "]";
}
String f(int n) {
    return h(n, n, "");
}

致谢


1
在Java 10中,您可以替换Object[]var。另外,我认为此else块是不必要的,就像您returnif块中一样。
Konrad Borowski

3

05AB1E,7个字节

LsãsGsô

在线尝试!

说明

L          # push range [1 ... input]
 sã        # input repeated cartesian products of the list
   sG      # input - 1 times do:
     sô    # split into input parts


3

MATLAB,116 108 104字节

考虑到MATLAB对多维矩阵的亲和力,我觉得必须有一种更短的方法来完成此工作...感谢Luis提供的一些短手操作的4个字节

a=~(1:n)+n;c=cell(1,n);[c{:}]=ind2sub(a,1:n^n);reshape(arrayfun(@(varargin)[varargin{:}],c{:},'un',0),a)

说明

% For using twice, define the array of dimension sizes [n, n, .., n]
a=~(1:n)+n;
% To group variable number of outputs from ind2sub into a cell array
c=cell(1,n);   
% Convert linear indices to self-describing coordinates
[c{:}]=ind2sub(a,1:n^n);     
% reshape to make it the n-dimensional array
% arrayfun to loop over the numerous ind2sub outputs simultaneously
% varargin and {:} usage to account for various numbers of inputs
reshape(arrayfun(@(varargin)[varargin{:}],c{:},'uni',0),a)

输出是n维单元格数组,其中每个元素都是坐标值的数组。n只要数字数组输出,n^(n+1)就可以毫无歧义地工作,只要元素数组可以存储在RAM中即可!


3

木炭,26字节

Nθ≔EXθθ⪫⪪◧⍘ιθθ ¦0υFθ≔⪪υθυυ

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

Nθ

输入n

≔EXθθ⪫⪪◧⍘ιθθ ¦0υ

nⁿ n在base中生成全数字n

Fθ≔⪪υθυ

将它们分割n成一个n维数组,其中每个维的大小都为size n

υ

打印数组。默认输出格式是每个元素在其自己的行上,然后每个n行块都以空白行终止,然后每个行nn以第二个空白行终止,依此类推,直到n-1最上层的空白行。


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.