5318008-计算器带来的乐趣


32

在世界各地的学校中,孩子们在LCD计算器中键入数字后,将其倒置并在创建“笨蛋”一词后大笑。当然,这是最受欢迎的词,但是还有许多其他词可以被产生。

但是,所有单词的长度必须少于10个字母(但是词典中包含的单词长度不超过10个字母,因此您必须在程序中执行过滤器)。在此词典中,有一些大写单词,因此将所有单词都转换为小写。

使用英语词典,创建一个数字列表,可以将这些数字输入到LCD计算器中并生成一个单词。与所有代码高尔夫球问题一样,以最短的程序完成此任务将获胜。

对于我的测试,我使用了UNIX单词列表,该单词列表是通过键入以下内容收集的:

ln -s /usr/dict/words w.txt

或者,在这里获取它。

例如,上面的图像是通过35007在计算器中键入数字并将其上下颠倒而创建的。

字母及其相应的数字:

  • b8
  • g6
  • l7
  • 1
  • o0
  • s5
  • z2
  • h4
  • e3

请注意,如果数字以零开头,则在该零后需要一个小数点。该数字不能以小数点开头。

我认为这是MartinBüttner的代码,只是想向您致谢:)

/* Configuration */

var QUESTION_ID = 51871; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";

/* App */

var answers = [], page = 1;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      if (data.has_more) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SIZE_REG = /\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;
var NUMBER_REG = /\d+/;
var LANGUAGE_REG = /^#*\s*([^,]+)/;

function shouldHaveHeading(a) {
  var pass = false;
  var lines = a.body_markdown.split("\n");
  try {
    pass |= /^#/.test(a.body_markdown);
    pass |= ["-", "="]
              .indexOf(lines[1][0]) > -1;
    pass &= LANGUAGE_REG.test(a.body_markdown);
  } catch (ex) {}
  return pass;
}

function shouldHaveScore(a) {
  var pass = false;
  try {
    pass |= SIZE_REG.test(a.body_markdown.split("\n")[0]);
  } catch (ex) {}
  return pass;
}

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  answers = answers.filter(shouldHaveScore)
                   .filter(shouldHaveHeading);
  answers.sort(function (a, b) {
    var aB = +(a.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0],
        bB = +(b.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0];
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  answers.forEach(function (a) {
    var headline = a.body_markdown.split("\n")[0];
    //console.log(a);
    var answer = jQuery("#answer-template").html();
    var num = headline.match(NUMBER_REG)[0];
    var size = (headline.match(SIZE_REG)||[0])[0];
    var language = headline.match(LANGUAGE_REG)[1];
    var user = getAuthorName(a);
    if (size != lastSize)
      lastPlace = place;
    lastSize = size;
    ++place;
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", user)
                   .replace("{{LANGUAGE}}", language)
                   .replace("{{SIZE}}", size)
                   .replace("{{LINK}}", a.share_link);
    answer = jQuery(answer)
    jQuery("#answers").append(answer);

    languages[language] = languages[language] || {lang: language, user: user, size: size, link: a.share_link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 50%;
  float: left;
}

#language-list {
  padding: 10px;
  width: 50%px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>


4
即使不需要,也可以在第一个数字后面使用小数点吗?
丹尼斯

1
难道我们必须键入0.7734用于打招呼或将.7734是可以接受的?
丹尼斯

3
如果词典中包含大写,标点符号等单词,正确的行为是什么?
彼得·泰勒2015年

1
@Dennis 0.7734是必需的
Beta Decay

4
要求小数点后跟零的单词呢?例如,oligo需要一个尾随零的小数点:0.6170
骆驼先生

Answers:


7

CJam,44 42字节

r{el"oizehsglb"f#W%"0."a.e|N+_,B<*_W&!*r}h

CJam解释器中在线尝试。

要从命令行运行程序,请下载Java解释器并执行:

java -jar cjam-0.6.5.jar 5318008.cjam < /usr/share/dict/words

怎么运行的

r            e# Read a whitespace-separated token from STDIN.
{            e# While loop:
 el          e#   Convert to lowercase.
 "oizehsglb" e#   Push that string.
 f#          e#   Get the index of each character from the input in that string.
             e#   This pushes -1 for "not found".
 W%          e#   Reverse the resulting array.
 "0."a       e#   Push ["0."].
 .e|         e#   Vectorized logical NOT. This replaces an initial 0 with "0.".
 N+          e#   Append a linefeed.
 _,B<*       e#   Repeat the array (array.length < 11) times.
 _W&!*       e#   Repeat the array !(array.intersection(-1)) times.
 r           e#   Read a whitespace-separated token from STDIN.
}h           e# If the token is not empty, repeat the loop.

9

Bash + coreutils,54岁

再次感谢@TobySpeight提供的高尔夫帮助。

rev|tr oizehsglb 0-8|sed '/.\{11\}\|[^0-9]/d;s/^0/&./'

输入单词表取自STDIN:

$ ./5318008.sh < /usr/share/dict/words | head
8
38
338
5338
638
5638
36138
31738
531738
7738
$ 

“ Belie”和“ Belies”是单词吗?您知道的越多...
clismique

6

Python 2中,271 216 211 205字节

这是我到目前为止唯一的想法。一旦想到其他事情,我将进行更新!我以为我们需要从文件中读取内容,但是如果没有告诉我,我可以进行更新:)

非常感谢Dennis为我节省了55个字节:)

同时还要感谢Sp3000节省了6个字节:)

d,f,g='oizehsglb',[x.lower()for x in open('w.txt').read().split('\n')if len(x)<10],[]
for x in f:
 c=x[::-1]
 for b in d:c=c.replace(b,`d.find(b)`)
 g=[g,g+[['0.'+c[1:],c][c[0]!='0']]][c.isdigit()]
print g

我不太了解Python,但是会不会"oizehsglb".index(b)更短一些?
丹尼斯

3
d[b] == "oizehsglb".index(b)。可能缺少对字符串/字符的强制转换。
丹尼斯

1
哦,哇,我从没想到我们能够替换的数字是按顺序排列的数值。是的,那绝对可以!谢谢!
卡德2015年

1
尚未测试,但:1).find短于.index2)取决于您所使用的版本,至少在2.7.10中,open不带模式参数的默认值是r3,这是否for x in open(...)行得通?(可能需要删除尾随的换行符),如果不是,则.split('\n').splitlines()
Sp3000

