태그 보관물: answer-chaining

answer-chaining

다른 OEIS 솔루션은 그로부터 시작되어야합니다. 다음 사용자 (userA라고 함)는 색인

13/03/2018 16:45 세계 협정으로, 우승자는 # 345에 응답 하여, Scrooble . 이는 컨테스트가 공식적으로 종료되었지만 규칙을 준수하는 한 자유롭게 답변을 게시하는 것을 의미합니다.

또한, 답변 수의 관점에서 상위 3 명의 답변자에게 간단히 외치십시오.

1. NieDzejkob- 답변 41 개

2. KSmarts- 답변 30 개

3. Hyper Neutrino- 답변 26 개


이것은 OEIS의 시퀀스와 이전 제출 기간을 사용하는 답변 체인 질문입니다.

이 답변 연쇄 질문은 다음과 같은 방식으로 작동합니다.

  • 첫 번째 답변을 게시하겠습니다. 다른 모든 솔루션은 그로부터 시작되어야합니다.
  • 다음 사용자 (userA라고 함)는 색인 번호 (아래 참조)가 내 코드 길이와 동일한 OEIS 시퀀스를 찾습니다.
  • 그런 다음 시퀀스를 사용하여 사용 하지 않는 언어 로 정수를 입력 n으로 사용하고 해당 시퀀스에서 n 번째 숫자를 출력하는 프로그램 을 코딩해야합니다 .
  • 다음으로 솔루션을 게시 한 후 새 사용자 (userB)가 동일한 작업을 반복해야합니다.

n시퀀스의 첫 번째 항은 첫 번째 후 n 번의 항이며, 첫 번째 값은 OEIS 페이지에 주어진 첫 번째 값입니다. 이 질문에서는 이러한 시퀀스에 0 인덱싱 을 사용 합니다. 예를 들어, 함께 A000242 하고 n = 3, 올바른 결과가 될 것이다 (25) .

하나!

이것은 가 아니므로 가장 짧은 코드는 중요하지 않습니다. 그러나 코드 길이는 여전히 영향을 미칩니다. 시퀀스 중복을 방지하려면 바이트 수는 고유해야합니다 . 이것은 여기에 제출 된 다른 프로그램이 귀하의 바이트 와 동일한 길이 일 수 없음을 의미합니다 .

마지막 게시물의 길이에 대한 시퀀스가없는 경우 게시물의 시퀀스가 ​​사용되지 않은 가장 낮은 시퀀스입니다. 이는 사용 된 시퀀스도 고유해야하며 시퀀스가 ​​바이트 수와 같을 수 없음을 의미합니다.

답변이 게시되고 일주일 이상 새 답변이 게시 되지 않으면 마지막 게시 전 (체인을 끊지 않은 사람) 이전 의 답변 이 이깁니다.

입력과 출력

일반 입력 및 출력 규칙이 적용됩니다. 입력은 정수 또는 정수의 문자열 표현이어야하며 출력은 시퀀스에서 올바른 값이어야합니다.

서식

대부분의 질문과 마찬가지로 답변을 다음과 같이 형식화하십시오.

# N. language, length, [sequence](link)

`code`

[next sequence](link)

*anything else*

