짧은 달 이름을 더 긴 상대방으로 변환 [종료]


28

이 도전은 끝났습니다! 축하 Flonk !

나는 확실히 내가 좋은 성적을 얻을 것입니다,하지만 터닝 후 Flonk이기 가 너무 복잡 이유를 이해할 수 없었다 또한, 교수님이 내이었다 믿지 않았다 나의 일 ... 나는 실패 엄마가 페이스 북과 마인 크래프트에서 저를 접지 한 달 동안. 이해가 안 돼요 :(

제출해 주셔서 감사합니다! 여기에 좋은 답변이 있습니다. 공식 우승자는 64 점의 Flonk 입니다 . 상위 5 개는 다음과 같습니다.

  1. Flonk , 64 (Haskell, 효율적인 수학!)
  2. DigitalTrauma , 40 (클라우드, 미래는 지금입니다)
  3. primo , 38 (Python 및 개인적으로 가장 좋아하는 – 매우 전문적인)
  4. Sylwester , 20 (1 월은 스트레칭하지만 라켓!)
  5. ilmale 16 (A 고도로 루아 최적화 알고리즘)

아래의 원래 도전.


도와주세요, 매우 시급합니다 !!! :(

월 이름의 단축 버전을 더 긴 표현 (예 : "Dec"-> "December")으로 대소 문자를 구분하지 않고 변환해야합니다. 지금은 Java를 사용하고 있습니다. 월 이름은 문자열이며 먼저 Date 객체로 변환하지 않습니다. 그러나 모든 언어가 가능합니다.

이것을 수행하는 쉬운 방법이 있습니까 ?? 내가 프로그래밍을 처음 접하는 사람이라면 제발!


이것은 코드 트롤링 인기 콘테스트입니다 (최고의 종류가 있습니다!). 2014 년 4 월 8 일에 가장 많이 투표 된 답변이 우선합니다.


7
"제발 도와주세요, 매우 시급합니다 !!! :("<<< 숙제를 빨리합니까?

13
@yeti 당신이 할 수있는 한 빨리! 수업에 실패하기 전에 서둘러!
Jason C

24
코드 오버 롤링 태그를 사용하여 이러한 질문을 Stackoverflow에서 codegolf.SE로 비밀리에 복사 한 다음 스포일러 태그의 텍스트를 제거한 상태에서 codegolf.SE의 답변을 원래 게시물로 다시 전송하는 기능이 있어야합니다.
daniero의

공식 입장 에 따라 코드 트롤링을 제거하는 중 입니다. 이 질문은 많은 답변으로 매우 높은 평가를 받았으며, 그 중 많은 수가 매우 높은 투표로 선정되었습니다. 여론 조사 에서 50 % 이상의 "삭제"투표를 받았지만, 많은 답변과 투표를 받았다는 점에서 독특합니다.
Doorknob

답변:


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"]

지금 무슨 일이 일어나고 있는지 알 수 있습니다. 필요한 것은 13 ~ 0, 1 ~ 1, 20 ~ 2 등으로 매핑되는 getIndex 함수입니다.

getMonthName shortname = mons !! (getIndex shortname)

운 좋게 Wolfram | Alpha 는 나를 위해 이것을 할 수 있습니다 ! 숫자는 조금 커지지 만 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
아주 좋고 정수는 매우 효율적입니다. 나는 강사가 내 일을 좋아할 것이라고 확신합니다!
Jason C

8
에 관하여 저를 가르치는 일 interpolating polynomial.
primo

3
첫 문장을 읽을 때 웃어야 했어요.
Anaphory

46

배쉬 + 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

[a-zA-Z]대한 대체품으로 작동 하지 [[:alpha:]]않습니까? 3자를 절약 할 수 있습니다. 을 쿼리하여 문자를 몇 개 더 저장할 수 ask.com있지만 신뢰할 수는 없습니다.
Michael

7
이것이 코드 골프 인 경우에 중요한 @Mic
undergroundmonorail

7
@JasonC "클라우드 기반"솔루션입니다. 다른 정당화는 필요하지 않습니다.
Digital Trauma

4
@DigitalTrauma 친애하는 각하, 나는 구름에 대해 들었고 그것은 매우 전문적입니다! 아주 좋아요! 매우 확신합니다! 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에 익숙하지 않은 사람에게는 불분명합니다. 조사를 방해하기 위해 "많은 전문 도구에 사용됨"이라고 덧붙였습니다.
-해싱 함수는 12 개월 사이에 정확하게 구분할 수있을만큼 고유하지만 스왑 문자와 같은 일반적인 오타는 잡을 수 없습니다. - "Febuary"의 철자가 잘못되었습니다. - "이 기능은 매우 중요합니다."
-3 문자보다 긴 문자열은 배열 인덱스 범위를 벗어나면 충돌합니다.


12
잘보세요, 여러분 이것은 올바른 코드 스크롤링 답변입니다! 추신. 임은 확실 나는이와 함께 좋은 성적을 얻을 것이다 및 더 나은 다음 sloooow 작성하는 자바 쉘 스크립트 I의 시도 [여기 이미지에 대한 설명을 입력]?!
제이슨 C

2
"Febuary"의 철자가 잘못되었습니다. -일부 심각한 트롤링 :)
Jaa-c

10
+1 해시 테이블이 비효율적이라고 말하면 정말 비효율적 인 해시 테이블을 구현합니다
James_pic

1
"HashMaps을이되어 정말 느린 배열 비교. 당신은 단지 숫자에 각 약어를 변환해야합니다.이 사용할 수있는 표준 해시 기술이있다 ..."즉 해시 맵을 구현할 정도면. 하 +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"

분명히 여기서 트롤링은 몇 가지 경우에만 작동하므로 쓸모가 없다는 것입니다 :-)