1
另外g+=[['0.'+c[1:],c][c[0]!='0']]*c.isdigit(),您可以通过反向f执行for c in f而不是执行操作来节省更多c=x[::-1]。另外,您只使用f一次,因此您无需将其另存为变量
Sp3000,2015年

6

JavaScript(ES7),73个字节

仅需73个字节即可在ES7中完成此操作:

s=>[for(w of s)'oizehsglb'.search(w)].reverse().join``.replace(/^0/,'0.')

取消高尔夫:

var b = function b(s) {
    return s.length < 10 && /^[bglioszhe]*$/.test(s) ? s.replace(/./g, function (w) {
        return 'oizehsglb'.search(w);
    }).reverse().join('').replace(/^0/, '0.') : '';
};

用法:

t('hello'); // 0.7734
t('loose'); // 35007
t('impossible'); //

功能:

t=s=>                       // Create a function 't' with an argument named 's' 
   [                        // Return this array  comprehension
     for(i of s)            // Loops through each letter in the string
     'oizehsglb'.search(w)  // Converts it to it's corresponding number
   ]
  .reverse().join``         // Reverse the array and make it a string
  .replace(/^0/,'0.')       // If the first character is a 0, add a decimal after it

我在UNIX单词表上运行了此命令,并将结果放入了粘贴容器中:

结果

用于在Firefox上获取结果的代码:

document.querySelector('pre').innerHTML.split('\n').map(i => t(i.toLowerCase())).join('\n').replace(/^\s*[\r\n]/gm, '');

会发生什么t('Impossible')
Arturo TorresSánchez2015年

@ArturoTorresSánchez是的,我已经解决了
Downgoat 2015年

是加入``ES2015还是ES2015之前的版本?
WallyWest

@WallyWest这是ES6的功能。大多数主流浏览器都支持该功能
Downgoat 2015年

ES7的具体含义是什么?
Arjun

5

Python 2,121字节

for s in open("w.txt"):
 L=map("oizehsglb".find,s[-2::-1].lower())
 if-min(L)<1>len(L)-9:print`L[0]`+"."[L[0]:]+`L`[4::3]

假设字典文件 w.txt以尾随换行符结尾,并且没有空行。


3

GNU sed,82岁

