种元:获得最短答案中的最长者


14

您的任务(如果您接受)是编写一个程序,该程序通过计算与比赛的获胜者来帮助理解我对meta建议。当然,此问题的答案将被视为建议的答案,因此您的程序(如果正确)可以计算您的答案是否将成为接受的答案。

规则

  • 程序读取具有以下格式的多行文件(请参见下面的示例):[Language] TAB [NumberOfCharacters] TAB [LinkToAnswer]
  • 文件名将作为参数传递给您的程序,或者将文件重定向到程序的标准输入。由您选择,给出答案时请提及方法
  • 预期输入格式正确。无需进行错误处理。
  • 字符数为正。您的程序必须处理的长度最大为65535。64k应该足够每个人使用:-)
  • 程序在标准输出上输出符合meta提案思想的那些行,即
    • 特定编程语言的最短代码胜出(简化阶段)
    • 所有编程语言中最长的代码胜出(排序阶段)
    • 抽奖时,应打印所有相同长度的答案
  • 输出顺序并不重要
  • 尽管最长的代码获胜,但这不是。对于您的编程语言,您的代码必须尽可能短。
  • 很少尝试不缩短代码的编程语言的答案应该被否决,因为它们试图绕过这种问题的意图。如果对于一种特定的编程语言只有一个答案,那么它将被视为优胜者,因此您可以开始发布其代码。

输入文件示例(如果格式有问题,请用单个选项卡分隔):

GolfScript  34  http://short.url/answer/ags
GolfScript  42  http://short.url/answer/gsq
C#  210 http://short.url/answer/cs2
Java    208 http://short.url/answer/jav
C#  208 http://short.url/answer/poi
J   23  http://short.url/answer/jsh
Ruby    67  http://short.url/answer/rub
C#  208 http://short.url/answer/yac
GolfScript  210 http://short.url/answer/210

预期输出(顺序不重要):

C#  208 http://short.url/answer/poi
C#  208 http://short.url/answer/yac
Java    208 http://short.url/answer/jav

更新资料