규칙

  • 답변을 게시 한 후 게시 한 후 1 시간 이상 기다려야합니다.
  • 한 번에 두 번 이상 게시 할 수 없습니다.
  • 시퀀스의 색인 번호는 A부품 뒤의 번호 이며 선행 0이 제거됩니다 (예 : A000040색인 번호의 경우 40).
  • 입력 또는 필수 출력이 언어 숫자 범위를 벗어나지 않는다고 가정 할 수 있지만, 예를 들어 숫자 1 만 사용할 수있는 언어를 선택하여이를 남용하지 마십시오.
  • 제출 기간이 65536자를 초과하는 경우 코드에 액세스 할 수있는 방법 (예 : 페이스트 빈)에 대한 링크를 제공하십시오.
  • n 언어가 경쟁하는 것을 막기 위해 정확도 불일치가 발생하는 것을 막기 위해 1000보다 크거나 시퀀스의 범위를 벗어나지 않습니다.
  • 150 (유효한) 답변마다 언어 사용 횟수가 증가합니다. 따라서 150 개의 솔루션을 게시 한 후에는 모든 언어를 두 번 사용할 수 있습니다 (이전의 모든 답변은 이에 해당됩니다). 예를 들어, 150 답변이 게시되면 Python 3을 두 번 사용할 수 있지만 이미 한 번 사용했기 때문에 300 답변이 게시 될 때까지 한 번만 사용할 수 있습니다.
  • 도움이되고 사용할 다음 순서에 대한 링크를 게시하십시오. 필수는 아니지만 권장 사항입니다.
  • 다른 버전의 언어 (예 : Python 2 및 Python 3)는 다른 언어 입니다. 일반적으로 Try It Online에서 다른 버전을 모두 사용할 수있는 경우 언어가 다르지만 이는 일반적인 규칙 이며 엄격한 대답이 아니라는 점을 명심하십시오 .
  • 금지되어 있지는 않지만 OEIS 페이지에서 코드를 복사하지 말고 실제로 해결해보십시오.
  • 하드 코딩은 시퀀스가 ​​유한 한 경우에만 허용됩니다. 이 메시지를 표시 한 답변 ( # 40 )은 규칙에 대한 예외입니다. 체인 하드 코드의 초기에 몇 가지 답변이 있지만 # 100까지 체인을 삭제하는 것이 좋지 않기 때문에 무시할 수 있습니다.

답변 체인 스 니펫

var QUESTION_ID=133754,OVERRIDE_USER=66833;function shareUrl(i){return"https://codegolf.stackexchange.com/a/"+i}function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getTemplate(s){return jQuery(jQuery("#answer-template").html().replace("{{PLACE}}",s.index+".").replace("{{NAME}}",s.user).replace("{{LANGUAGE}}",s.language).replace("{{SEQUENCE}}",s.sequence).replace("{{SIZE}}",s.size).replace("{{LINK}}",s.link))}function search(l,q){m=jQuery("<tbody id='answers'></tbody>");e.forEach(function(s){if(!q||(l==0&&RegExp('^'+q,'i').exec(s.lang_name))||(l==1&&q===''+s.size)){m.append(jQuery(getTemplate(s)))}});jQuery("#answers").remove();jQuery(".answer-list").append(m)}function sortby(ix){t=document.querySelector('#answers');_els=t.querySelectorAll('tr');els=[];for(var i=0;i<_els.length;i++){els.push(_els[i]);}els.sortBy(function(a){a=a.cells[ix].innerText;return ix==0||ix==4?Number(a):a.toLowerCase()});for(var i=0;i<els.length;i++)t.appendChild(els[i]);}function checkSize(x){if(!x)return jQuery("#size-used").text("");var i=b.indexOf(+x);if(i<0)return jQuery("#size-used").text("Available!");var low=+x,high=+x;while(~b.indexOf(low))low--;while(~b.indexOf(high))high++;jQuery("#size-used").text(("Not available. The nearest are "+low+" and "+high).replace("are 0 and","is"))}function checkLang(x){}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.answer_id;answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return (e.owner.user_id==OVERRIDE_USER?"<span id='question-author'>"+e.owner.display_name+"</span>":e.owner.display_name)}function process(){b=[];c=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);if(a){e.push({user:getAuthorName(s),size:+a[4],language:a[2],lang_name:a[3],index:+a[1],sequence:a[5],link:shareUrl(s.answer_id)});if(b.indexOf(+a[4])>=0&&c.indexOf(+a[4])<0){c.push(+a[4])};b.push(+a[4])}else{jQuery('#weird-answers').append('<a href="'+shareUrl(s.answer_id)+'">This answer</a> is not formatted correctly. <b>Do not trust the information provided by this snippet until this message disappears.</b><br />')}}),e.sortBy(function(e){return e.index});e.forEach(function(e){jQuery("#answers").append(getTemplate(e))});var q="A"+("000000"+e.slice(-1)[0].size).slice(-6);jQuery("#next").html("<a href='http://oeis.org/"+q+"'>"+q+"</a>");c.forEach(function(n){jQuery('#weird-answers').append('The bytecount '+n+' was used more than once!<br />')})}Array.prototype.sortBy=function(f){return this.sort(function(a,b){if(f)a=f(a),b=f(b);return(a>b)-(a<b)})};var ANSWER_FILTER="!*RB.h_b*K(IAWbmRBLe",COMMENT_FILTER="!owfmI7e3fd9oB",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page,e=[];getAnswers();var SCORE_REG=/<h\d>\s*(\d+)\.\s*((?:<a [^>]+>\s*)?((?:[^\n,](?!<\/a>))*[^\s,])(?:<\/a>)?),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*, ((?:<a[^>]+>\s*)?A\d+(?:\s*<\/a>)?)\s*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important;font-family:Roboto,sans-serif}#answer-list,#language-list{padding:10px;/*width:290px*/;float:left;display:flex;flex-wrap:wrap;list-style:none;}table thead{font-weight:700}table td{padding:5px}ul{margin:0px}#board{display:flex;flex-direction:column;}#language-list li{padding:2px 5px;}#langs-tit{margin-bottom:5px}#byte-counts{display:block;margin-left:15px;}#question-author{color:purple;text-shadow: 0 0 15px rgba(128,0,128,0.1);}#label-info{font-weight: normal;font-size: 14px;font-style: italic;color: dimgray;padding-left: 10px;vertical-align: middle; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><p id="weird-answers"></p><p>Currently waiting on <span id="next"></span></p><span>Search by Byte Count: <input id="search" type="number" min=1 oninput="checkSize(this.value);search(1,this.value)" onclick="document.getElementById('search2').value='';!this.value&&search(0,'')"/> <span id="size-used"></span></span><br><span>Search by Language: <input id="search2" oninput="checkLang(this.value);search(0,this.value)" onclick="document.getElementById('search').value='';!this.value&&search(0,'')"/> <span id="language-used"></span></span><h2>Answer chain <span id="label-info">click a label to sort by column</span></h2><table class="answer-list"><thead><tr><td  onclick="sortby(0)">#</td><td onclick="sortby(1)">Author</td><td onclick="sortby(2)">Language</td><td onclick="sortby(3)">Sequence</td><td onclick="sortby(4)">Size</td></tr></thead><tbody id="answers"></tbody></table><table style="display: none"><tbody id="answer-template"><tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SEQUENCE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"><tbody id="language-template"><tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SEQUENCE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>