아마도 코드 트롤링 태그 위키에서 "작업은 작동하지만 쓸모없고 OP를 심각하게 좌절시키는 코드를 제공하는 것입니다."코드가 작동하지 않습니다. 여기에 또 다른 공감대가 있습니다.
user12205

@ace 오류가 발생하지 않으며 정답 "12 월"을 반환합니다. 질문은 그것이 다른 달 동안 작동해야한다고 지정하지 않았거나 어떤 긴 이름을 가질 것인지를 말하지 않았으므로 끝에 "ember"를 추가하는 것이 좋은 트롤 대답입니다.
Sylwester

1
"단축 된 월 이름의 버전을 더 긴 표현으로 변환해야합니다 (예 :"Dec "->"December ")"12 월은 모든 예가 아닙니다. 귀하의 프로그램은 모든 월 이름에 대해 작동해야합니다.
user12205

9
@ace 그리고 그렇습니다. "Jan"을 "Janember"로 바꿉니다. OP가 원하는 것을 정확히 보여주는 예를 살펴보십시오. "질문을 잘못 해석하는"과 "질문을 속이는"방법이 모두 대답하는 좋은 방법이기 때문에 코드 트롤링 태그에 대한 답변을 어떻게 공감할 수 있는지 알 수 없습니다.
Sylwester

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

긴 문자열을 올바르게 리턴하면 현재 달의 약어를 확인하십시오. 그렇지 않으면 다시 시도하십시오. 1 개월 후


훌륭한! <<< 에러 : 연결 시간이 초과되었습니다. >>>
joeytwiddle

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의 무작위 사용 g, 다른 사용자는 대체에서 패턴을 반복합니다.
- use re 'eval'실제로는 필요하지 않습니다. 변수 패턴을 원할 때만 사용됩니다. 또한, eval약간의 "압축"을 얻기 위해 사용 합니다.


17
나에게 정상적인 펄처럼 보인다 ...
피터 올슨

1
@PeterOlson 언어가 알고리즘에 맞게 선택되었지만 알고리즘이 작업에 전혀 맞지 않습니다. 동의하지 않습니까? :-)
John Dvorak

10

자바

당신은 당신의 현재 코드가 자바로되어 있다고 말했기 때문에, 나는 당신을 위해 쉽게 만들 것이라고 생각했다.

// 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");
  }
}

Calendar 클래스에는 몇 달이 0부터 시작하여 번호가 매겨지는 재미있는 재미가 JANUARY == 0있습니다. 그러나 이것은 테스트 할 때 코드에 영향을 미치지 않습니다. shortNameToNumber에 의도하지 않은 스위치 오류가 있음을 알 수 있습니다. 이는 매월 0으로 끝나는 것을 의미 JANUARY == 0합니다. 따라서 테스트가 통과됩니다.


1
맙소사, 나는 스위치 선언에서 휴식이 부족하다는 것을 알지 못했습니다. 스위치를 사용한 지 오래되었습니다.
Joe Z.

10

