ウィキペディア:哲学!


26

多くのオタクがウィキペディアのほとんどのページ(95%と思う)を知っている可能性があるため、最終的には次のような哲学につながります。

別の通常の記事への最初の非イタリックまたはカッコ内のリンクをクリックします(つまり、File:やSpecial:ではなく、Wikipedia:のようなものでも構いません)。

スクリプトは以下を行う必要があります。

  • 入力として最初のページを取る
  • 到達する各記事の名前を印刷する
  • そして、哲学にたどり着くまでにどれだけの記事を印刷したか、そうでない場合は印刷してください。

1000ポイントから開始し、コード内の各キャラクターにつき1ポイントを失います。

ループ記事の検出と停止:+50

ループする記事を検出し、ユーザーが記事の次のリンクに移動するかどうかを要求する:+170

コマンドライン引数などとして、以前のチェックでデフォルトを許可:+140

最高スコアが勝ちます。


7
+1、大きな挑戦!この括弧の検出は困難である:P
ドアノブ

1
これはもっと良い定義を使用できると感じていますが、まだどのように正確に定義されているかわかりません。
イッツィ14年

3
入力した文字ごとに1ポイントを失います。うーん 素晴らしい、私はそれを得た、私はちょうどキャラクターをコピー&ペーストします!ポイントは失われません!
ジャスティン14年

5
回答が既に投稿された後にルールを変更しないでください。それは非常に失礼であり、一般的にここのコミュニティで眉をひそめています...
Doorknob

回答:


8

ルビー、1000 - 303 299 337から50 373から170 382から170 - 140 379 - 170から140文字= 697 701 713 797 928 931

多くの改善が行われると確信しています。

(これにはノコギリが必要です)

require'open-uri'
require'nokogiri'
x="/wiki/"+gets.chomp
r=[n=i=0]
until x=~/\/Philosophy/
d=Nokogiri.HTML open"http://en.wikipedia.org#{x}"
x=d.css('p a').select{|a|t=a.xpath('preceding::text()').map(&:text)*'';t.count('(')==t.count(')')&&a.attr('href')=~/^.wiki[^:]+$/}[i].attr'href'
i=0
puts r.index(x)?"#{$><<'i=';i=($*[0]||gets).to_i;''}": r.push(x)[-1][6..-1]
n+=1
end
p n

実行例:

c:\a\ruby>wikipedia_crawl_philosophy
Latin (note: this is my input)
Classical_antiquity
History
Umbrella_term
Terminology
Word
Linguistics
Science
Knowledge
Fact
Proof_(truth)
Argument
Logic
Reasoning
Consciousness
Quality_(philosophy)
Property_(philosophy)
Modern_philosophy
Philosophy
18

別のリンクに移動する必要があるサンプル1

c:\a\ruby>wikipedia_crawl_philosophy
Snow
Precipitation_(meteorology)
Meteorology
Atmospheric_physics
Synoptic_scale_meteorology
i=2 // I put the 0-indexed number of the link I wanted to go to (so, the third link)

Weather
Atmosphere
Gas
State_of_matter#The_four_fundamental_states
Physics
Natural_science
Sciences
Knowledge
Fact
Proof_(truth)
Argument
Logic
Reasoning
Consciousness
Quality_(philosophy)
Property_(philosophy)
Modern_philosophy
Philosophy
25

私が使用したトリック:

  • セレクタを使用して、p aイタリック以外のリンクのみを取得しました。これは、実際の記事内の斜体以外のすべてのリンクが常にウィキペディアの段落要素にあるためです。

うーん...たぶん私は...どんなしかし、言語が付属してlibrarysを禁止すべきである
AlphaModder

@ user1825860実際には、言語に付属するライブラリではありません。それは宝石です。回答を編集しました。しかし、本当に、あなたはこのすでに難しい挑戦を受けて、HTML解析ライブラリも使わないように強制したいですか?:P
ドアノブ

私はそれを拒否していませんが、ポイントを失います:P
AlphaModder 14年

あなたはそれに応じて最初の投稿や編集を再読み込みする必要がありますP
AlphaModder

2
@ user1825860回答が既に投稿された後は、ルールを変更しないでください。それは非常に失礼です...
ドアノブ

5

「BASH」–(間違えない場合:1000-397 + 170 + 140 = 913ポイント)
「BASH」 -(間違えない場合:1000-386 + 170 + 140 = 924ポイント)

「BASH」 –(間違っていない場合:1000-381 + 170 + 140 = 929ポイント)