(包括1个-r

感谢@TobySpeight提供高尔夫帮助。

s/$/:/
:
s/(.)(:.*)/\2\1/
t
s/://
y/oizehsglb/012345678/
/.{11}|[^0-9]/d;s/^0/&./

输入单词表取自STDIN:

$ sed -rf 5318008.sed /usr/share/dict/words | tail
3705
53705
1705
0.705
50705
5705
505
2
0.02
5002
$ 

2

TI-BASIC,75岁 88字节

编辑2:没关系,这在技术上仍然无效,因为它一次只能接受一个单词(不接受字典)。我将尝试对其进行修复,以允许输入多个单词...

编辑:哎呀;我本来使其在显示.0 结束,如果最后一个数字为0,而不是周围的其他方法。已修复,尽管这是一种不好的解决方法(如果数字以0开头,则在数字旁边显示“ 0.”,否则在同一位置显示两个空格)。从好的方面来说,它可以正确处理“ Otto”之类的单词(显示两个0),因为它实际上并未显示十进制数字!


我想不出更好的语言来做。当然可以打更多的高尔夫球,但是我现在太累了。代字号是否定符号[ ( - )按钮]。

输入来自计算器的答案变量,这意味着最后一次求值的内容(例如_在交互式python shell中),因此您必须在主屏幕上键入一个字符串(带引号的位置ALPHA+),按ENTER,然后运行程序。另外,您可以使用冒号分隔命令,因此,如果将程序命名为“ CALCTEXT”,并且要在字符串“ HELLO”上运行它,则可以键入"HELLO":prgmCALCTEXT而不是单独执行。

seq(inString("OIZEHSGLB",sub(Ans,X,1))-1,X,length(Ans),1,~1
Text(0,0,sub("0.  ",1+2(0 or Ans(1)),2),sum(seq(Ans(X)10^(dim(Ans)-X),X,1,dim(Ans

2

Python 2中,147个 158 156字节

我错过了这个“ 0”。需求。希望现在一切正常。

编辑:删除了“ .readlines()”,它仍然有效; p

edit2:删除一些空格并将打印移至第三行

edit3:由于Sp3000而节省了2个字节(打印后删除了空间,并将“索引”更改为“查找”)

for x in open("w.txt"):
 a="oizehsglb";g=[`a.find(b)`for b in x[::-1].lower()if b in a]
 if len(g)==len(x)-1<10:
  if g[0]=="0":g[0]="0."
  print"".join(g)

1

Python 2中,184个 174字节

for s in open('w.txt'):
 try:a=''.join(map(lambda c:dict(zip('bglioszhe','867105243'))[c],s[:-1][::-1]));a=[a,'0.'+a[1:]][a[0]=='0'];print['',''.join(a)][len(s)<11]
 except:0

1

Ruby 2,88 86字节

x="oizehsglb"
puts$_.tr(x,"0-8").reverse.sub /^0/,"0." if$_.size<11&&$_.delete(x)<?A

ln命令行中的选项的字节数包括2 :

$ ruby -ln 5318008.rb wordlist.txt

在这种情况下==""可以替换为<?A。而无需gsub()sub()就够了。
manatwork 2015年

1

C,182个 172 181分之169 172字节

char*l="oizehsglb",S[99],*s,*t;main(x){for(;t=S+98,gets(S);){for(s=S;*s;s++)if(x=strchr(l,*s|32))*--t=48+x-(int)l;else break;*t==48?*t--=46,*t=48:0;*s||s-S>10?0:puts(t);}}

展开式

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *l="oizehsglb",S[99],*s,*t;

main(int x, char **argv)
{
    for (;t=S+98,gets(S);){
        for (s=S;*s;s++)
            if (x=strchr(l,*s|32))
                *--t=48+x-(int)l;
            else
                break;
        if (*t==48) {       // '0'
            *t--=46;        // '.'
            *t=48;  // '0'
        }

        if (!*s && s-S <= 10)
            puts(t);
    }
}

使用链接的words.txt,并进行小写转换:

$ ./a.out  < words.txt  | tail
2212
0.2
0.802
0.602
7702
37702
0.02
321607002
515002
0.02002

$ ./a.out < words.txt   | wc -l
 550

1
*s|32在这种情况下不能用作小写转换吗?
哈根·冯·埃岑2015年

好点子!谢谢!
用户

1

Haskell,不带导入的175个字节(带导入的229个字节)

相关代码(例如在文件Calc.hs中):

import Data.Char(toLower)
import Data.Maybe(mapMaybe)
s="oizehsglb\n"
g('0':r)="0."++r
g x=x
main=mapM_(putStrLn.g.reverse.mapMaybe(`lookup`zip s['0'..'8'])).filter(\l->length l<10&&all(`elem`s)l).lines.map toLower=<<getContents

$ cat /usr/share/dict/words | runghc Calc.hs

0

Java中,208个 200 176字节

String f(char[] w){String o="",l="oizehsglb";for(int i=w.length;i>0;i--)o+=l.indexOf(w[i-1]|32);if(o.contains("-")||o.length()>8)o="  ";return o.charAt(0)+"."+o.substring(1);}

展开式

String f(char[] w)
{
    String o = "", l = "oizehsglb";
    for(int i = w.length; i > 0; i--)
        o+=l.indexOf(w[i-1]|32);
    if(o.contains("-")||o.length() > 8)
        o = "  ";
    return o.charAt(0) + "." + o.substring(1);
}

它总是加上小数,当无效返回“。”。但除此之外,它应该可以正常工作。:P

谢谢@ LegionMammal978!


您可以通过更改保存7个字节;String l=,l==o++=
LegionMammal978
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.