배쉬 + 코어 유틸리티 + 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 문자열을 포함하는 파일 이 현재 디렉토리에 존재 하면 아카이브를 다운로드하지 않습니다 . 이 작동 할 수 있습니다.

  • 이 작업에서는 100MB 파일 (36MB로 압축 된 경우에도)을 다운로드하는 것이 과도합니다. 또한 enwik8 에는 4+ GB Wikipedia 덤프의 첫 100MB가 포함되어 있으므로 특정 작업에 유용한 정보가 포함되어 있지 않을 수 있습니다.

  • paq8hp12로 파일을 압축하면 파일 크기가 16MB로 줄어들지 만 압축 및 압축 해제에는 1 시간이 걸립니다. 실제로이 스크립트가 처음 실행될 때 둘 다 수행합니다.

  • 스크립트는 압축 또는 원시 버전의 enwik8을 삭제하지 않으므로 16MB로 줄이면 훨씬 더 많은 하드 디스크 공간이 소비됩니다.

  • 압축 유틸리티는 64 비트 프로세서에서만 작동합니다.

  • 현재 디렉토리에 다운로드 또는 추출 된 모든 파일을 그대로 둡니다.

  • 스크립트의 가장 까다로운 부분 인 정규식 파이프 괴물을 설명하지 않습니다. 기본적으로 선행 및 후행 숫자가있는 4 바이트와 19 바이트 사이의 모든 문자열을 추출하고 해당 문자열을 발생 횟수별로 정렬하고 짧은 월 이름이 포함 된 문자열을 필터링하고 발생 횟수별로 다시 정렬하고 가장 자주 표시합니다.

  • 위 의 좋은 생각 이었지만 처음 에는 고양이 가 필요 하지 않습니다. 예를 들어이 작업의 속도가 느리면 정규 표현식은 많은 잘못된 긍정을 반환 합니다 (모든 정규식으로 수행 할 수 있음), 첫 번째 정렬 | uniq -c | 정렬 -n | TAC는 그것을 사용 절대적으로 아무것도 달성하지 종류 | sort -rcut 대신 tac 은 시작 부분의 공백 수가 가변적이기 때문에 안정적으로 작동하지 않습니다.

  • 정규식은 확장 POSIX 정규 표현식이므로 BRE 구문을 검색해도 전혀 도움이되지 않습니다.

  • 11 월 대신 11 월 , 8 월 대신 6을 반환 합니다.


1
이것들은 매우 유용한 조언입니다! 확실히 이것은 더 효율적이며 내 강사는 전문가가 OOP 및 OOP에 대해 데이터를 재사용 할 수있게 만들고 더 빠르다고 말합니다.
Jason C

9

파이썬 + 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 ...


나는 언어를 모르기 때문에 여기서 악한 것을 볼 수 없습니다. 나는 당신의 downvotes가 비슷한 위치에있는 다른 사람들로부터 온 것으로 가정합니다. 무슨 일이 일어나고 있으며 왜 악한 지 설명하십시오. 궁금해.
Level River St

그것은의 (N) (AB) 소용 date의 날짜 포맷 기능을 제공합니다. 그리고 date점은 현지화 일치 달 생성, 현지화. -d"a_month_name 1날짜를 명명 된 달의 첫 번째 날짜 (짧은 이름 일 수 있음)로 설정하고 누락 된 연도가 다음 달이되도록 설정합니다. +%B주어진 날짜를 정리하는 형식이며 '달의 긴 이름'을 의미합니다. 모든 tat는 쉘 함수에 싸여 있으며 거기에 BASH 고유의 것이 없기 때문에 SH는 그것을 실행하기에 충분합니다. 기본적으로 date모든 박수를받을 자격이 있습니다. 그리고 나는 codegolf의 downvotes에 관심이 없습니다! : -Þ

나는 이것을 좋아한다! 학대.
ojblass

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";

이것이 굉장한 이유 :

  • 무차별 대항은 항상 그것을하는 가장 남자 다운 방법입니다.
  • 귀하의 편의를 위해, 부분 답변을 알게 되 자마자 부분 답변을 인쇄합니다.
  • 최대한의 보안을위한 맞춤형 해싱 기능.
  • 펄의 내장 연산자 오버로딩 (문자열 증가)을 사용하면이 코드가 네이티브 C 코드만큼 빠릅니다. 얼마나 빨리 실행되는지 보여주는 모든 0을보십시오!

    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
    
  • 알고리즘은 직관적으로 명백하며 독자에게 연습으로 증거를 남기지 만 모든 경우에 작동하는지 확인하기 위해 8 월, -ber 개월 중 하나 및 -uaries 중 하나를 확인하여 아무것도 놓치지 않았다 :

    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 배 정도 (100 만 배) 느립니다. 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

추신-런타임이 훨씬 더 많은 코드가 있었지만 모든 경우에 정답을 지루하게 출력하므로 훨씬 재미가 없습니다.


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

자바, 구글 및 확률