BASHは、* nixシェルで使用されるツールを組み合わせたものですが、bashスクリプトにラップされているため、意図的に引用されています。

編集1:

  • これhttp://curlデフォルトとして削除しました。
  • 変更href=へのアンカーの試合f=としては<a>、他の持っていない、通常で終わる属性をf。(カスタムタグの可能性があります。今まで見たことがない。)
  • 終了メッセージをの!Phil代わりにに設定しNoPhilます。一つは、また、例えば言うことができるよう、この1ビット風変わりで!0N!Pまたは類似しました。
  • 癖2:-son curlを削除してさらに3バイト減らすことができますが、それは面倒な出力になります。それが問題かどうかわかりません。
  • このページのヘルプを更新しました。

癖を使用すると、コードは379バイト、931ポイントになります。

また、6バイトを追加する(6ポイントを減算する)ことにより、一致する(できれば)ナビゲーションボックスの@plannapusの使用を実装できます。(p|ul).*?<(\1)

編集2:

カウンターの${#c[@]}代わりに分離度を印刷するために使用します$i

癖を使用すると、コードは374バイト、936ポイントになります。


クトゥルフを呼び出して、正規表現+ bash / shell / * nixソリューションを探します。

盗まれた:

実装済み:

  • ループを検出し、次のリンクを取得するかどうかを尋ねます。
  • オプションで、複製として次のリンクをオプションとして選択します。

要件:

  • bash v。?
  • grep-P(PCRE)のサポート。
  • sed
  • curl
  • cut

使用法:

script PATH [OPTIONS]

Print separation of article from ``PATH'' to ``Philosophy'' on Wikipedia.
Degrees of separation, if found, is printed as last line. 
If not found last line yields ``!Phil''.

PATH    
     Absolute path to starting article, e.g: /wiki/Word 
OPTIONS
     y   Automatically select next link if already visited.
     n   (Or other) Quit if next link already visited.
BUGS
     1. On previous visit; "next link" is not checked. Thus if next link
     has already been visited we get eternal loop. Not sure if this
     disqualify +170 points.
     2. Sure there are.

インラインコード。ファイルにコピーします。chmod +x filename./script /wiki/…bashシェルから実行します。

u=($1);c=($1);while ! [[ "$u" =~ /Philosophy$ ]];do echo "$u";u=($(curl -s "en.wikipedia.org$u"|tr '\n' ' '|grep -Po '<p>.*?</p>'|sed 's/>[^<]*([^)]*)//g'|grep -o '<a [^>]*f="/wiki/[^":]*"'|cut -d\" -f2));for x in "${c[@]}";do if [ "$x" = "$u" ];then [ $2 ] &&s=$2||read -p "${u[0]}?" s;[ $s = y ] &&u[0]=${u[1]}||{ echo "!Phil";exit;} fi;done;c=("${c[@]}" "$u");done;echo ${#c[@]};

拡張および説明されたコード:

u=($1); # Array of paths.
c=($1); # Array of visited paths.
# While $u != /Philosophy, ugly trick is to use $u instead of ${u[0]}.
while ! [[ "$u" =~ /Philosophy$ ]];do   
        echo "$u";      # Print current page.
        # curl   : prints retreived page to stdout. "-s" could be skipped.
        # tr     : replace all newline with space. This is a ®sanity thing when it comes to 
        #          twidling with html using regex.
        # grep 1 : match <p> tags. Using -P's ungreedy *?.
        # sed    : remove all occurences of "(" something ")".
        # grep 2 : match links where "href" attribute starts with /wiki/ and is not e.g. File:
        # cut    : match actual href value.
        # Result is added to array ``u''.
        u=($(curl -s "en.wikipedia.org$u" |
                tr '\n' ' ' | 
                grep -Po '<p>.*?</p>' | 
                sed 's/>[^<]*([^)]*)//g' | 
                grep -o '<a [^>]*f="/wiki/[^":]*"' | 
                cut -d\" -f2));

        # For previously visited pages as x.
        for x in "${c[@]}"; do 
                # If x equals to first page ...
                if [ "$x" = "$u" ]; then        
                        # Use option or ask.
                        [ $2 ] && s=$2 || read -p "${u[0]}?" s; 
                        # If response is "y" use next link, else exit with status.
                        [ $s = y ] && u[0]=${u[1]} || { 
                                echo "!Phil"; 
                                exit;
                        } 
                fi;
        done;
        # Append current link to "visited"
        c=("${c[@]}" "$u"); 
done;
# Print number of visited pages.
echo ${#c[@]}

くそー、あなたは私を一点倒した!:P解決策をもっとゴルフしなければならない
Doorknob

ええ;)、しかしこれが有効なコードかどうかはわかりません。この方法でツールを使用します。
ルニウム14年

5

JavaScript 726(444文字[556] + 170)

これはブックマークレットとして有効ではないかもしれないことを感謝していますが、とにかくそれをいじることを楽しんでいます。

使用法:開始するページに移動し、コンソールで次を実行します。

(function(a){c=0,o="";$(u="html")[u](f=$('<iframe src="'+location+'?">').on("load",function(){$=f.contentWindow.$;p=f.contentDocument.title[s="split"](" - ")[0];c++;p=="Philosophy"?document.write("<pre>"+o+p+"\n"+c):(i=RegExp("^"+p+"$","m").test(o)?a||confirm("Loop, try next?")?2:0:1)&&(f.src=$("p>a").filter(function(){return(t=$(this).parent()[u]()[s](this.outerHTML)[0])[s]("(").length==t[s](")").length})[--i].href);o+=p+"\n"})[0])})(true)

JavaScriptの場合、出力は次のとおりです。

JavaScript
Interpreter (computing)
Computer science
Science
Knowledge
Fact
Proof (truth)
Argument
Logic
Reason
Consciousness
Quality (philosophy)
Property (philosophy)
Modern philosophy
Philosophy
15

このソリューションでは、検出されているループの次のリンクにジャンプすることを前提としていますがtrue、最後に変更するとfalse代わりに確認ボックスがポップアップします(いらいらします...)二次ボーナスかどうか。そうではないと思います。

インデント:

(function(l){
    c=0,o='';
    $(u='html')[u](f=$('<iframe src="'+location+'?">').on('load',function(){ // Firefox needs the ? to properly load the frame
        $=f.contentWindow.$; // reference repeated calls as strings to save more bytes
        p=f.contentDocument.title[s='split'](' - ')[0]; // get the title

        c++;
        p=='Philosophy'?
            document.write('<pre>'+o+p+'\n'+c): // pre for nice formatting
            (i=RegExp('^'+p+'$','m').test(o)?
                l||confirm('Loop, try next?')?
                    2: // desired index + 1 so we can use as a boolean
                    0
                :
                1)&&
            (f.src=$('p>a').filter(function(){
                return (t=$(this).parent()[u]()[s](this.outerHTML)[0])[s]('(').length == t[s](')').length // shorter, but still not overly happy with this...
            })[--i].href);
            o+=p+'\n' // update output
    })[0])
})(true) // change this to show confirm box when loop detected

だから、私は元々かっこ内のアイテムを無視する部分を逃し、それがはるかに冗長になったので、そのフィルター機能を低下させる(またはうまくいけばそれを完全に置き換える)ことを望んでいます。

ChromeとFirefoxの両方で動作(Firefox 26でテスト済み)


2
素晴らしい見えますが、Firefoxの20で失敗した
boothby

ああ!Chromeのみをテストしました。調べてみます!
ドムヘイスティングス14年

@boothby Firefoxで動作するはずです...それでも私が選択しているリンクで動作したいです!
ドムヘイスティングス14年

5

C#-813文字

スコア:1000-813 + 50 + 170 + 140 = 547 :(

外部ライブラリはありません。ループ検出

最初の引数はソース記事で、2番目はターゲット記事です。

ゴルフバージョン:

class Program
{
    static void Main(string[] a)
    {
        Func<XmlDocument,IList<string>> G=delegate(XmlDocument xd){return xd.SelectNodes("//p//a[starts-with(@href,'/wiki/') and not(contains(@href,':'))]").Cast<XmlNode>().Select(n=>n.Attributes["href"].InnerText).ToList();};Action<string> W=delegate(string s){Console.WriteLine(s);};var h=new HashSet<string>();var c=new WebClient();var x=new XmlDocument();var t=c.DownloadString(@"http://wikipedia.org/wiki/"+a[0]);int i=0,C=0;
    GO:
        x.LoadXml(t);var ns=G(x);
    COL:
        var f=ns[i];if(f.Equals("/wiki/"+a[1],StringComparison.OrdinalIgnoreCase)){goto END;}if(h.Contains(f)){W("loop: "+f);i++;goto COL;}else{h.Add(f);i=0;C++;}W(f);t=c.DownloadString(@"http://wikipedia.org"+f);goto GO;
    END:
        W("Found in "+C);
    }
}

わかりやすいバージョン:

class Program
{
    // arg[0] source article. arg[1] target article
    static void Main(string[] arg)
    {
        Func<XmlDocument, IList<string>> G = delegate(XmlDocument xd)
        {
            return xd.SelectNodes("//p//a[starts-with(@href,'/wiki/') and not(contains(@href,':'))]").Cast<XmlNode>().Select(n => n.Attributes["href"].InnerText).ToList();
        };
        Action<string> W = delegate(string s) { Console.WriteLine(s); };
        var h = new HashSet<string>(); var c = new WebClient(); var x = new XmlDocument();
        var allText = c.DownloadString(@"http://wikipedia.org/wiki/" + arg[0]);
        int i = 0; int C = 0;
    GO:
        x.LoadXml(allText);
        var ns = G(x);
    COL:
        var f = ns[i];
        if (f.Equals("/wiki/" + arg[1], StringComparison.OrdinalIgnoreCase))
        {
            goto END;
        }
        if (h.Contains(f))
        {
            W("loop: " + f); i++; goto COL;
        }
        else
        {
            h.Add(f); i = 0; C++;
        }
        W(f);
        allText = c.DownloadString(@"http://wikipedia.org" + f);
        goto GO;
    END:
        W("Found in " + C);
    }
}

「空」から「哲学」への実行例:

C:\>wiki.exe Sky Philosophy

/wiki/Earth
/wiki/Geometric_albedo
/wiki/Phase_angle_(astronomy)
/wiki/Observational_astronomy
/wiki/Astronomy
/wiki/Natural_science
/wiki/Sciences
/wiki/Latin_language
/wiki/Classical_antiquity
/wiki/History
/wiki/Ancient_Greek
/wiki/Greek_language
/wiki/Modern_Greek
loop: /wiki/Greek_language
/wiki/Colloquialism
/wiki/Word
/wiki/Linguistics
/wiki/Science
loop: /wiki/Latin_language
/wiki/Knowledge
/wiki/Fact
/wiki/Latin
loop: /wiki/Classical_antiquity
/wiki/Italic_languages
/wiki/Indo-European_languages
/wiki/Language_family
/wiki/Language
/wiki/Human
/wiki/Extinct
/wiki/Biology
loop: /wiki/Natural_science
/wiki/Life
loop: /wiki/Earth
/wiki/Physical_body
/wiki/Physics
loop: /wiki/Greek_language
loop: /wiki/Natural_science
/wiki/Matter
/wiki/Rest_mass
/wiki/Center_of_momentum_frame
loop: /wiki/Physics
/wiki/Inertial_frame
loop: /wiki/Physics
/wiki/Frame_of_reference
loop: /wiki/Physics
/wiki/Coordinate_system
/wiki/Geometry
loop: /wiki/Ancient_Greek
/wiki/Mathematics
/wiki/Quantity
/wiki/Property_(philosophy)
/wiki/Modern_philosophy
Found in 41

C:\>

5

Scala(294文字=> 1000-294 + 140 = 846ポイント)

既に使用されている場合、自動的に次のリンクを取得する更新されたソリューション。140ボーナスポイントをありがとう。

ロジック: 「:」が含まれていない最初の「/ wiki」リンクを選択します(「File:」リンクは無視されます)。毎回、カウント+ 1を返す再帰でリンスして繰り返します。プログラムが無限ループに陥らないように、以前のすべての出力のリストを手元に置いておきます。

正規表現:正規表現には2つの形式があります。

  • "<p>.*?\"/wiki/([^:]*?)\".*?/p>"<p>タグ内のリンクを見つけます
  • "p>.*?/wiki/([^:]*?)\""これはもう少し実験的なタグですが、動作することが証明されていますが、右側の情報バーからリンクを選択することがあるため、異なる結果を提供します。これらは定期的な記事ですので、まだ有効だと思います。そうでないと判断された場合、OP(または他の誰か)が私にコメントを残すことができ、より良い正規表現にソリューションを更新できます。

動作しないテストケースが見つかるか、OPがサイドバーからリンクを選択することを許可しないまで、2番目の正規表現を使用します(私の意見では、情報バーはまだ実際の記事自体、より多くの要約)。


縮小ソース:

object W extends App{print(x(Seq(args(0))));def x(s:Seq[Any]):Int={val? =s.last;println(?);?match{case "Philosophy"=>1;case _=>x(s:+"p>.*?/wiki/([^:]*?)\".*?/p>".r.findAllMatchIn(io.Source.fromURL("http://en.wikipedia.org/wiki/"+ ?).getLines.mkString).map(_ group 1).filter(!s.contains(_)).next)+1}}}

読み取り可能なソース:

object W extends App {
  print(x(Seq(args(0))))

  def x(s: Seq[Any]): Int = {
    val ? = s.last
    println(?)
    ? match {
      case "Philosophy" => 1
      case _ => x(s :+ "p>.*?/wiki/([^:]*?)\"".r.findAllMatchIn(io.Source.fromURL("http://en.wikipedia.org/wiki/" + ?).getLines.mkString).map(_ group 1).filter(!s.contains(_)).next) + 1
    }
  }
}

サンプル出力:

入力

Space_toilet

出力

Space_toilet
Weightlessness
G-force
Weight
Force
SI_unit
French_language
Second_language
Language_acquisition
Word
Linguistics
Science
Latin_language
Pontifical_Academy_for_Latin
Pope_Benedict_XVI
Pope_Benedict_(disambiguation)
Regnal_name#Catholic_Church
Monarch
State_(polity)
Community
Commutative_property
Mathematics
Quantity
Property_(philosophy)
Modern_philosophy
Philosophy
26

1
Scalaはメインのオブジェクトやメソッドを必要としません。インタープリターで「scala <filename> [args ..]」として実行できます。を使用args(0)して、最初の引数を取得しobjectmain定義を削除し:Intます。これも削除できると思います。pastebin.com/YqywKcG8
KChaloux

を削除できないことが判明しました: Int。あなたが再帰呼び出しを行っていることに気づかなかった。また、pastebinは古いReadable Sourceから取得されましたが、同じ概念が適用されます。
KChaloux 14年

mainメソッドを削除してみます。ええ、再帰呼び出しにより、:Intそこに追加されました。また、本日、私が持っている333 charソリューションの読み取り可能な形式を追加します。@KChaloux
javatarz

1
前述のようにobject Q extends App { ... }、scalacでコンパイルするのではなく、インタープリターでコードを実行する場合、への参照はまったく不要です。ただ走るscala <filename> [args..]
KChaloux 14年

4

R、379文字。1000-379 + 170 = 791ポイント

ループが検出された場合の処理​​方法をユーザーに尋ねるバージョン

library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste0(w,W,A[n]);d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),`[`,'href'),v=T),"/"),`[`,3);B=d[-grep(":",d)];n=n+1;if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)

