将短月份的名称转换为较长的月份[已结束]


28

挑战已经结束!恭喜Flonk

我确定我会获得很好的成绩,但是上交Flonk的作品后,我的教授不相信这是我的,也无法理解为什么如此复杂...我失败了我的妈妈使我脱离了Facebook和Minecraft一个月。我不明白 :(

感谢您提交的所有内容!这里有一些很好的答案。官方冠军是Flonk,得分为64。前五名是:

  1. Flonk,64岁(Haskell,数学高效!)
  2. DigitalTrauma,40岁(云,未来就在眼前)
  3. primo,38岁(Python和我个人最喜欢的-非常专业!)
  4. Sylwester,20岁(球拍,尽管Janember正在伸展!)
  5. ilmale,16(Lua中的高度优化算法)

以下是原始挑战。


请帮助我,这非常紧急!!!:(

我需要将月份名称的缩写版本转换为更长的表示形式(例如“ Dec”->“ December”),不区分大小写。现在我正在使用Java。该月的名称是一个String,我宁愿不先将其转换为Date对象。但是,任何语言都可以。

是否有捷径可寻??轻松一点,我是编程的新手!


这是一场代码巨魔人气竞赛(这是最好的!)。2014年4月8日投票最多的答案将获胜。


7
“请帮助我,这非常紧急!!! :(” <<<做我的作业,快吗?

13
@yeti尽快!!快上我的课不及格!
詹森C

24
应该有一个功能,可以使用代码拖曳标签将此类问题从Stackoverflow秘密复制到codegolf.SE,然后将codegolf.SE的答案转移回原始帖子,同时删除剧透标签中的文本。
daniero 2014年

根据官方立场,代码拖曳正在被删除这个问题的投票率很高,有很多答案,其中很多投票率都很高。它在民意测验中获得了超过50%的“删除”选票,但它的独特之处在于它获得了如此多的答案和投票,因此我将其锁定为具有历史意义。
门把手

Answers:


74

一点点多项式内插就非常简单!

首先,我查看了短月份名称列表

["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]

并检查了其字符ASCII值的总和

[313,301,320,323,327,333,331,317,328,326,339,300]

然后从中减去300以了解我在这里要处理的内容,并准备了一个数组,其中包含月份名称的所有较长版本。

[13,1,20,23,27,33,31,17,28,26,39,0]
mons = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

我想您可以看到现在发生了什么-我需要的只是一个getIndex函数,该函数将13映射为0、1映射为1、20映射为2,依此类推,所以我可以简单地执行

getMonthName shortname = mons !! (getIndex shortname)

幸运的是,Wolfram | Alpha 可以为我做到这一点!数字有些大,但是Haskell可以很好地处理。我们只需要确保对结果取整即可,因为浮点算术有点不精确!因此,您可以快速,优雅且惯用的Haskell:

import Data.Char

getIndex x = round $ 11 -
    (220797068189915461*x)/11644212222720 +
    (184127469431441671621*x^2)/6982771136140800 -
    (8800438195450444577647153*x^3)/1013060436431307264000 +
    (2826703553741192361967823*x^4)/2026120872862614528000 -
    (269098602165195540339443*x^5)/2026120872862614528000 +
    (13744405529566098359*x^6)/1692665725031424000 -
    (13060656886070844161*x^7)/39727860252208128000 +
    (5939638907108115199*x^8)/675373624287538176000 -
    (303426664924585177*x^9)/2026120872862614528000 +
    (2983240583426137*x^10)/2026120872862614528000 -
    (12901227927103*x^11)/2026120872862614528000

mons = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
getMonthName = (mons!!).getIndex.subtract 300.fromIntegral.sum.fmap (ord.toLower)

像这样简单地运行它:

λ> getMonthName "DeC"
"December"

λ> getMonthName "jan"
"January"

3
很好,整数非常有效我敢肯定我的老师会喜欢我的工作!
杰森C

8
+1教给我有关interpolating polynomial
primo 2014年

3
阅读您的第一句话时,我确实不得不笑了。
照应2014年

46

Bash + GNU工具+“云”

Google可以解决所有问题,我感到很幸运

wget -qU Mozilla -O- "http://www.google.com/search?q=$1+month&btnI" | grep -Eo "<title>[[:alpha:]]+" | cut -d\> -f2

正在使用:

$ ./longmonth.sh jan
January
$ ./longmonth.sh feb
February
$

1
长官好玩!
ojblass 2014年

不能[a-zA-Z]代替[[:alpha:]](至少在我尝试时似乎是这样)的吗?这样可以节省3个字符。通过查询可以保存更多字符ask.com,但这可能不那么可靠。
迈克尔

7
@Mic如果这是代码高尔夫球这将关系
undergroundmonorail

7
@JasonC它是“基于云的”解决方案。当然,不需要其他理由。
Digital Trauma 2014年

4
@DigitalTrauma尊敬的Ive先生先生,我听说过云,它非常专业!很好!很有说服力!Ty -JasonC
Jason C

43

蟒蛇

由于此功能非常重要,因此可能会被大量使用,因此您应尝试使其尽可能快。其他海报推荐使用哈希表查找...不要这样做!与数组相比,哈希映射确实很慢。您只需要将每个缩写转换为数字即可。有一种标准的哈希技术可用于此目的:

index = reduce(int.__mul__, (ord(c) for c in abbr))

几乎可以保证这是唯一的,许多专业工具都在使用它。

现在,您需要创建一个查找功能:

def month_abbr_to_name(abbr):
  months = ["Unknown"] * 2000000

  months[679932]  = "December"
  months[692860]  = "Febuary"
  months[783315]  = "August"
  months[789580]  = "January"
  months[829920]  = "April"
  months[851466]  = "March"
  months[903749]  = "May"
  months[907236]  = "October"
  months[935064]  = "July"
  months[938896]  = "September"
  months[952380]  = "June"
  months[1021644] = "November"

  index = reduce(int.__mul__, (ord(c) for c in abbr))

  month_name = months[index]

  if month_name == "Unknown":
    raise ValueError("Invalid month abbreviation!")

  return month_name

并像这样使用它:

print month_abbr_to_name("Dec")December

HTH!


拖钓

-这段代码太慢了。尽管数组访问的速度确实比哈希图快,但是如果数组比必需的哈希图大数千倍,则此方法不适用。
-每次调用函数时,都会一次又一次地创建这个难以置信的大数组。为了浪费更多的空间,每个值都用“未知”初始化。
-哈希函数对于那些不熟悉Python的人来说是晦涩难懂的。我补充说,它“被许多专业工具使用”以阻止调查。
-散列函数的独特性足以在十二个月内正确消失,但不会捕获许多常见的错字,例如交换字符。
-几乎任何长度超过3个字符的字符串都会在数组索引超出范围时崩溃。
-“ Febuary”拼写错误。
-“此功能非常重要。” 对OP进行次要自我干预。


12
伙计们,好好看看;是一个正确的代码拖尾答案!附言 我确定我会因此而获得良好的成绩,并且比我尝试编写的sloooow Java shell脚本要好得多!! [在此处输入图片描述]
Jason C

2
“ Febuary”拼写错误。-严重的巨魔:)
Jaa-c

10
+1表示哈希表效率低下,然后实现了一个效率很低的哈希表
James_pic

1
“ 与数组相比,哈希表确实很慢。您只需要将每个缩写转换为数字即可。为此可以使用一种标准的哈希技术...”,换句话说,就是重新实现哈希图。哈哈 +1
wchargin

25

球拍

我寻求一个KISS解决方案。我已经用OP的用例“ Dec”进行了全部测试,以检查是否返回了正确的结果。它以鲜艳的色彩通过。

(define (long-month short-month)
  (define end "ember")   
  (string-titlecase 
   (string-append short-month end)))

;; Test OP's use case
(long-month "DEC") ;;==> "December"

显然,这里的恶魔是它仅在少数情况下有效,因此它是无用的:-)


可能是因为,在代码跟踪标签Wiki中,“任务是提供有效的代码,但无用,严重地阻碍了OP。”您的代码甚至无法正常工作。在这里,再投票一次。
user12205 2014年

@ace它不会引发任何错误,并且会返回正确的答案“十二月”。这个问题没有指定它应该在其他月份使用,也没有指定它们的长名,因此我希望在结尾加上“ ember”是一个很好的答案。
Sylwester 2014年

1
关于这个问题,“我需要将月份名称的缩写版本转换为更长的表示形式(例如,“ Dec”->“ December”)” 12月是一个示例,并非所有情况都如此。您的程序应适用于所有月份名称。
user12205 2014年

9
@ace确实如此。看看OP到底想要什么的示例,它将“ Jan”变成“ Janember”。我真的看不到如何降低代码滚动标签的答案,因为“故意误解问题”和“对问题作弊”都是回答问题的好方法。
Sylwester 2014年

7
这正是我正在考虑提供的解决方案的类型,带有“免责声明:您说的很紧急,所以我匆匆忙忙地只测试了3个案例,但所有案例都通过了”。
AShelly

22

鲁阿

我的解决方案将使用您的语言环境,您的教授会很高兴

input = ...
found = false
input = string.lower(input)

i = 12
while i > 0 do
   abb = os.date("%b")
   if string.lower(abb) == input then
      print(os.date("%B"))
      return
   end
   os.execute('sleep 28d')
   i = i - 1
end
print('not found')

测试

lua 25207.lua aPr
April

检查当前月份的缩写,如果正确,则返回长字符串,否则重试。


辉煌!让我想起了我<<错误:连接超时的时间。>
joeytwiddle14年

13

佩尔

use re 'eval';$_=lc<>;
s/b/br/;s/an|br/$&uary/;s/(?<!u)ar/arch/;s/r$/ril/;s/p$/pt/;s/t|v|c$/$&ember/;
s/ju(.)/$&.$1=~tr\/nl\/ey\/r/e;s/(?<=g)/ust/;s/ctem/cto/;
print ucfirst;

-正则表达式地狱。我希望正则表达式不算作“用晦涩的语言拖拉”。
-非常脆弱。您很难添加对Bugsember的支持。
-不可读。模式内部的模式使它更加如此。
-将6月和7月压缩为单个语句实际上并没有压缩任何内容。
-随机使用lookbehind for g,而其他人在替换中重复使用该模式。
- use re 'eval'实际上是不需要的;仅在需要可变模式时使用。同样,使用eval来“获得”一点“压缩”。


17
对我来说,我看起来像是普通的Perl ...
Peter Olson 2014年

1
@PeterOlson选择了适合该算法的语言,但是该算法根本不适合该任务,您不同意吗?:-)
John Dvorak 2014年

10

爪哇

您说您当前的代码是用Java编写的,所以我想我会让您更轻松。

// The standard library's there, so you should use it
import static java.util.Calendar.*;

public class MonthConverter {

  private static int shortNameToNumber(String shortName) {
    int i;
    switch (shortName) {
      case "jan": i = 1;
      case "feb": i = 2;
      case "mar": i = 3;
      case "apr": i = 4;
      case "may": i = 5;
      case "jun": i = 6;
      case "jul": i = 7;
      case "aug": i = 8;
      case "sep": i = 9;
      case "oct": i = 10;
      case "nov": i = 11;
      case "dec": i = 12;
      default: i = 0;
    }
    return i;
  }

  private static String numberToLongName(int month) {
    switch (month) {
      case JANUARY: return "January";
      case FEBRUARY: return "February";
      case MARCH: return "March";
      case APRIL: return "April";
      case MAY: return "May";
      case JUNE: return "June";
      case JULY: return "July";
      case AUGUST: return "August";
      case SEPTEMBER: return "September";
      case OCTOBER: return "October";
      case NOVEMBER: return "November";
      case DECEMBER: return "December";
      default: return "Unknown";
    }
  }

  public static String fullName(String shortName) {
    return numberToLongName(shortNameToNumber(shortName));
  }

  public static void main(String[] args) {
    // Always test your code
    System.out.println("jan is: " + fullName("jan"));
    assert fullName("jan").equals("January");
  }
}

日历类有一个有趣的小陷阱,其中月份从0开始编号JANUARY == 0。但是,这显然不会影响我们的代码,因为我们对其进行了测试,对吗?请注意,shortNameToNumber中有一个意外切换,这意味着每个月的最终结局为0。很容易JANUARY == 0,所以我们的测试通过了。


1
哦,天哪,我没有注意到switch语句中没有中断。自从我使用开关以来已经有很长时间了。
Joe Z.

10

Bash + coreutils + paq8hp12

当前最受好评的答案是每次查询都必须访问互联网。除了效率很低之外,这还意味着如果没有互联网,您的脚本将失败。

最好将必要的信息存储在硬盘上。当然,您可以只存储此脚本所需的数据,但是对于不同的任务,将需要不同的数据。将您可能需要的所有数据存储在单个多功能文件中会更好。

# This script is supposed to output only the wanted information, so we'll have to close
# STDERR and make sure accidental keyboard presses don't show any characters on the screen.

exec 2>&-
stty -echo

# Unfortunately, Bash doesn't have goto labels. Without them, it's impossible to use if
# statements, so we'll implement them.

goto()
{
    exec bash <(egrep -A 1000 "^: $1" $0) $BASH_ARGV
}

# We'll need enwik8, a magic file containing all the important Wikipedia data. EVERYTHING
# can be found on Wikipedia, so this file contains all the information any script could
# possibly need.

ls | grep -q enwik8 && goto alreadydownloaded

# Too bad.

wget http://mattmahoney.net/dc/enwik8.zip
unzip enwik8.zip

# ZIP is a very wasteful format and hard disk space is expensive. It is best to compress
# the file using a more efficient algorithm.

wget http://mattmahoney.net/dc/paq8hp12any_src.zip
unzip paq8hp12any_src.zip

# Make the compression program executable and compress the magic Wikipedia file.

chmod +x paq8hp12_l64
./paq8hp12_l64 enwik8.paq8 enwik8

: alreadydownloaded

# Extract the enwik8 file from the paq archive.

./paq8hp12_l64 enwik8.paq8 enwik8

# Now we use a simple POSIX Basic Regular Expression to find the required information in
# the file.

cat enwik8 | egrep -io "[0-9].[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?.[0-9]" | sort | uniq -c | sort -n | tac | egrep -o "$1[a-z]*" | sort | uniq -c | sort -n | tac | head -n 1 | cut -d ' ' -f 7

# We're done.

拖钓

  • 关闭STDERR,因此如果脚本失败,我们将无法对其进行调试。

  • 禁用输入回显,该结束在脚本完成后仍然存在。如果从终端执行,则必须执行stty echo才能使终端再次可用。如果未从终端执行,则可能导致脚本崩溃。

  • 需要先执行goto。好像这还不够糟糕,如果脚本的文件名包含空格,goto函数将无法正常工作。

  • 如果当前目录中包含包含字符串enwik8的文件,我们将不会下载存档。这可能有效。

  • 下载100 MB的文件(即使压缩到36 MB)显然对于此任务来说是过大的。另外,enwik8包含4 GB以上的Wikipedia转储中的前100 MB,因此对于特定任务,它不太可能包含任何有用的信息。

  • 使用paq8hp12压缩文件可将其压缩到16 MB,但是压缩和解压缩都需要一小时。实际上,第一次运行此脚本时,它将同时执行。

  • 该脚本不会删除enwik8的压缩版本或原始版本,因此将其缩小到16 MB会消耗更多的硬盘空间。

  • 压缩实用程序仅适用于64位处理器。

  • 它将所有已下载或提取的文件保留在当前目录中。

  • 它没有解释脚本中最棘手的部分,即正则表达式管道怪兽。它基本上会提取4到19个字节之间具有前导和尾随数字的所有字符串,按出现次数对这些字符串进行排序,过滤包含短月份名称的字符串,再次按出现次数进行排序,并显示最频繁的字符串。

  • 即使以上一个好主意,一开始也不需要categrep的执行速度很慢,但是regex会返回很多误报(一切都可以用一个regex完成),第一种| uniq -c | 排序-n | tac绝对不执行任何操作,它使用sort | tac而不是sort -rcut不能可靠地工作,因为开头的空格数是可变的。

  • 正则表达式是扩展的 POSIX正则表达式,因此对BRE语法进行搜索根本无济于事。

  • 返回Nov而不是11月,返回6而不是August


1
这些是非常有帮助的建议!当然这会更有效,我的教练告诉我,专业人员可以使数据可重复用于OOP,并且OOP更快,更好!
杰森C

9

Python + SQLite

到目前为止,许多答案都出现了对月份名称进行硬编码的错误。但是,您永远都不知道何时某些教皇或总统会把我们切换到另一个日历,然后大量的日期解析/格式化代码将立即变得一文不值!(或更常见的是,当您需要国际化程序时。)

您需要一个数据库。

CREATE TABLE tblShortMonthNames (
   MonthAbbr CHAR(3) PRIMARY KEY NOT NULL COLLATE NOCASE,
   MonthID   INTEGER NOT NULL
);

CREATE TABLE tblFullMonthNames (
   MonthID   INTEGER PRIMARY KEY,
   MonthName VARCHAR(9) NOT NULL
);

INSERT INTO tblFullMonthNames VALUES (1, 'January');
INSERT INTO tblFullMonthNames VALUES (2, 'February');
INSERT INTO tblFullMonthNames VALUES (3, 'March');
INSERT INTO tblFullMonthNames VALUES (4, 'April');
INSERT INTO tblFullMonthNames VALUES (5, 'May');
INSERT INTO tblFullMonthNames VALUES (6, 'June');
INSERT INTO tblFullMonthNames VALUES (7, 'July');
INSERT INTO tblFullMonthNames VALUES (8, 'August');
INSERT INTO tblFullMonthNames VALUES (9, 'September');
INSERT INTO tblFullMonthNames VALUES (10, 'October');
INSERT INTO tblFullMonthNames VALUES (11, 'November');
INSERT INTO tblFullMonthNames VALUES (12, 'December');

INSERT INTO tblShortMonthNames
   SELECT SUBSTR(MonthName, 1, 3), MonthID FROM tblFullMonthNames;

然后,只需编写一个简单的程序即可对其进行查询。

import sqlite3
import sys

QUERY = """SELECT tblFullMonthNames.MonthName
FROM tblShortMonthNames INNER JOIN tblFullMonthNames USING (MonthID)
WHERE tblShortMonthNames.MonthAbbr = ?"""

with sqlite3.connect('months.db') as db:
    for abbr in sys.argv[1:]:
        row = db.execute(QUERY, [abbr]).fetchone()
        if row:
            print(row[0])
        else:
            print(abbr + ' is not a valid month name.')

5

SH和一个朋友(日期)

功能:

longmonth() {
    date +%B -d"$1 1"
}

测试它:

$ echo $LANG
de_DE.utf8
$ for i in jan feb mar apr may jun jul aug sep oct nov dec ; do longmonth $i ; done
Januar
Februar
März
April
Mai
Juni
Juli
August
September
Oktober
November
Dezember
$ LANG=C
$ for i in jan feb mar apr may jun jul aug sep oct nov dec ; do longmonth $i ; done
January
February
March
April
May
June
July
August
September
October
November
December

这很短...但是计算出“每个角色的邪恶”比例... mwhuaaahahahaaa ...


我不懂语言,所以在这里看不到任何邪恶的东西。我认为您的赞成票来自于处于类似职位的其他人。请解释发生了什么,为什么它是邪恶的。我很好奇。
级圣河

是()滥用date日期格式功能。并且date尊重本地化,它会产生与本地化匹配的月份。-d"a_month_name 1将日期设置为指定月份的第一天(也许简称),并设置缺少的年份,因此它将是下一个这样的月份。+%B是输入给定日期的格式,表示“月份的长名称”。所有tat都包装到一个shell函数中,并且因为那里没有BASH特定的东西,所以SH足以运行它。因此,基本上date应该得到所有掌声,而不是我!而且我不在乎Codegolf中的否决票!:第

我喜欢这个!滥用者。
ojblass 2014年

4

佩尔

良好的蛮力怎么样?

$|++;

use List::Util qw(reduce);

sub hash {
    my $t=9;
    (reduce { $a*$b*log(++$t+$a) } map { ord() } split//, shift)%54321098
}

my @m = (qw( january february march april may june
             july august september october november december ) );
my %targets = map { hash($m[$_]) => 1 } (0..$#m);

chomp(my $in = lc <>);

print ucfirst $in;

my $r;
if(!$targets{hash($in)}) {
  $r = "a";
  ++$r until $targets{hash($in.$r)};
}
print "$r\n";

为什么这很棒:

  • 蛮力总是最强硬的方法。
  • 为了方便起见,请在知道部分答案后立即打印出来(我敢打赌您不知道“ Feb”是从“ Feb ...”开始的缩写)
  • 自定义哈希函数可提供最大的安全性。
  • 使用perl的内置运算符重载(字符串增加)可使此代码与本机C代码一样快。查看所有这些零,显示其运行速度!

    ski@anito:/tmp$ for m in mar apr may jun jul  ; do echo $m | time -f "%U user" perl brute.pl ; done 
    March
    0.00 user
    April
    0.00 user
    May
    0.00 user
    June
    0.00 user
    July
    0.00 user
    
  • 该算法在直观上很明显,我为读者提供了一个练习,但只是为了确保它在所有情况下都有效,让我们检查一下-ber月之一和8月-uber之一,以确保我们没有错过任何东西:

    ski@anito:/tmp$ for m in aug jan oct ; do echo $m | perl brute.pl  ; done 
    August
    January
    October
    

拖曳:

撇开可能会使Damian Conway丧命的编码做法来看,此代码间歇性地出错,并且间歇性地极慢。“ Feb”的运行速度大约比“ may”,“ jun”或“ jul”慢6个数量级-一百万倍。Feboapic,Sepibnd,Novgpej和Decabjuj都不是几个月(尽管尝试发音很有趣)。

    ski@anito:/tmp$ for m in jan feb mar apr may jun jul aug sep oct nov dec ; do echo $m | time -f "%U user" perl  brute.pl  ; done 
    January
    3.14 user
    Feboapic
    62.77 user
    March
    0.00 user
    April
    0.00 user
    May
    0.00 user
    June
    0.00 user
    July
    0.00 user
    August
    0.10 user
    Sepibnd
    1.33 user
    October
    2.22 user
    Novgpej
    1.11 user
    Decabjuj
    4.27 user

PS-我有一些代码,它们的运行时间分布更大,但是在所有情况下它无聊地输出正确的答案,这很有趣。


3

JavaScript-具有分支,叶子和字符串桶的优化节点群集。

// fullMon - Converts month key names to full names using a highly optimized tree for fast traversal.
function fullMon(key) {

    // Initialize the full month string
    var fullMonth = "";

    // Make sure the key is capitalized.
    key = key.substr(0,1).toUpperCase() + key.substr(1).toLowerCase();

    // Set the current node to the tree root.
    var current = fullMon.tree;

    // Traverse the characters in key until we can go no further.
    for (var i = 0; i < key.length; i++) {
        var c = key.charAt(i)
        fullMonth += c
        if (typeof current[c] === "undefined") return key // no full month for this key
        current = current[c]
    }

    // The remaining leaves are the characters in the full month.
    while (current !== null) {
        for (c in current) fullMonth += c
        current=current[c]
    }
    return fullMonth
}

// fullMon.treeBuilder - Builds a character node tree of full month names.
fullMon.treeBuilder = function() {
    // Set a barrel of month keys.
    var barrel = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    // Root node for letter tree.
    var tree = {};

    // Loop through all month keys.    
    for (var i = 0; i < barrel.length; i++) {

        // Get the next month key and do a barrel roll by
        // splitting into an array of single character strings.
        var monKey = barrel[i].split("");

        // Set the current branch to the tree root.
        var branch = tree;

        // Climb branches in the tree by looping through
        // month key characters and doing leaf wipes.
        for (var c = 0; c < monKey.length; c++) {

            // The next character is the next leaf of the branch.
            var leaf = monKey[c];

            // Wipe this leaf on the branch if it doesn't already exist.
            if (typeof branch[leaf] === "undefined") {
                // If the leaf is the last character then it's not sticky should be set to null.
                branch[leaf] = (c === (monKey.length-1)) ? null : {};
            }

            // Switch to the next branch.
            branch = branch[leaf];
        }
    }
    return tree;
}

fullMon.tree = fullMon.treeBuilder();

fullMon.demo = function () {
    // Demonstrates keys that are not found "none" and found keys.
    var short = ["none","jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];
    for (var i = 0; i < short.length; i++) {
        console.log(fullMon(short[i]));
    }
    // Shows the optimized tree for fast lookups.
    console.log(JSON.stringify(fullMon.tree));
}

fullMon.demo();

3

Java,Google和概率

我很失望的是,当互联网上很容易获得答案时,这里的许多解决方案都会“重新发明轮子”。

这是我程序的输出:

The short version of jan is january
The short version of feb is february
The short version of mar is margin
The short version of apr is april
The short version of may is mayinhistory
The short version of jun is june
The short version of jul is july
The short version of aug is august
The short version of sep is september
The short version of oct is october
The short version of nov is november
The short version of dec is december

不完美,但足以发送给质量检查人员。通过利用众包的力量,我能够实现以下结果:

public static String expandMonthName(String shortMonthName) {
    try {
        // First, we ask Google for the answer

        String query = "https://www.google.com/search?q="
                + "what+month+is+" + shortMonthName;
        String response = curl(query);

        // now sift through the results for likely answers.
        // The best way to parse HTML is regex.

        List<String> possibleMonths = new ArrayList<>();
        Pattern pattern = Pattern.compile(shortMonthName + "[A-Za-z]+");
        Matcher matcher = pattern.matcher(response);
        while (matcher.find())
            possibleMonths.add(matcher.group(0));

        // And finally, choose the likeliest answer using 
        // the ineluctable laws of probability

        return possibleMonths.get(new Random().nextInt(possibleMonths.size()));

    } catch (Exception e) { return "August";}   // well, we tried.
}

如果不清楚,expandMonthName(“ jan”)会从Google结果中返回一个随机选择的单词,以“ jan”开头,表示“ what month is jan”。除非您在代理后面,否则它将返回“ August”。


2

Bash + Binutils

我通过将输入转换为日期对象来尽力做到显而易见,但是失败了。最后,我诉诸于暴力手段。

while read -e line; do
  [[ "${line,,}" == "${1,,}"* ]] && o=$line && break
done < <(strings /bin/date)
o=${o:=$1}
o=${o,,}
echo ${o^}

测试运行:

$ bash getmonth.sh jan
January
$ bash getmonth.sh may
May
$ bash getmonth.sh DEC
December

2

我知道检查月份的名称非常困难,并且需要大量的计算和逻辑思考。这是Buzz-Strahlemann算法的优化版本,用于检查月份名称

的PHP

$month = "Jan"; //Change this to search for a different month, noob :)
$time = time(); //This loads an extended time library
$ivefoundthismonthnowexit = false;
while (!$ivefoundthismonthnowexit) {
    $checkThis = date('F', $time); //"F" stands for "Find it"
    if (substr($checkThis, 1, 4) == $month) $ivefondthismonthnowexit = true; //You can also replace it with ($checkThis, 0, 3)
    //since PHP understands if you are counting from 0 or 1!
    $time++;
}

巨魔:

  • 这个答案;

  • 不处理时区,将输出警告消息;

  • 不接受月份作为输入,但是您需要对其进行硬编码;

  • 即使您对其进行硬编码,它也区分大小写;

  • 该代码尝试执行的操作是获取当前月份,获取前三个字母,并检查是否与匹配$month。如果不匹配,则将时间戳加1,然后重试。最终变得非常 ;

  • 这段代码什么也不输出(当然除了警告)。

  • 注释极具误导性:time()不加载扩展时间库,但获取当前时间戳;substr($checkThis,1,4)跳过该月的第一个字母,并得到以下4(archMarch,例如); 正确的形式是评论中的形式;

  • 即使找到匹配项,代码也不会退出循环:实际上,设置为的变量true是不同的。


3
-1:在代码跟踪标签Wiki中,“任务是提供有效的代码,但它无用,使OP严重受挫。”您的代码甚至无法正常工作。
user12205 2014年

1
嗯?它有效且无用。等待10年才能完成无休止的循环还不够令人沮丧吗?“有效”意味着(至少对我而言这意味着)代码可以成功编译并运行,但这并不意味着它必须结束或提供任何解决方案。
Vereos 2014年

@ace(我在上一条评论中忘了提及您);我想在评论中说的是,我想更好地理解您的意思,因为从我的观点来看这是正确的。
Vereos 2014年

也许因为arch永远不会平等Mar
user12205 2014年

因此,您的代码无法转换月份名称,因此不起作用。
user12205 2014年

2

批量

您要的是不平凡的。但是,我为您找到了完美的解决方案!这是通过将非常复杂的英语列表下载到硬盘上来实现的。然后根据下载的列表检查输入内容,并给出月份的最终名称!天才!

现在,此方法比其他方法有很多优点,其中包括:

  • 您可以使用单词的任何缩写!例如Jan还是Janu一月!
  • “您永远不知道什么时候教皇或总统会令我们切换到另一个日历,然后大量的日期解析/格式化代码将立即变得一文不值!” 这对于我们的方法永远不会有问题!
  • 向用户发送确认提示,安全胜过遗憾!

代码:

@ECHO OFF
setlocal EnableDelayedExpansion
REM Remove this at the end ^^^
REM First off, we have to get the user's input
set /p abbreviatedUserInput= Please input your abbreviated form of the month: 
REM echo out confirmation message. Without this, the thing won't work
SET /P variableThatIsUsedForConfirmation= Are you sure you want to look for %abbreviatedUserInput% (Y/N)? 
REM if the user said no, send him elsewhere
if /i {%variableThatIsUsedForConfirmation%}=={n} (goto :hell)
REM to keep things clean, we clear the screen!
cls
ECHO Prepare for launch!
REM make sure the user reads what we wrote, we spent time on this and the user must understand that... 
REM BTW this pings an incorrect ip address and waits 3000 millisex for the output
ping 1.1.1.1 -n 1 -w 3000 > nul
REM to keep things clean, we clear the screen!
cls
REM We must inform the user that something is going on, otherwise they might get bored and quit the app
ECHO LOA-DING!
REM Now, how this works is by utilizing the dictionary.. I believe we all know what that is. First of all, let's get a dictionary!
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://www.mieliestronk.com/corncob_caps.txt', 'dic.txt')"
REM to keep things clean, we clear the screen!
cls
REM The user probably already got bored, let's inform them that we're still working...
ECHO STILL WORKING...
REM wait what?!! The dictionary is all caps!! Lets fix that...
REM Lets loop through the file like so:

for /F "tokens=*" %%A in (dic.txt) do (
    SET "line=%%A"
    REM replace ALL the letters!!
    SET "line=!line:A=a!"
    SET "line=!line:B=b!"
    SET "line=!line:C=c!"
    SET "line=!line:D=d!"
    SET "line=!line:E=e!"
    SET "line=!line:F=f!"
    SET "line=!line:G=g!"
    SET "line=!line:H=h!"
    SET "line=!line:I=i!"
    SET "line=!line:J=j!"
    SET "line=!line:K=k!"
    SET "line=!line:L=l!"
    SET "line=!line:M=m!"
    SET "line=!line:N=n!"
    SET "line=!line:O=o!"
    SET "line=!line:P=p!"
    SET "line=!line:Q=q!"
    SET "line=!line:R=r!"
    SET "line=!line:S=s!"
    SET "line=!line:T=t!"
    SET "line=!line:U=u!"
    SET "line=!line:V=v!"
    SET "line=!line:W=w!"
    SET "line=!line:X=x!"
    SET "line=!line:Y=y!"
    SET "line=!line:Z=z!"
    ECHO !line! >> dic-tmp.txt
)

REM to keep things clean, we clear the screen!
cls
REM The user probably already got bored, let's inform them that we're still working...
:lookup
ECHO WOW! THAT TOOK LONG! ALMOST THERE...
REM Alright, now we need to find the correct date in the dictionary, we might need the users help in this...
REM Lets loop through ALL the lines again
set match=seriously?
for /F "tokens=*" %%a in (dic-tmp.txt) do (
    SET "line=%%a"
    REM to keep things clean, we clear the screen!
    cls
    REM replace the user input with some other stuff...
    SET "test=!line:%abbreviatedUserInput%=lol!"
    REM if the original line does not equal the test variable, then we have a match!
    IF NOT !line!==!test! (
        REM ask the user if the match is correct..
        set /P variableThatIsUsedForConfirmation= "Did you mean !line!? (Y/N): "
        REM if the user entered "y"
        IF /i {!variableThatIsUsedForConfirmation!}=={y} (
            REM set the variable "match" to the current line and goto the matchFound section...
            set match=!line!
            goto :matchFound
        )
    )
)
:matchFound
REM to keep things clean, we clear the screen!
cls
REM give the user their match
Echo Here's your month's full name: %match%
PAUSE
:hell
ECHO screw you!

特罗兹

-批处理...-下载单词列表,因为我们不能手动输入月份...-不使用开关大小写破解 -非常慢-将文本文件转换为小写形式并将其保存在另一个文件中-运行它第二次不删除创建的文本文件,它甚至会更慢-将dic.txt文件转换为小写时,某些脚本将脚本关闭,这使回显重新打开-这种破坏者的事情已经弄乱了格式...


2

!#/ bash

! #/bash

# Make the MONTH variable equal to the $1 variable
MONTH="$1"

# Run grep passing the $MONTH variable and the -i flag
# Then use the << operator followed by a list of months
grep -i "$MONTH" << January
March
May
July
August
0ctober
December
April
June                                      
September
November
February
January

为了使您的程序更快地响应,我在列表中提前了31天。从统计上讲,给定日期的均匀分布,您更有可能在其中一个月中。

我记录了每一行,以打动你的老板。

将此保存在一个名为的文件中,lookup_month_script.bash然后复制并粘贴以下行进行测试:

bash $PWD/lookup_month_script.bash "0ct"

祝您项目顺利!


-尽管一月被列出两次,但在1月不起作用。(实际上,我们January用作heredoc的开始和结束的定界符。)

-在十月份也不起作用。没有人知道为什么。

-如果输入恰好为空,则返回所有11个月。

-如果脚本是复制粘贴的,则6月响应的长度为42个字符。

次要:

-shebang有点不正确,但未给出警告。

-评论,说明下面的行在说什么。

-即使程序确实对较早的条目做出了较快的响应,它仍无法更快地完成。


1

JavaScript的-209

它确实说不转换为日期,这不是这里发生的事情,我只是使用日期来生成短名称的扩展名。

function m(s){c=s.charAt(0).toUpperCase()+s.substr(1).toLowerCase();a="ember,ember,ober,tember,ust,y,e,,il,ch,uary,uary".split(",");b=[];for(i=12;i--;)b[(""+new Date(1,i,1)).slice(4,7)]=11-i;return c+a[b[c]];}

测试输入/输出:

jan: January
feb: Febuary
mar: March
apr: April
may: May
Jun: June
JUL: July
AuG: August
sEp: September
OCT: October
nov: November
dec: December

3
我似乎还拖曳了2月-r :)当然是故意的……
Matt

听起来好像有人遇到了Wendsdays。
杰森C

5
@Matt你的意思不是“出于目的”吗?
贾斯丁

@Quincunx
Matt

1

Java 696包括测试输入

public class DateConverter {
    String months[] = 
    {
        "January", "February","March","April","May","June","July",
        "August","September","October","November","December"
    };
    DateConverter(){}
    String LongMonth(String shortMonth)
    {
        String m = "Invalid";
        for(int i=0;i<months.length;i++)
        {
            if(months[i].toLowerCase().contains(shortMonth.toLowerCase()))
            {
                m=months[i];
                break;
            }
        }
        return m;
    }

    public static void main(String[] args) {

        String input[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
        for(int i=0; i<input.length; i++)
        {
            System.out.println((new DateConverter()).LongMonth(input[i]));
        }
    }
}

1

编程语言“ Brainf * ck”是一个完美的工具!当然,它可能并不是您要找的东西,但是它可以完美地完成工作!

>+<+[>[>[-]+<-]>[<+>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<->-]>>>>>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+

This is the debug part of the code used when looping more than once

>>+++++++++++++++[>+++++>+++++++>++>+++++++>+++<<
<<<-]>--.>+++++.++.+++++.-.>++.<.>>-.---.<.<.>>+++.<<--.>>---..>.<<<------.>>.
<<++++++++..>>.<<--.>.>----.+..<<.>>+++.<<++++.>>++++.--------
.<<--.>>++++++++.<<-----.-.>+.>>[-]<[-]<[-]<[-]<[-]<++++++++++.[-]

It takes a dummy argument due to the nature of my interpreter 
If you're using some other intepreter I can rewrite the code for you

>>>>>>>>>>>>>>>>>>>>>>>,<+<<<<<<<<<<<<<<<<<<<<<<<<->-]>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+

This is the normal part of the code, used when starting the programme the first time

>>+++++++++++++++[>+++++>+++++++>++>+++++++>+++<<<<<-]>--.>
+++++.++.+++++.-.>++.<.>>-.---.<.<.>>+++.<<--.>>---..>.<<<------.>>.<<++++++++..>>.<<-
-.>.>----.+..<<.>>+++.<<++++.>>++++.--------.<<--.>>++
++++++.<<-----.-.>+.>>[-]<[-]<[-]<[-]<[-]<++++++++++.[-]<-]>>>>>>>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>>-]<<<<<<
<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+

Here we take three arguments and assign them to variables; This is the three-letter 
abbreviation of the month

>>>>>>>>>>>>>>,<,<,

Now we check if the abbreviation is good; note that it will fail if it doesn't begin 
with a capital letter and isn't followed by two lowercase letters
In general it will print an error message and wait for you to input a letter 
(or just hit enter) before it exits

<<<[-]>>>>>[<<<<<+<<<<<<<+>>>>>>>>>>>>-]<<<<<<<<<<<<[>>>>>>>>>>>>+<<<<<<<
<<<<<-]>>>>>>>----------------------------------------------------------------->[-]    
<[<<<+>>>-]->[<<<<<<<+>+<<+>>>>>>>>-]<<<<<<<<[>>>>>>>>+<<
<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>
[>>>+<<<[-]]<<<[-]<->>>>>>>[<<<<<<<->>>>>>>-]<<<<<<<[>
>>>>>>+<<<<<<<-]>>>>>>>[>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]
<[>[-]+<-]>[<+>>+++++++++++[>++++++>++++++++++>+++<<<-
]>+++.>++++..---.+++.>.[-]<[-]<[-]<++++++++++.[-]>>>>>>>>>>>>>>>,,<<<<<<<<<<<<<<<<<-<-
>>-]>>>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<+>>>
>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>[-]>>>>[<<<<+    
<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>
>>>>>-------------------------------->[-    
]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<[<<<+>>>-]>    
[<<<<<<<+>+<<+>>>>>>>>
-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]
<<<[>>[-]+<<-]>>-]<[>>>>>>-<<<<<<[-]]>>>[-]>>>>[-]>>
>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>>---------------
----------------->[-]+++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<[<<<<+>>>>-]>[<<<<<<<<+>+
<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>[>>[<+<<
<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>[>>>>-<<<<[-]]<<<[-
]>>>>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>-<<<<<<<[-]]>
>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]<[>>>>>>>[-]-<<<<<<<[-]]->>>>>>>
[<<<<<<<->>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>
>>>>>>+<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[<+>>+++++++++++
[>++++++>++++++++++>+++<<<-]>+++.>++++..---.+++.>.[-]<[-]<[-]<+
+++++++++.[-]>>>>>>>>>>>>>>>,,<<<<<<<<<<<<<<<<<-<->>-]>>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<[>[-]+<
-]>[<+>>>>>>>>>[-]>>>[<<<+<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>-    
------------------------------->[-]+++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++<[<<<+>>>-]>[<<<<<<<+>+<<+>>>>>>>>-]
<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+
<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]<[>>>>>>-<<<<<<[-]]>>>[-]>>>>[-]>>[<<+
<<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-
]>>>>>>>>-------------------------------->[-
]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<[<<<
<+>>>>-]>[<<<<<<<<+>+<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>[>>[<+<<<+>>>>-]
<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>
-]>>[>>>>-<<<<[-]]<<<[-]>>>>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>-<<<<<<<[-]]>>>>>>>>
[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]<[>>>>>>>[-
]-<<<<<<<[-]]->>>>>>>[<<<<<<<->>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>>>>>>>>+
<<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[
<+>>+++++++++++[>++++++>++++++++++>+++<<<-]>+++.>++++..---.+++.>.[-]<[-]<[-]<++++++++++.    
[-]>>>>>>>>>>>>>>>,,<<<<<<<<<<<<<<<<<-<->>-]>>>>>>>>
>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+

This part of the code handles special exceptions to the pattern

>>>>>>>>>[-]>>>>>[<<<<<+<<<<<<<+>>>>>>>>>>>>-]<<<<<<<<<<<<[>>>>>>>>>>>>+<<<<<<<<<<<<-
]>>>>>>>>[-]++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++<[<<<<<<+>>>>>>-]->[<<<<<<<-<+>>>>>>>>-]    
<<<<<<<<[>>>>>>>>+<<<<<<<<-]>[>>>>>>+<<<<<<[-]]>>>>>>>[-]>
>>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>>>[-    
]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++<[<<<<<<<+>>>>>>>-]->[<<<<<<<<-<+>>>>>>>>>-]
<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>[>>>>>>>+<<<<<<<[-]]>>>>>>[<<
<<<<<+>>>>>>>-]<<<<<<<[[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]
<[>>>>>>>-<<<<<<<[-]]]>>>>>>>>[-]>>[<<+<<<<<<<<+>>>>>>>>>>-]
<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>>>[-
]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++<[<<<<<<<+>>>>>>>-]->[<<<<<<<<-<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+
<<<<<<<<<-]>[>>>>>>>+<<<<<<<[-]]>>>>>>[<<<<<<<+>>>>>>>-]<<<<
<<<[[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]<[>>>>>>>-<<<<<<<[-]]]-
>>>>>>>[<<<<<<<->>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>
>[>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[<+>>++++++++++++
[>++++++>++++++++>+++++++++<<<-]>++.>+.>++.+++++++.<
.>---.+++++++.[-]<[-]<[-]<++++++++++.[-]>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<->-
]>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>-
]<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+

This part of the code handles the regular pattern

>>>>>>>>>[-]>>>>>[<<<<<+<<<<<<<+>>>>>>>>>>>>-]<<<<<<<<<<
<<[>>>>>>>>>>>>+<<<<<<<<<<<<-]>>>>>>>.[-]>>>>[<<<<+<<<<<<<+>>>>>>>>>>>-]       
<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>.[-]>>>[<<<+<<<<<<<+>>>>
>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>.<<<<<<<++++++++++++
[>++++++++++>++++++++<<-]>---.>+.<---.+++++++.>[-]<[-]<++++++++++.[-]>>
>>>>>>>>>>>>+<<<<<<<<<<<<<<<<->-]<[>[-]+<-]>[<+

Here the programme checks if you want to insert another abbreviation or are done with the programme

>-]>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<[>[-]+<-]>
[<+>>+++++++++++++++[>+++++>++++++++>++>+++++++>++++>+
+++++<<<<<<-]>--.>-----.>++.<+.>>-.-------.<<.>.>.<<--------..>>>+++.<<.>>>+.--.
<<<+++++++++++++++.<<+++++.>>>----.>>[-]<[-]<[-]<[-]<[-]<[-]
<++++++++++.[-]>>>>>>>>>>>>>>>>>>>>>>>,<<<<<<<<<<,<<<<<<[-]>>>>>>[<<<<<<+
<<<<<<<+>>>>>>>>>>>>>-]<<<<<<<<<<<<<[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]>
>>>>>>>[-]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<[<<<<<<+>>>>>>-]->[<<<<<<<-<+>>>>>>>>-]<<<<<<<<[>>>
>>>>>+<<<<<<<<-]>[>>>>>>+<<<<<<[-]]>>>>>>[>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>
[-]]<<<<<<<<-]<[>[-]+<-]>[<+>>>>>>>>>[-]>>>>>>[<<<<<
<+<<<<<<<+>>>>>>>>>>>>>-]<<<<<<<<<<<<<[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]>>>>>>>>[-
]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++<[<<<<<<+>>>>>>-]->[<<<<<<<-<+>>>>>>>>-]<<<<<<<<[>>>>>>>>+
<<<<<<<<-]>[>>>>>>+<<<<<<[-]]<->>>>>>>[<<<<<<<->>>>>>>
-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<-
>>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[<+-<->>-]>>>>>>>>>>>>>>>>
>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>>>>-]
<<<<<<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>+++++++++++[>++++++>++++++++++>+++
<<<-]>+++.>++++..---.+++.>.[-]<[-]<[-]<++++++++++.[-]<<<->>-]<<]

我相信当您向他展示这个老师时,他会感到骄傲!


拖钓

首先,该程序编写得很糟糕。我做了一些循环,这些循环会导致随机错误打印,并且由于缺少更好的单词而导致普遍无法正常工作。要获得像样的工作代码(主要是在代码的前两段中),需要一点清理工作,因为它给出了长名称“缩写+'uary'”(1月,2月,Maruary等)的方式,因此毫无用处。包括“一月”的冗余代码(定义为异常并单独编码)。关于Stackexchange的第一个答案,所以我希望这符合标准


1

爪哇

尊敬的计算机科学家学徒,

这是一项艰巨的任务,我只能部分解决:我想这是为您的论文工作或某些研究目的。

到目前为止,我只有beta版,但存在一些小错误:有时会产生错误的结果,但是我相信您的教授会接受您的努力。

文件Month.java:

/**
 * This bean keep track of a month-code (e.g. Apr) and month-name (e.g. April)
 * pair.
 */
public class Month{
    String month_name;
    String month_code;
    public void Month(monthName,monthCode){
        setMonthName(monthName);
        setMonthCode(monthCode);
    }
    public String getMonthName(){
        return this.monthName;
    }
    public void setMonthName(String monthName){
        this.monthName=monthName;
    }
    public String getMonthCode(){
        return this.monthCode;
    }
    public void setMonthCode(String monthCode){
        this.monthCode=monthCode;
    }

文件Era.java:

/**
 * This bean keep contains every couple of month-code,month-name in a year.
 */
public class Era{
    List <Month>months;
    public void Era(){
        months.add(new Month("Jan","January"));
        months.add(new Month("Feb","Febrary"));
        months.add(new Month("Apr","March"));
        months.add(new Month("May","May"));
        months.add(new Month("June","June"));
        months.add(new Month("Jul","July"));
        months.add(new Month("Aug","August"));
        months.add(new Month("Sep","September"));
        months.add(new Month("Oct","October"));
        months.add(new Month("Nov","Novemeber"));
        months.add(new Month("Dec","December"));
   }
   public String getMonthByCode(String monthName){

       return String.format("[%s]",months.get(new Random().nextInt((11) + 1) + 0));
   }
   public static void main(String ... argv){
        String monthCode="jan";
       System.out.println(String.format("%s: %s",monthCode, new Era().getMonthByCode(monthCode));
   }

要运行它,执行:

javac Month.java
javac Era.java
java Era jan

输出:

jan: [January]

切记将您设置%JAVAPATH%Java编译器的安装路径!

它只是返回一个随机的月份。其实我什至没有测试。我想有些进口货不见了。


1

由于OP使用Java,因此我将提供Java解决方案。这个想法很简单:

  1. 创建Map从长名称到短名称的名称。
  2. 生成一个随机字符串,将其映射为短名称。
  3. 使用String.equalsIgnoreCase检查短名称是否相同输入简称忽略的情况。如果是这样,成功,退出。
  4. 否则请转到步骤2。

来源如下:

import java.util.*;

public class Short2Long {
    static final Map<String, String> long2Short = new HashMap<String, String>();
    static {
        long2Short.put("Janurary", "jan");
        long2Short.put("February", "feb");
        long2Short.put("March", "mar");
        long2Short.put("April", "apr");
        long2Short.put("May", "may");
        long2Short.put("June", "jun");
        long2Short.put("July", "jul");
        long2Short.put("August", "aug");
        long2Short.put("September", "sep");
        long2Short.put("October", "oct");
        long2Short.put("November", "nov");
        long2Short.put("December", "dec");
    }

    static Random rand = new Random();

    static String genString() {
        int len = rand.nextInt(9-3) + 3;
        StringBuffer res = new StringBuffer(len);
        res.append((char)('A' + rand.nextInt(26)));
        for (int i = 1; i < len; i ++) {
            res.append((char)('a' + rand.nextInt(26)));
        }
        return res.toString();
    }

    public static void main(String[] args) {
        String s = args[0];
        while (true) {
            String l = genString();
            if (s.equalsIgnoreCase(long2Short.get(l))) {
                System.out.println(s + " -> " + l);
                break;
            }
        }
    }
}

拖钓

该程序需要快速的CPU和您的病人。当您学习多线程并拥有多核cpu时,可以尝试使其更快。


1


感谢您发布这个令人发指的问题和原始问题。我们中那些在Stack Overflow上发布答案的人有幸获得帮助海报的机会,因为该网站的目的是对所有此类问题进行分类,从而不再需要教科书和自发学习。不要对这个特定的问题缺乏理解而感到震惊,因为这是常见的问题类型,因为有效地解决它需要隐藏的技巧。教师通常会问这个问题,以确定您对语言的理解深度,并确定您是否意识到程序员的这种常见陷阱:字符编码。在您通读以下链接后,您将更加全面地理解,正如我所知:link

我敢肯定,到现在为止,您的教授已经详细描述了代码重用的重要性,因此,当您阅读我提供的字符编码链接时,您绝对会了解,您将必须制作足够通用的类来可以使用任何语言,即使原始问题并未明确指定此要求(您可能也想了解要求规范,这将有助于您理解要求,请阅读以下链接:link。

您非常聪明地建议不要使用提供的Date对象,因为使用默认语言的代码将无法让您的教授真正理解该语言。

为了帮助您解决这个难题,我编写了一个Groovy应用程序,它将解决您的问题,并且无疑比神秘的Java更有意义。不要为这个答案而使用Groovy感到惊慌,因为Groovy就像Java代码一样在JVM上运行,因此您只需进行少量修改就可以轻松地将此代码放入Java类。我已经附上了一个链接来帮助您完成此过程,但是直到早上我都不会担心,因为它只需花费一秒钟的时间(这里是稍后的链接: link。因此,现在就复制一下代码,因为我将展示大量代码正常运行的测试用例,以便您对自己的提交充满信心。我绝对明白,您是一个非常非常忙碌的渴望学生,承担着很多义务。您可能知道这里的贡献者全职工作,并且得到了很好的报酬。

//Definetely leave the comments in so your instructor
//can see how well you document your code!

//see how easy it is to specify other languages!
//the users of your software will probably have an IDE just
//like yours, so they can easily come into the source
//code and edit these to their liking, That's Code Reuse!
def EnglishNames ="""January
February
March
April
May
June
July
August
October
November
December
"""

//change this to use other encodings, as discussed above
final String encodingToUseSoThatOurCodeIsSuperRobust = "UTF-8"

//it is a good idea to number your lists for clarity,
//just in case you need more
def list1 = []
def list2 = []

//specifying the method name like this will help make it
//easy to add more languages, another method for another
//language

//this is called a 'Closure', which is pretty much identical
//to that cool new Java thing called the 'Lambda', so if you
//wanted to turn this into Java code, it would be soo easy!
EnglishNames.eachLine() {
    //You probably remember you instructor telling you
    //never to do this String 1 == String 2
    //So to get around that, we will convert the String
    //to bytes, Easy huh!
    list1.add(it.getBytes(encodingToUseSoThatOurCodeIsSuperRobust))
}

//change this to run a different test, the IDE no doubt makes
//it very easy to do this!
//See the very very descriptive variable name for readability?
def iAmLookingForThisCountriesLongNameWithThisShortName = "Dec"
def theFoundAnswerInTheListIs

//this is the real important part as you can easily see
for(BigInteger index = 0; index < list1.size(); index ++){
    for(BigInteger indeX = 0; indeX < list1[index].size(); indeX ++){
        list2[index] = [list1[index][0],list1[index][1],list1[index][2]]
    }
}

boolean foundTheAnswerSoDontDoAnymore = false

//now we just find the correct answer in the list!
for(BigInteger index = 0; index < list1.size(); index ++){
    for(BigInteger indeX = 0; indeX < list1[index].size(); indeX ++){
        //see how readable the following code is!
        if((list2.get(index)) == iAmLookingForThisCountriesLongNameWithThisShortName.getBytes(encodingToUseSoThatOurCodeIsSuperRobust)){
            //see how we can now use the == so we can compare the two strings!
            if(!(new Boolean(foundTheAnswerSoDontDoAnymore))){
                println new String(list1[index], encodingToUseSoThatOurCodeIsSuperRobust)
                foundTheAnswerSoDontDoAnymore = true
            }
        }
    }
}

抱歉,我在这里没有为您做任何事情,我很高兴回答您的发人深省的问题。因此,只需复制并粘贴此响应即可。从下面的代码运行中可以看到,这是它的作用:

input: Dec, output: December
input: Jan, output: January
input: Feb, output: February

1

朱莉亚

您将要在这里使用多重调度的功能。首先,我们将定义每个月的类型。然后,我们可以为每个月的类型编写简单的函数定义,以给出所需的答案。这将使您可以使用便捷的形式,nicename(Jan)而不必理会那些烦人的引号。另外,我们可以定义一个便捷函数来接受字符串并将其转换为类型,重用我们已经做过的所有工作以提供一个全新的接口。

abstract Month
abstract Jan <: Month
abstract Feb <: Month
abstract Mar <: Month
abstract Apr <: Month
abstract May <: Month
abstract Jun <: Month
abstract Jul <: Month
abstract Aug <: Month
abstract Sep <: Month
abstract Oct <: Month
abstract Nov <: Month
abstract Dec <: Month
nicename(::Type{Jan})="January"
nicename(::Type{Feb})="February"
nicename(::Type{Mar})="March"
nicename(::Type{Apr})="April"
nicename(::Type{May})="May"
nicename(::Type{Jun})="June"
nicename(::Type{Jul})="July"
nicename(::Type{Aug})="August"
nicename(::Type{Sep})="September"
nicename(::Type{Oct})="October"
nicename(::Type{Nov})="Novermber"
nicename(::Type{Dec})="December"

nicename(s::String)=nicename(eval(symbol(ucfirst(s))))



nicename(Jan)
nicename("jan")

这是什么语言?
ugoren 2014年

朱莉娅,可笑的事情遗漏了。
gggg 2014年

0

Python 2.75

def getMonthName(short):
    from time import time, gmtime, strftime
    time = time()
    while not (lambda t:strftime("%B",t).upper().startswith(short.upper()))(gmtime(time)): time += 1
    return strftime("%B",gmtime(time))

真正的美在于简单,这意味着低内存需求。忘记那些讨厌的字典和代码段。此功能非常好,可以在任何情况下匹配短月份的名称。观察一下。

>>> getMonthName("Apr")
'April'
>>> getMonthName("apr")
'April'
>>> getMonthName("APR")
'April'

奖金:

您可以使用多个前三个字符(例如“ sept”,“ febr”等)

从运行该代码起,这将每秒循环一次,在名称的开头检查是否匹配,因此,如果预期结果不是您当前的月份,则它将永远运行。也有很多样式错误。


0

C#中

 var Dictonery = "january,febuary,March,April,May,June,July,August,September,October,November,December";
                     var input = "jan";
                     var outpt= Regex.Match(Dictonery , input + "[a-z]*",
RegexOptions.IgnoreCase).Value;

0

这是一个满足您要求的小程序。

或者实际上是其中的13个。

我已经用C ++编写了它,因为这是我目前使用的语言,但是它很容易转换为Java。作为一个敬业的学生,​​我敢肯定您可以自己努力。

#include <iostream>
#include <fstream>
#include <cstdlib>

int main()
{
   std::string months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

   for(int i = 0; i <= 12; ++i)
   {
       std::string filename = months[i] + ".cpp";
       std::ofstream myfile;
       myfile.open( filename.c_str() );
       myfile << "#include <iostream>\n\nint main()\n{\n\tstd::cout << \"" << months[i] << "\" << std::endl;\n return " << i << ";\n}";
       myfile.close();

       std::string compile = "g++ " + months[i] + ".cpp -o " +  months[i].substr(0, 3);
       system( compile.c_str() );
   }

   system("Dec");

   return 0;
}

哦,我可能忽略了循环中的一些偏移错误。

我决定变得不错,并使用std::strings而不是char*s。我敢肯定,我会把语法弄糊涂了char*[],我肯定会忘记调用delete,或者做一些愚蠢的事情,例如call delete而不是call delete[]


0

C

将缩写词转换为完整词的某种通用转换,只需调整data数组即可。

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

const char* getLong(char *shrt) {
    size_t position;
    size_t found = 0;
    static int32_t data[19];

    data[000] = 0x756e614a;
    data[001] = 0x46797261;
    data[002] = 0x75726265;
    data[003] = 0x4d797261;
    data[004] = 0x68637261;
    data[005] = 0x69727041;
    data[006] = 0x79614d6c;
    data[007] = 0x656e754a;
    data[010] = 0x796c754a;
    data[011] = 0x75677541;
    data[012] = 0x65537473;
    data[013] = 0x6d657470;
    data[014] = 0x4f726562;
    data[015] = 0x626f7463;
    data[016] = 0x6f4e7265;
    data[017] = 0x626d6576;
    data[020] = 0x65447265;
    data[021] = 0x626d6563;
    data[022] = 0x00597265;

    for (position = 0; position < strlen(shrt); position++) {
        shrt[position] = position < 1 ? (shrt[position] >= 97 ?
        shrt[position] - 97 + 65 : shrt[position]) : (
        shrt[position] <= 90 ? shrt[position] - 90 + 122 : shrt[position]);
    }

    for (position = 0; position < strlen(((char*)data)); position++) {
        if (((char*)data)[position] == shrt[found]) {
            found++;
            if (found == strlen(shrt)) {
                found = position;
                position -= strlen(shrt);
                for (;((char*)data)[found] > 90; found++);
                ((char*)data)[found] = 0;
                return &(((char*)data)[position + 1]);
            }
        } else {
            found = data[0] - data[1] - 0x2EF4EEE9;
        }
    }
    return "not a month";
}

int main(int argc, char *argv[]) {
    if (argc != 2) return 1;
    printf("%s is %s\n", argv[1], getLong(argv[1]));
    return 0;
}

0

的PHP

$month = strtolower($month);
if($month = 'jan') {
return 'January';
}
if($month = 'feb') {
return 'February';
}
if($month = 'mar') {
return 'March';
}
if($month = 'apr') {
return 'April';
}
if($month = 'may') {
return 'May';
}
if($month = 'jun') {
return 'June';
}
if($month = 'jul') {
return 'July';
}
if($month = 'aug') {
return 'August';
}
if($month = 'sep') {
return 'September';
}
if($month = 'oct') {
return 'October';
}
if($month = 'nov') {
return 'November';
}
if($month = 'dec') {
return 'December';
}
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.