인터넷에서 답변을 쉽게 얻을 수있을 때 여기에있는 많은 솔루션이 "바퀴를 재창조"한다고 실망합니다.

내 프로그램의 출력은 다음과 같습니다.

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"으로 시작하는 임의로 선택된 단어를 반환합니다. 프록시를 사용하지 않으면 "8 월"을 반환합니다.


2

배쉬 + binutils

I tried hard to do the obvious by converting the input to a date object, but failed miserably. Finally I resorted to brute-force approach.

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

Test runs:

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

2

I understand that checking months' names is very hard, and it requires lots of computation and logic thinking. Here's an optimized version of the Buzz-Strahlemann algorythm for checking months' names.

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++;
}

Trolls:

  • This answer;

  • Doesn't handle timezones and will output a warning message;

  • Doesn't accept month as an input, but you need to hardcode it;

  • Even when you hardcode it, it's case-sensitive;

  • What this code tries to do is to get the current month, get the first three letters, and check if it matches with $month. If it does not match, it increments the timestamp by 1 and then retries. This ends up to be EXTREMELY SLOW;

  • This code outputs nothing (except the warning, of course);

  • Comments are very misleading: time() does not load an extended time library, but gets the current timestamp; substr($checkThis,1,4) skips the first letter of the month and gets the following 4 (arch for March, e.g.); The correct form is the one in the comments;

  • Even when a match is found, the code won't exit the loop: in fact, the variable that gets set to true is different.


3
-1: From the code-trolling tag wiki, "The task is to give code that works, but is useless, severely frustrating the OP. " Your code doesn't even work.
user12205

1
Hm? It works and it's useless. Waiting 10 years for an endless loop to finish is not frustrating enough? "It works" means (at least, it means for me), that the code compiles and runs successfully, it doesn't mean that it has to end or give any solution.
Vereos

@ace (I forgot to mention you in the previous comment); What I'm trying to say in that comment is that I'd like to understand better what do you mean, because it is correct from my point of view.
Vereos

Perhaps because arch will never equal Mar?
user12205

So your code cannot convert the month names, therefore it does not work.
user12205

2

Batch

What you're asking for is non-trivial. However I have found the perfect solution for you! How this works is by downloading a highly intricate list of the English language to your hard-disk. The input is then checked against the downloaded list and the final name of the month is given! Genius!

Now, this method has many pros over other methods, some being:

  • You can have any abbreviation of the word! E.g. Jan or Janu for January!
  • "You never know when some Pope or President is going to make us switch to another calendar, and then tons of date parsing/formatting code will instantly become worthless!" This is never a problem with our method!
  • The user is sent confirmation prompts, better safe than sorry!

The Code:

@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!

Trollz

- Batch... - Downloading a list of words, because we can't type out the months manually... - Not using switch case hack - VERY SLOW - converting the text file to lowercase and saving it in another file - run it a second time without deleting the text files created and it will be even slower - Something ticks the script off while converting the dic.txt file to lowercase, this sets echo back on - This spoiler thing has messed up formatting by the way...


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

To make your program respond faster, I have put the months with 31 days earlier in the list. Statistically speaking, given an even distribution of dates, you are more likely to be in one of those months.

I documented each line to impress your boss.

Save this in a file called lookup_month_script.bash and copy-paste the following line to test it:

bash $PWD/lookup_month_script.bash "0ct"

Good luck with your project!


- Doesn't work for January, despite it being listed twice. (We are actually using January as the delimiter for the start and end of the heredoc.)

- Also doesn't work for October. Nobody can see why.

- If the input happens to be empty, returns all 11 months.

- If the script is copy-pasted, the June response will be 42 characters in length.

Minor:

- The shebang is somewhat incorrect, but no warning is given.

- Comments that are comments which say what the line below them is saying.

- Even if the program did respond sooner for the earlier entries, it still wouldn't complete any faster.


1

JavaScript - 209

It does say not to convert to a Date, which is not what's happening here, I'm simply using Date to generate the extension of the short name.

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]];}

Tests Input/Output:

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
I also appear to have trolled Febuary - r :) On purpose, of course...
Matt

Sounds like somebody's got a case of the Wendsdays.
Jason C

5
@Matt Don't you mean "On pupose"?
Justin

Of couse @Quincunx
Matt

1

Java 696 including test input

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

The programming language "Brainf*ck" is a perfect tool for this! It might not be exactly what you were looking for, sure, but it gets the job done flawlessly!

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

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

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

I'm sure your teacher will be proud when you show him this!


Trolling