답변

345. brainfuck , 162 바이트, A000301

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

온라인으로 사용해보십시오!

다음 순서!

이것은 코드 포인트 n(BF 사양에 따라)가 있는 문자를 입력 하고 동일한 방식으로 출력합니다. 숫자를 보려면 @Timwi의 EsotericIDE를 사용하는 것이 좋습니다 .

설명:

+<<,                                  Initialize the tape with the first two Fibonacci numbers. Take loop counter from input.
[                                     n times:
  >>[>]                                 Move to the end of the tape.
  <<[>>+>+<<<-]>>>[<<<+>>>-]            Add fib(n-2)...
  <<[>+>+<<-]>>[<<+>>-]                 and fib(n-1). Store on the end of the tape.
  <[<]<-                                Move back to start of tape. Update loop counter.
]                                     End loop.
>>[>]+<[-]++<                         Delete the extra Fibonacci number and prepare for exponentiation.
[                                     fib(n) times:
  >[>>+>+<<<-]>>>[<<<+>>>-]<<           Copy the base (2) to preserve it.
  [>[>+>+<<-]>>[<<+>>-]<<<-]            Multiply what started as a 1 by the base.
  >[-]>[<<+>>-]<<<<-                    Clean up and update loop counter.
]                                     End loop.
>>too golfy.                          Add some bytes, for all sequences <162 had been used. Print result.

이것은 모든 피보나치 수를 중요한 수까지 저장하기 때문에 바운드 테이프에서 실제로 큰 입력에 실패합니다.

베이스 (2)를 하드 코딩하여 크게 단축 할 수 있지만 골프는 전혀 문제가되지 않습니다.


답변

22. FiM ++ , 982 바이트, A000024

참고 :이 내용을 읽으면 “가장 오래된”항목 으로 정렬 할 수 있습니다 .

Dear PPCG: I solved A000024!

I learned how to party to get a number using the number x and the number y.
Did you know that the number beers was x?
For every number chug from 1 to y,
  beers became beers times x!
That's what I did.
Then you get beers!
That's all about how to party.

Today I learned how to do math to get a number using the number n.
Did you know that the number answer was 0?
For every number x from 1 to n,
  For every number y from 1 to n,
    Did you know that the number tmp1 was how to party using x and 2?
    Did you know that the number tmp2 was how to party using y and 2?
    Did you know that the number max was how to party using 2 and n?
    tmp2 became tmp2 times 10!
    tmp1 became tmp1 plus tmp2!
    If tmp1 is more than max then: answer got one more.
  That's what I did.
That's what I did.
Then you get answer!
That's all about how to do math.

Your faithful student, BlackCap.

PS:  This is the best answer
PPS: This really is the best answer

다음 순서


답변

1. 삼각형 , 10 바이트, A000217

$\:_%i/2*<

온라인으로 사용해보십시오!

다음 순서

작동 원리

이 삼각형으로 코드 형식

   $
  \ :
 _ % i
/ 2 * <

IP가 시작하여 $동남아시아 (SE, heh)에서 이동하면 다음과 같이 작동합니다.

$            Take a numerical input (n);     STACK = [n]
 :           Duplicate it;                   STACK = [n, n]
  i          Increment the ToS;              STACK = [n, n+1]
   <         Set IP to W;                    STACK = [n, n+1]
    *        Multiply ToS and 2ndTos;        STACK = [n(n+1)]
     2       Push 2;                         STACK = [n(n+1), 2]
      /      Set IP to NE;                   STACK = [n(n+1), 2]
       _     Divide ToS by 2ndToS;           STACK = [n(n+1)/2]
        \    Set IP to SE (heh);             STACK = [n(n+1)/2]
         %   Output ToS as number;           STACK = [n(n+1)/2]
          *  Multiply ToS by 2ndToS (no op); STACK = [n(n+1)/2]

답변

73. 별이 빛나는 , 363 바이트, A000252

, +      + *     '.     `
 + + + +  *  *  *  +
 +`      +*       +    `
 + +   +  + +   + *  '
   +   '  ####`  + +   +
 + +    ####  +*   +    *
    '  #####  +      + '
  `    ######+  + +   +
+ +   + #########   * '
 +   +  + #####+ +      +
*  +      + * +  *  *   +
   +  *  + + + +  *  *
+   +  +   *   + `  + +
 +  + +   + *'    +    +.

온라인으로 사용해보십시오!

다음 순서

a(n) = n^4 * product p^(-3)(p^2 - 1)*(p - 1)OEIS에서 “제품이 n을 나누는 모든 소수 p 위에있는 “공식을 사용합니다 .

달은 엉망이지만, 이건 코드 골프가 아닙니다.


답변

97. Python 3 (PyPy) , 1772 바이트, A000236

우선, Dr. Max Alekseyev에게 감사합니다. 이 문제를 이해하기 위해 이메일로 연락 할 수있어서 매우 행운입니다. 그의 Math.SE 답변은 여기 에 많은 도움이되었습니다. 저를 도와 준 밀 마법사에게 감사드립니다. 🙂

plist = []

def primes(maximal = -1): # Semi-efficient prime number generator with caching up to a certain max.
	index = plist and plist[-1] or 2
	for prime in plist:
		if prime <= maximal or maximal == -1: yield prime
		else: break
	while index <= maximal or maximal == -1:
		composite = False
		for prime in plist:
			if index % prime == 0:
				composite = True
				break
		if not composite:
			yield index
			plist.append(index)
		index += 1

def modinv(num, mod): # Multiplicative inverse with a modulus
	index = 1
	while num * index % mod != 1: index += 1
	return index

def moddiv(num, dnm, mod):
	return num * modinv(dnm, mod) % mod

def isPowerResidue(num, exp, mod):
	for base in range(mod):
		if pow(base, exp, mod) == num:
			return base
	return False

def compute(power, prime):
	for num in range(2, prime):
		if isPowerResidue(moddiv(num - 1, num, prime), power, prime):
			return num - 1
	return -1

# file = open('output.txt', 'w')

def output(string):
	print(string)
	# file.write(str(string) + '\n')

def compPrimes(power, count):
	maximum = 0
	index = 0
	for prime in getValidPrimes(power, count):
		result = compute(power, prime)
		if result > maximum: maximum = result
		index += 1
		# output('Computed %d / %d = %d%% [result = %d, prime = %d]' % (index, count, (100 * index) // count, result, prime))
	return maximum

def isValidPrime(power, prime):
	return (prime - 1) % power == 0

def getValidPrimes(power, count):
	collected = []
	for prime in primes():
		if isValidPrime(power, prime):
			collected.append(prime)
		if len(collected) >= count:
			return collected
		# output('Collected %d / %d = %d%% [%d]' % (len(collected), count, (100 * len(collected)) // count, prime))

power = int(input()) + 2

output(compPrimes(power, 100))

# file.close()

온라인으로 사용해보십시오!

잘못된 결과가 나오면 100을 더 크게 늘리십시오. 10000은 4에서 작동한다고 생각하지만 확인하기 위해 밤새 내 컴퓨터를 계속 실행합니다. 완료하는 데 몇 시간이 걸릴 수 있습니다.