有些程序依赖于一个最大值的事实(例如C#210字符程序)。源自现实,有人还可以编写一个包含210个字符的GolfScript程序。输出将保持不变。我已经在输入中添加了一个GolfScript。

更新2

如建议的那样,我已重新标记(仍然是代码高尔夫球),截止日期为2014-03-06(这看起来像是一个任意日期,但随后我将返回德国)。

最终结果

我决定投票如下:

  • 无法确认字符数的答案会给出注释以说明计数。
  • 可以轻松减少的答案得到评论,编辑建议,并以较低的计数值进入结果。(希望我已经提前看到了)。
  • 未编译的答案将被否决。(事实证明这是一项艰巨的任务)。
  • 未打高尔夫球的答案会被拒绝(如规则中所述)。
  • 产生预期输出的答案会受到欢迎。由于某些答案无法按预期工作,因此我使用了4个不同的输入文件,并对照预期结果进行检查。

最后,通过提供合格答案表作为我的参考程序的输入(加上手动仔细检查结果)来确定获胜者。如果我自己的答案将是获胜的答案,则将其从列表中排除。如果有几个获奖者,我将只选一个。因此,可以获得一些奖金:

  • 接受的输入比预期多的答案(例如超出定义范围)
  • 答案简短明了

我已于2014年3月6日UTC + 1拍摄了答案的快照。分析正在进行中。检查所有答案比预期的要难...


现在不应该将其标记为代码挑战吗?还有什么时候截止?
TheConstructor 2014年

2
替代

Answers:


2

Java的-556

import java.util.*;class G{public static void main(String[]x){TreeMap<?,TreeMap>m=new TreeMap();try{Scanner s=new Scanner(System.in);for(;;){String[]a=s.nextLine().split("\t");a(new Long(a[1]),a(a[0],m)).put(a[2],a);}}catch(Exception e){}TreeMap<?,Map<?,String[]>>n=new TreeMap();for(TreeMap o:m.values())a(o.firstEntry().getKey(),n).putAll((Map)o.firstEntry().getValue());for(String[]o:n.lastEntry().getValue().values())System.out.println(o[0]+"\t"+o[1]+"\t"+o[2]);}static<T>Map a(T t,Map m){if(m.get(t)==null)m.put(t,new TreeMap());return(Map)m.get(t);}}

程序将从STDIN读取。

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

class G {
    public static void main(String[] x) {
        TreeMap<?, TreeMap> m = new TreeMap();
        try {
            Scanner s = new Scanner(System.in);
            for (; ; ) {
                String[] a = s.nextLine().split("\t");
                a(new Long(a[1]), a(a[0], m)).put(a[2], a);
            }
        } catch (Exception e) {
        }
        TreeMap<?, Map<?, String[]>> n = new TreeMap();
        for (TreeMap o : m.values())
            a(o.firstEntry().getKey(), n).putAll((Map) o.firstEntry().getValue());
        for (String[] o : n.lastEntry().getValue().values())
            System.out.println(o[0] + "\t" + o[1] + "\t" + o[2]);
    }

    static <T> Map a(T t, Map m) {
        if (m.get(t) == null)
            m.put(t, new TreeMap());
        return (Map) m.get(t);
    }
}
  1. 程序将逐行读取,直到发生异常( ArrayIndexOutOfBoundsException遇到空白行或NoSuchElementException输入结束而不尾随新行)。读取的每一行都会添加到中TreeMap m,该行可能已定义为TreeMap<String, TreeMap<Long, TreeMap<String,String[]>>>(从左至右:语言,代码大小,URL,输入)。
  2. 然后是结果TreeSet<Long, TreeSet<String, String[]>> n构建(从左到右:代码大小,URL,输入),其中firstEntry()汇总了每种语言的内容。
  3. lastEntry() 的合计 TreeMap包含我们的结果-我们只需要打印即可。

尝试ideone.com(切换输入的后两行以显示所有行均已读取)


必须添加一个变量来存储BufferedReader -.-
TheConstructor 2014年

1
也许Java这次赢了,因为它没有var关键字...
Thomas Weller 2014年

@ThomasW。只是意识到我在高尔夫球版本中留下了一些不必要的{}
TheConstructor 2014年

还可以说我正在使用Integer。虽然int比long短,但Integer肯定应该打高尔夫球Long -.-
TheConstructor 2014年

2

Perl,195个字节

while(<>){/(\S+)\t(\d+)\t(.+)/;push@{$a{$1}},$3if$2==$l{$1};$l{$1}=$2,$a{$1}=[$3]if $2<($l{$1}//65536)}$m=(sort{$b<=>$a}values%l)[0];map{$l=$_;map{print"$l\t$m\t$_\n"if$l{$l}==$m}@{$a{$l}}}keys%l

预期在STDIN中输入,结果写入STDOUT:

C#      208     http://short.url/answer/poi
C#      208     http://short.url/answer/yac
Java    208     http://short.url/answer/jav

非高尔夫版本

#!/usr/bin/env perl
use strict;
$^W=1;

# hash %language remembers the minimum count for a language
# %language: <language> => <minimum count>
my %language;
# hash %array remembers the URLs for the minimum count of the language
# %array: <language> => [<url>, <url>, ....]
my %array;

while(<>){
    # parse input line (no error checking)
    /(\S+)\t(\d+)\t(.+)/;
    my ($lang, $count, $url) = ($1, $2, $3);
    # add URL, if the count is the current minimum for the language
    if ($count == ($language{$lang}//0)) {
    # better, but longer version:
    # if (defined $language{$lang} and $count == $language{$lang}) {
        push @{$array{$lang}}, $url;
    }
    # create a new entry for the language, if there is a new minimum
    if ($count < ($language{$lang}//65536)) {
    # better, but longer version:
    # if (not defined $language{$lang} or $count < $language{$lang}) {
        $language{$lang} = $count;
        $array{$lang} = [$url];   
    }
}

# Sort the minimal values in numerical descending order and
# get the first entry as maximum.
my $maximum = (sort { $b <=> $a } values %language)[0];

# Loop over all URLs of minimal answers for the language,
# but print only the entries for the languages with the largest
# minima.
foreach my $lang (keys %language) {
    foreach my $url (@{$array{$lang}}) {
        if ($language{$lang} == $maximum) {
            print "$lang\t$maximum\t$url\n";
        }
    }
}
__END__

正如@grovesNL所指出的,Heiko,某些程序可能依赖于一个最大值的事实。也许您可以检查您的程序是否受到影响。只需GolfScript 210 http://short.url/answer/210在输入中添加一行,然后查看输出是否保持不变即可。实际上,我认为您的机器并没有受到影响,因为您使用的最大值为[0],但是目前我还没有Perl可以尝试。
Thomas Weller

@ThomasW .:不受影响。我添加了这一行,输出保持不变。在读取文件的第一部分之后,数据结构%l/ %language包含语言及其最小值。数据结构%a/ %array仅包含那些语言/ URL对,其值是该语言的最小值。然后,最小值按降序排序,第一个用作全局最大值和%a/的过滤条件%array
Heiko Oberdiek

2

Python的378 377 372

import sys
d=__import__("collections").defaultdict(list)
o={}
x=int
n="\n"
for i,l,u in[a.split()for a in sys.stdin.read().strip().split(n)]:d[i]+=[(l,u)]
for e,b in d.items():o[e]=[i for i in b if i[0]==str(min([x(i[0])for i in b]))]
print("".join(n.join("\t".join([u,s[0],s[1]])for s in y if x(s[0])==max(x(i[0][0])for i in o.values()))+n for u,y in o.items()).strip())

在标准输入上输入:

C:\Users\gcq\Documents\python>type m.txt | python test.py
C#      208     http://short.url/answer/poi
C#      208     http://short.url/answer/yac
Java    208     http://short.url/answer/jav

这就是我开始压缩它之前的结果,为551个字符:

from collections import defaultdict
import sys
d = defaultdict(list)

for language, length, url in [a.split() for a in sys.stdin.read().strip().split("\n")]:
    d[language].append((length, url))

o = {}
for language, data in d.items():
    winval = data[0][0]
    for i in data:
        if int(i[0]) < int(winval):
            winval = i[0]
    o[language] = [i for i in data if i[0] == winval]

maxlen = max(int(i[0][0]) for i in o.values())

for language, dataa in o.items():
    for data in dataa:
        if int(data[0]) == maxlen:
            print("\t".join([language, data[0], data[1]]))

1

C#-628

这是您使用的更长的替代方法DataTable

using Microsoft.VisualBasic.FileIO;namespace System{using T=Data.DataTable;using R=Data.DataRow;using V=Data.DataView;using C=Data.DataColumn;class p{static void Main(string[] a){var I=typeof(Int32);T t=new T();t.Columns.AddRange(new[]{new C("a"),new C("b",I),new C("c"),new C("d",I)});var f=new TextFieldParser(a[0]);f.SetDelimiters("\t");while(!f.EndOfData){var r=t.NewRow();r.ItemArray=f.ReadFields();t.Rows.Add(r);}foreach(R r in t.Rows){r[3]=t.Compute("min(b)","a='"+r[0]+"'");}V v=new V(t);T s=v.ToTable();foreach(R r in s.Select("b='"+t.Compute("max(d)","")+"'")){Console.WriteLine(String.Join("\t",r[0],r[1],r[2]));}}}}

我本来以为我可以通过将max / min与一起使用来使代码减少一些DataTable,但是DataTable不幸的是,构建(行/列/视图)所需的类型增加了很多长度。我是打高尔夫球的新手,所以也许有人可以进一步减少打高尔夫球。仍然是一个有趣的挑战。


1

分克- 286个 281 260 251 218字节

import '/sys'
d=dict!
for(a,b,c)in(map str.split$(sys.stdin.read!).splitlines!)=>d!!a=(d.get a list!)+(list'(int b,c))
for(i,l)in(d.items!)=>for(s,u)in l=>s==(max$map(i->fst$min i)d.values!)=>print$i+' '+(str s)+' '+u

例:

$ cat langs.txt | dg langs.dg 
C# 208 http://short.url/answer/poi
C# 208 http://short.url/answer/yac
Java 208 http://short.url/answer/jav

非高尔夫版本:

import '/sys'

s = sys.stdin.read!
d = dict!
# convert the string into a list of tuples (name, score, url)
u = map str.split $ s.splitlines!
# add all the values to the dict (converting the score to an integer)
for (a, b, c) in u =>
  d!!a = (d.get a list!) + (list' (int b, c))
# computes the maximum value amongst the mins
m = max $ map (i -> fst $ min i) d.values!
for (i, l) in (d.items!) =>
  for (s, u) in l =>
    # if the score equals the maximum then print all the line
    s == m => print $ i + ' ' + (str s) + ' ' + u  # actually here .format()
                                                   # would be better

问:dg到底是什么?
答:一种可以编译为CPython字节码的编程语言,就像Scala可以编译为JVM一样。实质上,这意味着dg是Python 3的替代语法。它还允许您使用所有现有的库。

更多信息在这里(甚至是教程!):https : //pyos.github.io/dg


如果我将其放入文件中,则只有217个字节(Linux行结尾)
Thomas Weller 2014年

@ThomasW。奇怪的!使用cat langs.dg | wc -c我得到218!
rubik 2014年

也许尾随换行而不是尾随换行?
TheConstructor 2014年

@TheConstructor可能是,尽管它不应该用换行符oO保存
rubik 2014年

1

Rebol-314

d: map[]foreach r read/lines to-file system/script/args[r: split r tab p: take r r/1: to-integer r/1 r/2: reduce[r/2]either none? d/:p[repend d[p r]][case[d/:p/1 > r/1[d/:p: r]d/:p/1 = r/1[append d/:p/2 r/2]]]]l: 0 foreach[k v]d[l: max l v/1]foreach[k v]d[if l = v/1[foreach n v/2[print rejoin[k tab v/1 tab n]]]]

未打高尔夫球

d: map []

foreach r read/lines to-file system/script/args [
    r: split r tab
    p: take r
    r/1: to-integer r/1
    r/2: reduce [r/2]
    either none? d/:p [repend d [p r]] [
        case [
            d/:p/1 > r/1 [d/:p: r]
            d/:p/1 = r/1 [append d/:p/2 r/2]
        ]
    ]
]

l: 0 foreach [k v] d [l: max l v/1]
foreach [k v] d [
    if l = v/1 [
        foreach n v/2 [print rejoin [k tab v/1 tab n]]
    ]
]

用法示例:

$ rebol script.reb data.txt
C#    208   http://short.url/answer/poi
C#    208   http://short.url/answer/yac
Java  208   http://short.url/answer/jav

0

C#-515

需要文件名作为参数

using System.Collections.Generic;namespace N{using S=SortedList<int,T>;class T:List<string>{static void Main(string[]a){var d=new Dictionary<string,S>();int n,m=0;T w=new T();foreach(var l in System.IO.File.ReadAllLines(a[0])){var p=(a=l.Split('\t'))[0];n=int.Parse(a[1]);if(!d.ContainsKey(p))d.Add(p,new S());if(!d[p].ContainsKey(n))d[p].Add(n,new T());d[p][n].Add(l);}foreach(var e in d){n=e.Value.Keys[0];if(n==m)w.AddRange(e.Value[n]);if(n>m)w=e.Value[m=n];}foreach(var e in w)System.Console.WriteLine(e);}}}

首先,我设计C#程序要简单明了,因为我想拥有一种参考程序。但是后来我决定自己也参加比赛并打高尔夫球。这是该代码的早期版本之一,加上一些注释:

// N: namespace
// P: Program
// S: type definition: sorted dictionary
// a: arguments
// d: data container
// r: lines read from text file
// l: single line from r
// t: tabbed part of l after splitting
// p: programming language name
// n: character count
// m: maximum character count
// w: list of winners
// e: entry in data container
// c: winner candidate
using System.Collections.Generic;
namespace N
{
    using S = SortedList<int, P>;
    public class P : List<string>
    {
        public static void Main(string[] a)
        {
            var r = System.IO.File.ReadAllLines(a[0]);
            // Make it a data structure
            var d = new Dictionary<string, S>();
            foreach (var l in r)
            {
                var t = l.Split('\t');
                var p = t[0];
                var n = int.Parse(t[1]);
                if (!d.ContainsKey(p)) d.Add(p, new S());
                if (!d[p].ContainsKey(n)) d[p].Add(n, new P());
                d[p][n].Add(l);
            }
            // Get the maximum values
            var m = 0;
            P w = null;
            foreach (var e in d)
            {
                foreach (var s in e.Value.Keys)
                {
                    if (s > m)
                    {
                        w = e.Value[s];
                        m = s;
                    }
                    else if (s == m)
                    {
                        w.AddRange(e.Value[s]);
                    }
                    break; // Break here to get the shortest solution per language
                }
            }
            // Print everything on console
            foreach (var e in w)
            {
                System.Console.WriteLine(e);
            }
        }
    }
}

磁盘上的515文件大小似乎包含一个字节顺序标记。从此处复制/粘贴仅512个字节。
Thomas Weller 2014年

0

C# - 460 359

意识到DataTable解决方案的体积之后,我使用Linq创建了以下示例。它使用的方法与我以前的解决方案相同。

打高尔夫球

namespace System{using Linq;using IO;class p{static void Main(string[]i){var l=(from f in File.ReadAllLines(i[0])let s=f.Split('\t')select new Tuple<string,int,string>(s[0],Convert.ToInt16(s[1]),f)).ToList();foreach(var f in l.Where(a=>a.Item2==l.Where(b=>b.Item1==l.Single(c=>c.Item2==l.Max(d=>d.Item2)).Item1).Min(e=>e.Item2)))Console.WriteLine(f.Item3);}}}

不打高尔夫球

namespace System
{
    using Linq;
    using IO;
    class p
    {
        static void Main(string[]i)
        {
            var l=(from f in File.ReadAllLines(i[0])
                   let s=f.Split('\t')
                   select new Tuple<string, int, string>(s[0],Convert.ToInt16(s[1]),f)).ToList();
            foreach(var f in l.
                Where(a=>a.Item2==l.
                    Where(b=>b.Item1==l.
                        Single(c=>c.Item2==l.
                            Max(d=>d.Item2)).Item1).
                                Min(e=>e.Item2)))
            Console.WriteLine(f.Item3);
        }
    }
}

我对Linq还是很陌生,所以我几乎肯定那些表达可以进一步简化。

从您的问题来看,尚不清楚是否有单个最大长度的解决方案。对于我的答案,我假设存在一个最大点(即,如果GolfScript最大值也为210,则基于返回的单个最大记录可能会失败)。Heiko的解决方案将有相同的问题。要解决此问题,我们将不得不添加另一个步骤,其中包含绑定的最大值列表,以检查每种语言的最小值。


1
在我看来,您可以将f保存为Item3(而不是s [2]),然后将f.Item3写入控制台,而无需重新组合Item1和Item2。
Thomas Weller

感谢您对要求的澄清。源自现实,我会说有人(显然没有经验)用210个字符写一个GolfScript是可能的。
Thomas Weller

1
如果将第一个foreach循环转换为LINQ,它将变得更短:namespace System{using Linq;using IO;class p{static void Main(string[]i){var l=(from f in File.ReadAllLines(i[0])let s=f.Split('\t') select new Tuple<string, int, string>(s[0],Convert.ToInt16(s[1]),f)).ToList();foreach(var f in l.Where(a=>a.Item2==l.Where(b=>b.Item1==l.Single(c=>c.Item2==l.Max(d=>d.Item2)).Item1).Min(e=>e.Item2)))Console.WriteLine(f.Item3);}}}
Thomas Weller 2014年

@ThomasW .:拆分的好主意。感谢foreach循环转换,我本来曾想过添加它,但是我不知道我可以那样做。
grovesNL 2014年

我想我开始了解你的查询不会:),它也将失败像这样简单的输入:Golfscript 100 ...C# 1 ...C# 200 ...。这可能需要重做
Thomas Weller 2014年

0

C ++-535

仅选择每种语言的最短答案作为潜在赢家之后,才会输出与最长位置并列的答案。

#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){

    string s;
    vector<string>l;
    vector<int>v;
    vector<string>u;
    cin>>s;

    ifstream i(s.c_str());

    do{
        int n;
        i>>s;
        if(i.eof())break;
        l.push_back(s);
        i>>n;
        v.push_back(n);
        i>>s;
        u.push_back(s);
    }while(1);

    for(int i=0;i<l.size();i++){
        for(int j=0;j<l.size();j++){
            if(l[j]==l[i]){
                if(v[i]>v[j])l[i]="";
                else if(v[i]<v[j])l[j]="";
            }
        }
    }
    int n=0;
    for(int i=0;i<v.size();i++)
        if(n<v[i]&l[i]!="")n=v[i];

    for(int i=0;i<v.size();i++)
        if(v[i]==n)cout<<l[i]<<'\t'<<v[i]<<'\t'<<u[i]<<endl;
}

打高尔夫球(不像某些语言一样不可读):

#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){string s;vector<string>l;vector<int>v;vector<string>u;cin>>s;ifstream i(s.c_str());do{int n;i>>s;if(i.eof())break;l.push_back(s);i>>n;v.push_back(n);i>>s;u.push_back(s);}while(1);for(int i=0;i<l.size();i++)for(int j=0;j<l.size();j++)if(l[j]==l[i]){if(v[i]>v[j])l[i]="";else if(v[i]<v[j])l[j]="";}int n=0;for(int i=0;i<v.size();i++)if(n<v[i]&l[i]!="")n=v[i];for(int i=0;i<v.size();i++)if(v[i]==n)cout<<l[i]<<'\t'<<v[i]<<'\t'<<u[i]<<endl;}

您是否已将输出与预期输出进行对照?输入8行时,只能输出3行。您的程序似乎可以输出所有内容。
Thomas Weller

@ThomasW。哦,我误会了那部分。我现在将其删除。

@ThomasW。这看起来正确吗?

如果将其放入文件中,我将得到540个字节,而不是535个字节。请您仔细检查一下长度吗?
Thomas Weller 2014年

它是535个字符。我们俩都是正确的。我可以根据需要更改它。
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.