インデントとコメント付き:

library(XML) #Uses package XML
w="http://en.wikipedia.org"
W="/wiki/"
n=1
A=c(scan(,"")) #Stdin + makes it a vector so we can store each iteration
while(A[n]!="Philosophy"){
    a=paste0(w,W,A[n])
    d=sapply(strsplit(grep(W,sapply( #The heart of the program
             xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),
             `[`,'href'),v=T),"/"),`[`,3)
    B=d[-grep(":",d)] #get rid of Templates, Files ,etc...
    n=n+1
    #Ask user if should proceed when loop encountered 
    #(any answer other than "n" is considered agreement):
    if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break
    A[n]=head(B[!B%in%A],1) #Take the first link that is not redundant
    cat(A[n],"\n")
    }
cat(n-1)

実行例:

> library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste(w,W,A[n],sep="");d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),`[`,'href'),v=T),"/"),`[`,3);B=d[-grep(":",d)];n=n+1;if(B[1]%in%A)if(readline("Loop!2nd link?")=="n")break;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)
1: Extended_ASCII
2: 
Read 1 item
Eight-bit 
Computer_architecture 
Computer_science 
Science 
Logic 
List_of_aestheticians 
Art 
Human_behavior 
Behavior 
Organism 
Biology 
Loop!2nd link?y
Mathematics 
Quantity 
Property_(philosophy) 
Modern_philosophy 
Philosophy 
16

R、325文字。??? ポイント

デフォルトでは、最初に非冗長リンク(つまり、非ループ)を使用するバージョン。

library(XML);w="http://en.wikipedia.org";W="/wiki/";n=1;A=c(scan(,""));while(A[n]!="Philosophy"){a=paste0(w,W,A[n]);d=sapply(strsplit(grep(W,sapply(xpathApply(xmlParse(readLines(a)),"//p/a[@href]|//ul/li/a[@href]",xmlAttrs),`[`,'href'),v=T),"/"),`[`,3);B=d[-grep(":",d)];n=n+1;A[n]=head(B[!B%in%A],1);cat(A[n],"\n")};cat(n-1)
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.