Created
March 3, 2015 21:54
-
-
Save JFFail/3935b74e2a756b72f76a to your computer and use it in GitHub Desktop.
Solution to Reddit Daily Programmer 204
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# Reddit Daily Programmer | |
# http://www.reddit.com/r/dailyprogrammer/comments/2xoxum/20150302_challenge_204_easy_remembering_your_lines/ | |
#> | |
function MoveBack | |
{ | |
param | |
( | |
$text, | |
$location | |
) | |
#Decrement the counter. | |
while($true) | |
{ | |
#Move one space up. | |
$location-- | |
#Look at the corresponding line. | |
$next = $text[$location] | |
#Compare it. | |
if(-not(($next.Length -gt 4) -and ($next.Substring(0, 4) -eq " "))) | |
{ | |
#The next line down is the last in the passage. | |
$location++ | |
return $location | |
} | |
} | |
} | |
function MoveForward | |
{ | |
param( | |
$text, | |
$location | |
) | |
while($true) | |
{ | |
#Move one space down. | |
$location++ | |
#Look at the next line. | |
$next = $text[$location] | |
#Compare it. | |
if(-not(($next.Length -gt 4) -and ($next.Substring(0, 4) -eq " "))) | |
{ | |
#The previous line was the last. | |
$location-- | |
return $location | |
} | |
} | |
} | |
function PrintPassage | |
{ | |
param( | |
$text, | |
$first, | |
$last | |
) | |
$current = $first | |
while($current -le $last) | |
{ | |
Write-Host $text[$current] | |
$current++ | |
} | |
} | |
#Read in the file. | |
$macbeth = Get-Content -Path .\macbeth.txt | |
#Input | |
$search = "rugged Russian bear" | |
#Initialize a counter. | |
$counter = 0 | |
#Find this specific line by looping through the text. | |
foreach($line in $macbeth) | |
{ | |
#Only look at lines that are at least 4 characters long. | |
if($line.length -gt 4) | |
{ | |
#Text lines are indented 4 spaces. | |
if($line.Substring(0, 4) -eq " ") | |
{ | |
#Now see if that line contains what we're looking for. | |
if($line.contains($search)) | |
{ | |
#Call the function to figure out the beginning of the passage. | |
$firstLine = MoveBack -text $macbeth -location $counter | |
#Call the function to figure out the end of the passage. | |
$lastLine = MoveForward -text $macbeth -location $counter | |
#Print the passage. | |
PrintPassage -text $macbeth -first $firstLine -last $lastLine | |
#Kill the loop. | |
break | |
} | |
} | |
} | |
#Increment the counter. | |
$counter++ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment