SlideShare ist ein Scribd-Unternehmen logo
1 von 15
How I won a golf set from reg.ru
at YAPC::EU 2013
Brian McCauley
(nobull)
Discussion at http://perlmonks.org/?node_id=1049290
Who am I
• Just Another Perl Hacker ™
• I am the one Matt Trout warned you about
• Don’t to much Perl in my $dayjob
• Still come to YAPC::EU for the community
Perl Golf
• Solve a defined problem
• Minimal number of characters
• No points for best practice
• No points for runtime efficiency
• No points for originality
• No points for obfuscation
The reg.ru challenge
• Based on the ancient game of Go
• 2 players
• Square grid
• Place black/white stones
• Capture opponent’s stones by surrounding
The reg.ru challenge
• 9 x 9 game-state on STDIN
• Enumerate capturing moves on STDOUT
1 2 3 4 5 6 7 8 9
1 ¶
2 x ¶
3 b w b ¶
4 b w w b ¶
5 b b ¶
6 ¶
7 x x ¶
8 w b b w ¶
9 w b b w w ¶
2 4¶
7 9¶
My solution
• 205 characters (excluding #!perl)
#!perl
$b=++$/x11 .<>;for$i(9..99){if(($x=$b)=~s/^(.{$i}) /$1x/s){while($x=~/w/g){$_="$`W$'";1while
s/w((?<=W.{10})|(?<=W.)|(?=.{9}W|W))/W/s;/W((?<= .{10})|(?<= .)|(?=.{9} | ))/s||$i=~/./+(print"$& $'n")+last}}}
$b=++$/x11 .<>;$b = ++$/ x 11 . <>;
Read in the board
• Set $/ to a character that won’t appear
• Slurp STDIN including “n”
– (1,9) not adjacent (2,1) etc.
– Each row 10 characters
• Padding so cell (3,5) is in linear position 35 etc.
$/='';
$b = '11111111111' . <STDIN>;
Consider each vacant space
• Consider, in turn, a copy board with “x” in
each empty cell (“ ”)
• Record location of “x” in $i
for $i ( 9 .. 99 ) {
if( ($x = $b) =~ s/^(.{$i}) /$1x/s ) {
# Do stuff with $x
}
}
for my $i ( 11 .. 99 ) {
if( ( my $x = $b) =~ s/^(.{$i}) /$1x/s ) {
# Do stuff with $x
}
}
Consider each white stone
• Consider, in turn, a copy board with one “w”
highlighted as “W”
• Don’t need index this time
while( $x =~ /w/g ) {
$_ = "$`W$'";
# Do stuff with $_
}
}
Flood fill white stones
• Replace “w” adjacent “W” with “W”
• Repeat until no more
1 while
s/w((?<=W.{10})|(?<=W.)|(?=.{9}W|W))/W/s;
while ( # Repeat until fails
s/
w # Find 'w'
((?<=W.{10}) | # with a 'W' above
(?<=W.) | # or a 'W' to left
(?=W) | # or a 'W' to right
(?=.{9}W) ) # or a 'W' below
/W/xgs # Replace with 'W'
) { }
See if we’ve captured
• Find highlighted white stone (“W”) adjacent
an empty cell (“ ”).
• If none then we’ve captured some stones.
/W((?<= .{10})|(?<= .)|(?=.{9} | ))/s ||
print "Hoorah! We captured some tiles";
unless(/W((?<= .{10})|(?<= .)|(?=.{9} | ))/) {
print "Hoorah! We captured some tiles";
}
Output the move
• Print the row and column derived from $i .
• Padding means these are div and mod 10
• Exit the “consider each white stone” loop.
• Row & col are also 1st and 2nd characters.
$i=~/./ +
( print "$& $'n" ) +
last
print int($i/10)," ",$i%10,"n";
last;
All together now
#!perl
$b = ++$/ x 11 . <>;
for $i ( 9 .. 99 ) {
if( ( $x = $b ) =~ s/^(.{$i}) /$1x/s ) {
while( $x =~ /w/g ) {
$_ = "$`W$'";
1 while
s/w((?<=W.{10})|(?<=W.)|(?=.{9}W|W))/W/s;
/W((?<= .{10})|(?<= .)|(?=.{9} | ))/ ||
$i=~/./ +
(print "$& $'n") +
last
}
}
}
TIMTOWDI
#!perl
@g=( d..n, map /./gs, <> );
sub n {
my($i,$r)=@_;
map{
$_=1 and $r=n($i+1)+n($i-1)+
n($i+10)+n($i-10)==1 if /w/;
$_=$r=1 and $0=$i if/ /
} $g[$i];
$r
}
map{
$0=~/./ + print "$& $'n" if $g[$_] eq 'w' && n $_
} 0 .. 99
Bonus post-YAPC slide
• Now 175! (stole ideas Sergei and Timur)
#!perl -ln0
map {
$i=$-[0]+11;
{
map {
1 while
s/w((?<=W.{10})|(?<=W.)|(?=.{9}W|W))/W/s;
/W((?<= .{10})|(?<= .)|(?=.{9} | ))/s ||
$i=~/./ +
print("$& $'") +
last
} "$`W$'" while/w/g
}
} "$`x$'" while/ /g

Weitere ähnliche Inhalte

Was ist angesagt?

A gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojureA gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojure
Paul Lam
 
RedHat/CentOs Commands for administrative works
RedHat/CentOs Commands for administrative worksRedHat/CentOs Commands for administrative works
RedHat/CentOs Commands for administrative works
Md Shihab
 
Joshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages TodayJoshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages Today
Refresh Events
 
Class array
Class arrayClass array
Class array
nky92
 
Comunicação Bluetooth Entre Python e PyS60
Comunicação Bluetooth Entre Python e PyS60Comunicação Bluetooth Entre Python e PyS60
Comunicação Bluetooth Entre Python e PyS60
Felipe Ronchi Brigido
 

Was ist angesagt? (20)

大海原の小さなイルカ
大海原の小さなイルカ大海原の小さなイルカ
大海原の小さなイルカ
 
Learning ProcessingJS
Learning ProcessingJSLearning ProcessingJS
Learning ProcessingJS
 
Code
CodeCode
Code
 
Clojure入門
Clojure入門Clojure入門
Clojure入門
 
A gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojureA gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojure
 
Kotlin, a nova linguagem oficial do Android
Kotlin, a nova linguagem oficial do AndroidKotlin, a nova linguagem oficial do Android
Kotlin, a nova linguagem oficial do Android
 
The Lesser Known Features of ECMAScript 6
The Lesser Known Features of ECMAScript 6The Lesser Known Features of ECMAScript 6
The Lesser Known Features of ECMAScript 6
 
Ececececuacion de primer grado y
Ececececuacion de primer grado yEcecececuacion de primer grado y
Ececececuacion de primer grado y
 
RedHat/CentOs Commands for administrative works
RedHat/CentOs Commands for administrative worksRedHat/CentOs Commands for administrative works
RedHat/CentOs Commands for administrative works
 
Tone deaf: finding structure in Last.fm data
Tone deaf: finding structure in Last.fm dataTone deaf: finding structure in Last.fm data
Tone deaf: finding structure in Last.fm data
 
Loops
LoopsLoops
Loops
 
goto dengan C++
goto dengan C++goto dengan C++
goto dengan C++
 
Joshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages TodayJoshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages Today
 
Class array
Class arrayClass array
Class array
 
Snow
SnowSnow
Snow
 
Funcd
FuncdFuncd
Funcd
 
Elf文件解析
Elf文件解析Elf文件解析
Elf文件解析
 
JavaScript Code Formatting With Prettier by Christopher Chedeau
JavaScript Code Formatting With Prettier by Christopher ChedeauJavaScript Code Formatting With Prettier by Christopher Chedeau
JavaScript Code Formatting With Prettier by Christopher Chedeau
 
Comunicação Bluetooth Entre Python e PyS60
Comunicação Bluetooth Entre Python e PyS60Comunicação Bluetooth Entre Python e PyS60
Comunicação Bluetooth Entre Python e PyS60
 
The Ring programming language version 1.6 book - Part 22 of 189
The Ring programming language version 1.6 book - Part 22 of 189The Ring programming language version 1.6 book - Part 22 of 189
The Ring programming language version 1.6 book - Part 22 of 189
 

Andere mochten auch

Developing questioning for learning
Developing questioning for learningDeveloping questioning for learning
Developing questioning for learning
douglasgreig
 
Edisi18 Sep Nasioanl
Edisi18 Sep NasioanlEdisi18 Sep Nasioanl
Edisi18 Sep Nasioanl
epaper
 
Edisi 2 Feb
Edisi 2 FebEdisi 2 Feb
Edisi 2 Feb
epaper
 
PropNex Real Estate Market Analysis July 2009
PropNex Real Estate Market Analysis July 2009PropNex Real Estate Market Analysis July 2009
PropNex Real Estate Market Analysis July 2009
John Tan Yi Shin
 
Aprendizaje colaborativo
Aprendizaje colaborativoAprendizaje colaborativo
Aprendizaje colaborativo
laurafrencia
 
Supplementing Literacy Through Technology in Elementary Educational Enrichmen...
Supplementing Literacy Through Technology in Elementary Educational Enrichmen...Supplementing Literacy Through Technology in Elementary Educational Enrichmen...
Supplementing Literacy Through Technology in Elementary Educational Enrichmen...
salm
 
13 interesting ways to Support Spelling in the Classroom
13 interesting ways to Support Spelling in the Classroom13 interesting ways to Support Spelling in the Classroom
13 interesting ways to Support Spelling in the Classroom
douglasgreig
 
Edisi19mei aceh
Edisi19mei acehEdisi19mei aceh
Edisi19mei aceh
epaper
 
S O U T H A F R I C A Fairtrade F I N A L
S O U T H  A F R I C A  Fairtrade  F I N A LS O U T H  A F R I C A  Fairtrade  F I N A L
S O U T H A F R I C A Fairtrade F I N A L
douglasgreig
 
Edisi 10 Nov Aceh
Edisi 10 Nov AcehEdisi 10 Nov Aceh
Edisi 10 Nov Aceh
epaper
 
10desnas
10desnas10desnas
10desnas
epaper
 
31 mei aceh
31 mei aceh31 mei aceh
31 mei aceh
epaper
 
Communication training 2013 a
Communication training 2013 aCommunication training 2013 a
Communication training 2013 a
douglasgreig
 
Edisi 9 April Nas
Edisi 9 April NasEdisi 9 April Nas
Edisi 9 April Nas
epaper
 

Andere mochten auch (20)

Developing questioning for learning
Developing questioning for learningDeveloping questioning for learning
Developing questioning for learning
 
Edisi18 Sep Nasioanl
Edisi18 Sep NasioanlEdisi18 Sep Nasioanl
Edisi18 Sep Nasioanl
 
Edisi 2 Feb
Edisi 2 FebEdisi 2 Feb
Edisi 2 Feb
 
Panduan Subsidi Pengawas 2007
Panduan Subsidi Pengawas 2007Panduan Subsidi Pengawas 2007
Panduan Subsidi Pengawas 2007
 
PropNex Real Estate Market Analysis July 2009
PropNex Real Estate Market Analysis July 2009PropNex Real Estate Market Analysis July 2009
PropNex Real Estate Market Analysis July 2009
 
Aprendizaje colaborativo
Aprendizaje colaborativoAprendizaje colaborativo
Aprendizaje colaborativo
 
Supplementing Literacy Through Technology in Elementary Educational Enrichmen...
Supplementing Literacy Through Technology in Elementary Educational Enrichmen...Supplementing Literacy Through Technology in Elementary Educational Enrichmen...
Supplementing Literacy Through Technology in Elementary Educational Enrichmen...
 
13 interesting ways to Support Spelling in the Classroom
13 interesting ways to Support Spelling in the Classroom13 interesting ways to Support Spelling in the Classroom
13 interesting ways to Support Spelling in the Classroom
 
Kenali Kehebatan Produk HPA Dalam Menangani Permasalahan Penyakit
Kenali Kehebatan Produk HPA Dalam Menangani Permasalahan PenyakitKenali Kehebatan Produk HPA Dalam Menangani Permasalahan Penyakit
Kenali Kehebatan Produk HPA Dalam Menangani Permasalahan Penyakit
 
Edisi19mei aceh
Edisi19mei acehEdisi19mei aceh
Edisi19mei aceh
 
The new-face-of-social
The new-face-of-socialThe new-face-of-social
The new-face-of-social
 
Nepal
NepalNepal
Nepal
 
S O U T H A F R I C A Fairtrade F I N A L
S O U T H  A F R I C A  Fairtrade  F I N A LS O U T H  A F R I C A  Fairtrade  F I N A L
S O U T H A F R I C A Fairtrade F I N A L
 
One Lightning business presentation
One Lightning business presentationOne Lightning business presentation
One Lightning business presentation
 
Edisi 10 Nov Aceh
Edisi 10 Nov AcehEdisi 10 Nov Aceh
Edisi 10 Nov Aceh
 
10desnas
10desnas10desnas
10desnas
 
31 mei aceh
31 mei aceh31 mei aceh
31 mei aceh
 
Communication training 2013 a
Communication training 2013 aCommunication training 2013 a
Communication training 2013 a
 
2010 tables 11.1 11.2
2010 tables 11.1 11.22010 tables 11.1 11.2
2010 tables 11.1 11.2
 
Edisi 9 April Nas
Edisi 9 April NasEdisi 9 April Nas
Edisi 9 April Nas
 

Ähnlich wie How i won a golf set from reg.ru

Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02
Apoorvi Kapoor
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Sway Wang
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
Kang-min Liu
 

Ähnlich wie How i won a golf set from reg.ru (20)

Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009Ruby presentasjon på NTNU 22 april 2009
Ruby presentasjon på NTNU 22 april 2009
 
In the Back of Your Mind
In the Back of Your MindIn the Back of Your Mind
In the Back of Your Mind
 
SAT/SMT solving in Haskell
SAT/SMT solving in HaskellSAT/SMT solving in Haskell
SAT/SMT solving in Haskell
 
Kotlin: maybe it's the right time
Kotlin: maybe it's the right timeKotlin: maybe it's the right time
Kotlin: maybe it's the right time
 
Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02
 
Ruby on rails presentation
Ruby on rails presentationRuby on rails presentation
Ruby on rails presentation
 
08 functions
08 functions08 functions
08 functions
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Scripting ppt
Scripting pptScripting ppt
Scripting ppt
 
正規表現のいろは
正規表現のいろは正規表現のいろは
正規表現のいろは
 
Ruby 1.9
Ruby 1.9Ruby 1.9
Ruby 1.9
 
Basics
BasicsBasics
Basics
 
tutorial7
tutorial7tutorial7
tutorial7
 
tutorial7
tutorial7tutorial7
tutorial7
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Advanced Regular Expressions Redux
Advanced Regular Expressions ReduxAdvanced Regular Expressions Redux
Advanced Regular Expressions Redux
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