The programme is, first of all, quite badly written. I've made some loops that cause random error prints and general non-workingness for lack of a better word. It takes a bit of cleanup to get decently working code (primarily in the first two paragraphs of it) which is anyhow useless as it gives long names as "abbreviation + 'uary'" (January, Febuary, Maruary etc.) The programme also includes redundant code for "January" (defined as an exception and coded separately). First answer on Stackexchange, so I hope this meets criteria


1

Java

Dear Computer Scientist Apprentice,

This is quite a difficult task, and I have solved only partially: I guess this is for your thesis work or some research purpose.

Up to now I have only beta version with some minor bugs: sometimes it gives the wrong results, but I'm sure your professor will accept your effort.

file 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;
    }

file 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));
   }

To run it execute:

javac Month.java
javac Era.java
java Era jan

output:

jan: [January]

Remember to set your %JAVAPATH% to the path where your Java compiler is installed!

It just return a random month. Actually I didn't even test it. I guess some imports are missing.


1

Since the OP is using Java, I'll give a Java solution. The idea is simple:

  1. Create a Map from long name to short name.
  2. Generate a random String, map it to the short name.
  3. Use String.equalsIgnoreCase to check whether the short name is same as the input short name ignoring cases. If so, success, exit.
  4. Otherwise go to Step 2.

Here is the source:

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;
            }
        }
    }
}

Trolling

The program needs a fast CPU and your patient. When you learn multi-threading and have a multi-core cpu, you can try make it faster.


1


Thank you for posting this thought provoking and original question. Those of us that post answers on Stack Overflow enjoy the opportunity to help posters, as the purpose of this website is to catalogue all such questions to make the need for text books and self-motivated learning obsolete. Do not be alarmed by your lack of understanding of this particular question, as it is a common type of question asked because of its hidden trick required to solve it effectively. Instructors will commonly ask this question to determine not only your depth of understanding of the language, but also whether you where aware of this common programmer pitfall: character encoding. You will understand more completely after you thoroughly read through the following link, as I know you will: link.

I am sure by now that your professor has described in great detail the importance of code reuse, so as you have read the character encoding link that I provided, you are absolutely coming to the understanding that you will have to make a generic enough class that can handle any language, even if the original question didn't specifically specify this requirement (you may also want to learn about requirement specification, which will help you understand requirements, read through this link: link.

You where very intelligent in suggesting not use the provided Date object, as using the code in the default languages will not allow you to show your true understanding of the language to your professor.

To help you through this difficult question, I have written a Groovy application that will solve you problem, and will undoubtably make more sense than that cryptic java. Don't be alarmed at the use of Groovy for this answer, as Groovy also runs on the JVM just like Java code, so you can easily drop this code into your java class with only a few modifications. I have attached a link to help you through this process, but I wouldn't worry about it until the morning, as it should only take a second (here is the link for later: link. So, just copy the code for now, as I will show plenty of test cases of the code working appropriately, so that you can feel confident in your submission. I definitely understand that you are very very busy eager student, with plenty of obligations on your plate. You are probably aware that contributors here work full time, and are well compensated.

//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
            }
        }
    }
}

Sorry that I didn't leave anything for you to do here, I got carried away answering your thought provoking question. So just copy and paste this response. As you can see from the following runs of the code, here is what it can do:

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

1

Julia

You're going to want to use the power of multiple dispatch here. First we'll define a type of each month. Then we can write simple function definitions for each month type that give the desired answer. This will allows you to use the convenient form of nicename(Jan) without having to bother with those annoying quotation marks. Plus we can define a convenience function to accept strings and converting them to types, reuse all the work we already did to provide a totally new interface.

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")

What language is it?
ugoren

Julia, silly thing to leave out.
gggg

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))

True beauty is in simplicity, which means low memory requirements. Forget those pesky dictionaries and paragraphs of code. This function is so good, it will match short month names using any case. Observe.

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

BONUS:

You can use more than the first 3 characters (e.g. "sept", "febr", etc.)

This will loop through every second from the time you run this code, checking for match at the beginning of the name, so it will take forever to run if the expected result is not your current month. Also numerous style errors.


0

in 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

Here's a little program that does what you requested.

Or actually, 13 of them.

I've written it in C++ because that's what I use at the moment, but it converts pretty easily to Java. Being a dedicated student, I'm sure you can work that bit out yourself.

#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;
}

Oh and I may have overlooked a little offset error in the loop.

I decided to be nice and use std::strings instead of char*s. I'm sure I would have confused you with syntax like char*[] and I would definitely have forgotten to call delete, or done something stupid like call delete instead of delete[].


0

C

Some kind of generic transformation of abbreviations to full words, just adjust data array...

#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';
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.