(PyPy) 부분은 파이썬을 다시 사용할 수 있도록하기위한 것입니다. 나는 정말로 다른 많은 언어를 모른다. 나는 이것을 Java로 포팅하려고 시도하지 않고 제 시간에 끝나지 않을 위험이있다.

다음 순서 (또한 더 이상 미친 수학 작업을 수행하지 마십시오. 파이썬 버전이 남아 있지 않으므로 다른 사람 이이 도전 과제를 저장해야합니다 🙂


답변

107. TrumpScript , 1589 바이트, A000047

My cat hears everything really well
because with me every cat is a safe cat
Everybody knows that one is 1000001 minus 1000000
but only most of you that two is, one plus one;
As always nothing is, one minus one;
My dog is one year old.
I promise you that as long as you vote on me, nothing will be less cool than a cat;:
Much dog is, dog times two;
Dead cat is, cat minus one;!
I will make dog feel good, food for dog plus one;
Roads can be made using different things. Asphalt is one of them.
As long as Hillary jailed, I love asphalt less than my dog;:
Roads are, always made using asphalt plus one of other things;
I promise my roadways are, two times asphalt than you want;
My roadways are great, always roadways plus one;
Vladimir is nothing more than my friend.
Name of Putin is Vladimir.
As long as, Putin eat less roadways;:
China is nothing interesting.
We all know people speaking Chinese are from China.
As long as, Chinese makes less roads;:
I will make economy, for Putin - Chinese will love me;
If it will mean, economy is asphalt in Russia?;:
I will make cat feel good, cat plus one dollar on food;
Make Vladimir roadways to help Russia economy.
Never make china roads!
I show you how great China is, China plus one; You can add numbers to China.
Like Chinese is, China times China makes sense;
Like Chinese is, two times Chinese letter;!
Make Vladimir happy, Vladimir plus one million dollars;
I also show you how great Putin is, Vladimir times Vladimir; You can do number stuff to Putin too!
I will make asphalt roads a lot!
Everybody say cat. You did it? America is great.

온라인으로 사용해보십시오!

TrumpScript에서 처음 프로그래밍 할 때 바퀴를 몇 번 다시 발명했을 수 있습니다-4 줄은 2 ^ n을 계산하는 데 전념합니다. 트럼프가 말할 수있는 것처럼 보이게하려고했습니다. 보너스로 여기에 내가 모든 것을 올바르게하고 있는지 확인하기 위해 작성한 Python 스크립트가 있습니다. 위의 프로그램과 약간의 차이가 있지만 대부분은 직접적으로 동일합니다.

cat = int(input())
dog = 2 ** cat + 1
asphalt = 1
cat = 0
while asphalt < dog:
    roads = asphalt + 1
    roadways = 2 * asphalt + 1
    vladimir = 0
    putin = vladimir
    while putin < roadways:
        china = 0
        chinese = china
        while chinese < roads:
            chair = putin - chinese
            if chair == asphalt:
                cat += 1
                vladimir = roadways
                china = roads
            china += 1
            chinese = 2 * china * china
        vladimir += 1
        putin = vladimir * vladimir
    asphalt = roads
print(cat)

다음 순서!


답변

30. 파이썬 1 , 1112 바이트, A000046

def rotations(array):
	rotations = []
	for divider_index in range(len(array)):
		rotations.append(array[divider_index:] + array[:divider_index])
	return rotations

def next(array):
	for index in range(len(array) - 1, -1, -1):
		array[index] = 1 - array[index]
		if array[index]: break
	return array

def reverse(array):
	reversed = []
	for index in range(len(array) - 1, -1, -1):
		reversed.append(array[index])
	return reversed

def primitive(array):
	for index in range(1, len(array)):
		if array == array[:index] * (len(array) / index): return 1
	return 0

def necklaces(size):
	previous_necklaces = []
	array = [0] * size
	necklaces = 0
	for iteration in range(2 ** size):
		if not primitive(array) and array not in previous_necklaces:
			necklaces = necklaces + 1
			for rotation in rotations(array):
				complement = []
				for element in rotation:
					complement.append(1 - element)
				previous_necklaces.append(rotation)
				previous_necklaces.append(complement)
				previous_necklaces.append(reverse(rotation))
				previous_necklaces.append(reverse(complement))
		array = next(array)
	return necklaces

온라인으로 사용해보십시오!

이 골프를 귀찮게하지 않습니다. 이 사이트에서 가장 긴 Python 답변이 아닙니다!

다음 순서