How i won a golf set from reg.ru

  • 1. How I won a golf set from reg.ru at YAPC::EU 2013 Brian McCauley (nobull) Discussion at http://perlmonks.org/?node_id=1049290
  • 2. Who am I • Just Another Perl Hacker ™ • I am the one Matt Trout warned you about • Don’t to much Perl in my $dayjob • Still come to YAPC::EU for the community
  • 3. Perl Golf • Solve a defined problem • Minimal number of characters • No points for best practice • No points for runtime efficiency • No points for originality • No points for obfuscation
  • 4. The reg.ru challenge • Based on the ancient game of Go • 2 players • Square grid • Place black/white stones • Capture opponent’s stones by surrounding
  • 5. The reg.ru challenge • 9 x 9 game-state on STDIN • Enumerate capturing moves on STDOUT 1 2 3 4 5 6 7 8 9 1 ¶ 2 x ¶ 3 b w b ¶ 4 b w w b ¶ 5 b b ¶ 6 ¶ 7 x x ¶ 8 w b b w ¶ 9 w b b w w ¶ 2 4¶ 7 9¶
  • 6. My solution • 205 characters (excluding #!perl) #!perl $b=++$/x11 .<>;for$i(9..99){if(($x=$b)=~s/^(.{$i}) /$1x/s){while($x=~/w/g){$_="$`W$'";1while s/w((?<=W.{10})|(?<=W.)|(?=.{9}W|W))/W/s;/W((?<= .{10})|(?<= .)|(?=.{9} | ))/s||$i=~/./+(print"$& $'n")+last}}}
  • 7. $b=++$/x11 .<>;$b = ++$/ x 11 . <>; Read in the board • Set $/ to a character that won’t appear • Slurp STDIN including “n” – (1,9) not adjacent (2,1) etc. – Each row 10 characters • Padding so cell (3,5) is in linear position 35 etc. $/=''; $b = '11111111111' . <STDIN>;
  • 8. Consider each vacant space • Consider, in turn, a copy board with “x” in each empty cell (“ ”) • Record location of “x” in $i for $i ( 9 .. 99 ) { if( ($x = $b) =~ s/^(.{$i}) /$1x/s ) { # Do stuff with $x } } for my $i ( 11 .. 99 ) { if( ( my $x = $b) =~ s/^(.{$i}) /$1x/s ) { # Do stuff with $x } }
  • 9. Consider each white stone • Consider, in turn, a copy board with one “w” highlighted as “W” • Don’t need index this time while( $x =~ /w/g ) { $_ = "$`W$'"; # Do stuff with $_ } }
  • 10. Flood fill white stones • Replace “w” adjacent “W” with “W” • Repeat until no more 1 while s/w((?<=W.{10})|(?<=W.)|(?=.{9}W|W))/W/s; while ( # Repeat until fails s/ w # Find 'w' ((?<=W.{10}) | # with a 'W' above (?<=W.) | # or a 'W' to left (?=W) | # or a 'W' to right (?=.{9}W) ) # or a 'W' below /W/xgs # Replace with 'W' ) { }
  • 11. See if we’ve captured • Find highlighted white stone (“W”) adjacent an empty cell (“ ”). • If none then we’ve captured some stones. /W((?<= .{10})|(?<= .)|(?=.{9} | ))/s || print "Hoorah! We captured some tiles"; unless(/W((?<= .{10})|(?<= .)|(?=.{9} | ))/) { print "Hoorah! We captured some tiles"; }
  • 12. Output the move • Print the row and column derived from $i . • Padding means these are div and mod 10 • Exit the “consider each white stone” loop. • Row & col are also 1st and 2nd characters. $i=~/./ + ( print "$& $'n" ) + last print int($i/10)," ",$i%10,"n"; last;
  • 13. All together now #!perl $b = ++$/ x 11 . <>; for $i ( 9 .. 99 ) { if( ( $x = $b ) =~ s/^(.{$i}) /$1x/s ) { while( $x =~ /w/g ) { $_ = "$`W$'"; 1 while s/w((?<=W.{10})|(?<=W.)|(?=.{9}W|W))/W/s; /W((?<= .{10})|(?<= .)|(?=.{9} | ))/ || $i=~/./ + (print "$& $'n") + last } } }
  • 14. TIMTOWDI #!perl @g=( d..n, map /./gs, <> ); sub n { my($i,$r)=@_; map{ $_=1 and $r=n($i+1)+n($i-1)+ n($i+10)+n($i-10)==1 if /w/; $_=$r=1 and $0=$i if/ / } $g[$i]; $r } map{ $0=~/./ + print "$& $'n" if $g[$_] eq 'w' && n $_ } 0 .. 99
  • 15. Bonus post-YAPC slide • Now 175! (stole ideas Sergei and Timur) #!perl -ln0 map { $i=$-[0]+11; { map { 1 while s/w((?<=W.{10})|(?<=W.)|(?=.{9}W|W))/W/s; /W((?<= .{10})|(?<= .)|(?=.{9} | ))/s || $i=~/./ + print("$& $'") + last } "$`W$'" while/w/g } } "$`x$'" while/ /g

Hinweis der Redaktion

  1. I am Just Another Perl Hacker – 10 years ago quite active in the community but I am the person Matt warned you about…
  2. On the first day recall reg.ru announced a Perl Golf competition.So what is this Perl Golf anyhow? I’ve never done this before and BooK is not here so I thought I’d have a go.
  3. place pieces black and white alternately on a board capture opponent’s pieces turning them your colour by surrounding them.
  4. Test suite provided by reg.ru as you’d expect in Perl.
  5. Now let’s break that down
  6. WARNING: 2 transitions!Need the \n so there are 10 char/line also as a border so we don’t see 1,9 adjacent 2,1No strictures andno whitespace except the space between 11 and .
  7. Consider all the places I could place my next black stone. Actually this considers even characters in the leading padding and the newlines but these will never be spaces.
  8. NO TRANSITIONSMark theMention that assigning $_ and using $` and $’ are bad practice. Considering every white stone is very wasteful and against my instincts but there are no points for speed in this game.
  9. OK this is the guts of the solution. Flood fill “W” over “w”. Use look-ahead/behind assertions find “W” 10 characters back (above), 1 character back (left), 9 forward (below), imediately after (right). 9 v 10 because regex cursor is now after the character in question Need the /s because I need . to match \n. Need two look behind clauses because Perl does not support variable width look-behind.
  10. This is the same regex you’ve just seen LHS of s/// except the “w” is now “W” and “W” is “ “
  11. Use regex not div and mod for brevity. Use + not ; so we don’t need do{} block. Unfortunately need () around print but still a saving. next(LABEL) would be more idiomatic but this is Golf!
  12. All but 2 of the whitespace can be removed.Up until 01:50 (217)– woke up repeatedly with small optimisations like using $i=~/./.
  13. Sergi’s solution is a more elegant approach using arrays and recursion. At the submission deadline it passed all the tests but was a bit longer than mine. With a bit of fine tuning it’s now 179 (v 205) but I found a couple of bugs that the tests missed. Is 26 enough to fix it.
  14. ApparentlySergei Mozhaiskybeat me but missed the deadline – actually there was a bug in his solution.Borrowed the idea of using map{} with single element LIST and a statement modifier from Sergei Mozhaisky’s solution.Also borrowed a better way of printing the output from TimurNozadze’s solution meaning I did not need the padding and could use #! flags to slurp the input. I got my solution down from 205 to 175. There was a rumour that BooK beat me but he denied it.