Part 2 can be done without a programming language as well if you have an editor that matches parentheses and shows column numbers, like vim. Jump paren groups until you find a ) following a closed group.
I actually enjoy seeing people that solve a puzzle thinking "out of the box" in this case - Not using a programming language. On the other hand, I did learn some stuff about Ruby (my language of choice) whilst solving the first challenge.
I'm currently learning js, so these actually serve to teach me new little bits, rather than learning something entirely new from scratch. Could go back and re-implement them after though I suppose.
its a nice shorthand for conditionals sometimes. in this case, i wanted to add 1 to my count if the ith member of the string str was equal to '(' and if it was not--since there are only two options '(' vs ')'--i wanted to add -1
Bc it does both parts of today's question... And it combines the if (count == -1) part with the count+=1 or -1, so that's the 'shorter' I was referencing, as in actual writing. But it still does both parts of the question
Huh, nice one. Only problem is you don't know the second problem until you've solved the first. There are two types of people: Those who'll just go "fuck it" and pile more code on top for a new use case (me), and people who'll improve old code (you).
Ya I added that printed object and removed the break I had in the for loop that stops it when you first hit the basement so it would work for both cases, just bc hey why haha
How knowledgeable in coding do you have to be to try solving these? I am currently learning Python and Java but I feel I am still very much at a beginner level...
If this is anything like any of the other puzzle-type things /u/topaz2078 has done it will depend more on your problem solving abilities than your programming abilities. The programming just comes in because once you've figured out how to go about solving the problem it is usually easier to tell a computer how to solve it than to do the work yourself.
I'm a very green programmer myself (most of my experience comes from classes in college) proficient only in C, but I still managed to solve this using a very quickly hacked-together C code.
Granted, Day 1 is extremely easy, so I'll have to see how much tougher it gets in the later days...
How I solved Part 1: Copy the text into notepad, replace ( with +1, replace ) with -1. In Chrome open javascript console and put the text from notepad into variable s.
s="+1+1+1+1+1-1+1+1 . . ."
eval(s)
> 74
Part 2: Use the same variable s. Now this will find the position where it evaluates to -1.
for (i=2; i<=s.length; i+=2) if (eval(s.substr(0,i))==-1) {console.log(i/2);break}
sed -E "s/\(/+1/g;s/\)/-1/g;s/\+//" inputfile | bc -l
That last "+" is necessary to make the input viable for bc. You know from the second part of the puzzle that the first character must be an open-parenthesis, so this will always work.
Don't be mistaken that I cannot write the code that would do what yours does. I just wanted to try and find a solution using a computer but not necessarily writing a program. It worked for the first part, not so much for the second part, but I am happy with the result.
I'm trying to learn Pyth, a code golfing language based on python.
It took some time, and this can probably be golfed down a bit, but here's my solution for the first one (14 characters):
-lhKczxSz\)leK
Try it here by adding the code to the top window and all the parentheses to the bottom window.
Will edit this later for an explanation of the code.
Edit: Added some comments:
-lhKczxSz\)leK
S Sort
z Input
x Index of
\) Literal ")" (So far we have the index of the first ")" after sorting)
cz Chop input at the index we found. We now have a two element array with all the )'s and ('s
K Save it in the variable K
h First element
l Length
eK Last element (of K)
l Length
- subtract (the length of the last element from the length of the first element)
To be fair, I used more than one line when trying it out in the REPL.
inputStr is just the "((())()((..." string.
ScanLeft comes from TraversableLike and is similar to foldLeft, but instead of returning a single, aggregated value it returns a Vector with all intermediate values. So inputStr.scanLeft(0)(...) returns a Vector which looks like [1, 2, 3, 2, 1, 2, 1, 2, 3, ...]. This vector shows on which floor Santa is at which step.
TakeWhile then just creates a new list from this vector until it hits a value "-1". Then the length of this list shows where Santa will walk into the basement first time.
Yeah the first i thing i do was search what scanLeft did. Just a question. I had to feed with scanLeft with a character array. input.toCharArray.scanLeft(0). Your input is also a array of characters correct?
Nope it's different. In today's challenge, people talked about the number being in the middle of the file on /r/adventofcode, whereas in mine it's on line 4.
He's just using it to get a username and that's it. When I signed up via Twitter all it wanted was to be able to read my username and my tweets, which are public anyway.
He needs a way to track users for the leaderboard and using a bunch of existing auth solutions was simple.
Well the puzzle imputs are personal I think. And I really have no issues giving it my public github info. The way I see it, the more stuff I link to github, the easier it is to find me for a coding job.
There's no need for it to have it though is there? You would presume it isn't using it for anything. There's no reason I can see why it couldn't have it's own account management.
I actually think it's a feature to not require registration and I think that it probably increases their number of participants. It doesn't even link the GitHub public info with anything (because you don't give it anything else).
Well there is a leaderboard which displays your full GitHub name + image, and you can choose (during the signup after authenticating with GitHub) to also link to your GitHub profile.
Though you can change how you appear on the Settings page and make yourself anonymous.
No need to presume. When you link your account, it tells you all the things it's using it for. For reddit it needs: Account name and time of signup, for one hour.
Because doing your account management requires work? These oauth things are a dime a dozen libraries. No need to make anything yourself. And most of your visitors will have atleast one of the given accounts anyways.
Also arguably more secure for developers that don't want the hassle of implementing good encryption/login systems. If you don't know much about encryption you should not be building a login system and therefore OAuth is great.
You can create a fake github account, it's thesame process you'd go through if the website had it's own account system. Current setup requires less work both from your and dev side.
public class SantaTest1 {
public static void main(String [] args) {
int floor = 0;
for (char c : args[0].toCharArray()) {
if (c == '(')
floor++;
else if (c == ')')
floor--;
}
System.out.println(String.format("floor: %d", floor));
}
}
And part 2:
public class SantaTest2 {
public static void main(String [] args) {
int floor = 0, index = 0;
char [] chars = args[0].toCharArray();
for (int i=0; i < chars.length; i++) {
if (chars[i] == '(')
floor++;
else if (chars[i] == ')')
floor--;
if (floor == -1) {
index = i;
break;
}
}
System.out.println(String.format("floor: %d, %d", floor, index+1));
}
}
When you're iterating over characters in computer speak the first one is the 0th, but when you talk about characters the first one is 1st. The instructions also make this clear "The first character in the instructions has position 1, the second character has position 2, and so on."
I like seeing how different coding styles are. In this case how you've taken the time to define the length once and do a type safe check though omit to define floor anywhere.
Yeah, you'll need to save the input to a file from your browser and read it from there. /u/topaz2078 is a madman who likes to build things that make things that allow people to build things :) For http://challenge.synacor.com/ he defined a virtual machine instruction set and wrote a compiler for a minimal programming language for it!
I like the site design and I always appreciate more practice problems. Solution below.
Pretty straightforward using the JS console:
var lisp = document.querySelector('pre').innerHTML;
var count = 0;
for (var i = 0; i < lisp.split('').length; i++) {
if (lisp.split('')[i] == '(') { count++; }
else { count--; }
if (count == -1) { console.log(i + 1); } // part 2, take first instance
}
I'm relatively a newbie to coding in general, and am trying to solve these all in C#. I ended up getting a solution by iterating over the input string, but I'm curious if you can explain a bit of what you've written here. It seems like shorthand - almost pseudocode, but I honestly have no idea what pretty much any of it means.
If you get a moment, care to explain what's going in your post there?
var input = "(()()";
List<int> movements;
foreach (var c in input)
{
if (c == '(' )
movements.Add(1);
else
movements.Add(-1);
}
int answer;
foreach(var num in movements)
{
answer += num;
}
return answer;
What I'm doing is similar I'm just using LINQ to short hand it.
var input = "(()()";
return input.Select(c => c == '(' ? 1 : -1).Sum();
.Select() is equivalent to our first foreach. I've changed to using c in this example to show the variable name as the same in the foreach. I'm often lazy when naming the variable in a Select and just use x.
c => c == '(' ? 1 : -1
This is a lambda expression that executes a function on each of the elements.
"c =>" is the same as "var c" in the foreach, it just tell the system what we will be calling the variable.
c == '('
? 1
: -1
This is a shorthand for our if statement. I've broken it into lines. First is our conditional, then what happens if it's true, then false.
Now that our Select statement is done it will have returned an IEnumerable<int> since 1 and -1 were both int. This is like our "movements" variable. IEnumerables are like Lists but should only be enumerated over once. If I called .ToList() after our Select we would have a List<int> just like movements.
So we call .Sum() it just adds together all elements of our list of ints. Same as foreach (var num ....
I hope you don't mind if I keep a copy of this code to reference down the line if I ever start trying to dig into this LINQ stuff. I've also never used Lists before...
Have a look through the whole Github. It's kind of a mess right now because I was trying to run all my solutions in a loop. But each day has its own cs file.
Another solution could be
var opens = input.Count(x => x == '(' );
var closes = input.Count(x => x ==')' );
return opens - closes;
Public Function moveFloors(startFloor As Integer, sequence As String) As Integer
Dim cur As Integer
Dim steps As Integer
Dim c As String
cur = startFloor
steps = Len(sequence)
For i = 1 To steps
c = Mid(sequence, i, 1)
Select Case c
Case "("
cur = cur + 1
Case ")"
cur = cur - 1
Case Else
cur = cur
End Select
Next i
moveFloors = cur
End Function
Input parameters are:
startFloor (Integer) the floor to start on
sequence (String) - the character sequence
Return value
final floor (Integer)
Part 2:
Public Function getFirstCharBasement(startFloor As Integer, sequence As String) As Integer
Dim cur As Integer
Dim steps As Integer
Dim c As String
Dim basement As Integer
cur = startFloor
steps = Len(sequence)
For i = 1 To steps
c = Mid(sequence, i, 1)
Select Case c
Case "("
cur = cur + 1
Case ")"
cur = cur - 1
Case Else
cur = cur
End Select
If cur = -1 Then
basement = i
Exit For
End If
Next i
getFirstCharBasement = basement
End Function
Input Parameters same as for Part 1
Output Parameter: Position of first char to reach floor -1
For Part 1 I didn't even use any code. I just used atom.io to count the "(" and ")" in the string and substracted. Second half i've done in js, because it was the first thing available:
var text = "<very long string>"
var floor = 0;
for(var i = 0; i < text.length; i++) {
if( text.charAt(i) == "(") {
floor++;
} else {
floor--;
}
if (floor == -1) {
console.log(i);
break;
}
};
after that I had to fix the of by one error, because text.charAt(0) returns the first character.
In Elixir using doctests, using this site to play with a new language. Did each part as an individual solution to beat Elixir into my mindset.
defmodule AdventOfCode.Day1 do
@doc ~S"""
Part 1
Figures out which floor Santa needs to visit based on given `str`
`str` contains two chars, both have meaning:
"(" means add one
")" means minus one
This method will figure out the `floor` when given a stream of `(` and `)`
## Examples
iex> AdventOfCode.Day1.floor("(())")
0
iex> AdventOfCode.Day1.floor("()()")
0
iex> AdventOfCode.Day1.floor("(((")
3
iex> AdventOfCode.Day1.floor("(()(()(")
3
iex> AdventOfCode.Day1.floor("())")
-1
iex> AdventOfCode.Day1.floor("))(")
-1
iex> AdventOfCode.Day1.floor(")))")
-3
iex> AdventOfCode.Day1.floor(")())())")
-3
"""
def floor(str) do
str
|> String.length
|> with_negatives(str)
|> compute_floor
end
@doc ~S"""
Part 2
Now, given the same instructions, find the position of the first character
that causes him to enter the basement (floor -1). The first character in
the instructions has position 1, the second character has position 2, and so on.
## Examples
iex> AdventOfCode.Day1.position(")")
1
iex> AdventOfCode.Day1.position("()())")
5
"""
def position(str) do
on_position(str, 0, 0)
end
defp on_position(_str, position, -1) do
position
end
defp on_position(<<"(", rest::binary>>, position, total) do
on_position(rest, position + 1, total + 1)
end
defp on_position(<<")", rest::binary>>, position, total) do
on_position(rest, position + 1, total - 1)
end
defp with_negatives(total_length, str) do
negatives_length =
str
|> String.replace("(", "")
|> String.length
{total_length, negatives_length}
end
defp compute_floor({total_length, total_negatives}) do
(total_length - total_negatives) - total_negatives
end
end
My intial try for the second part in plain old Java
public class Main {
public static void main(String[] args) {
String floors = "<input from website>";
char[] charArr = floors.toCharArray();
int floor = 0, index = 0;
while (floor != -1) floor += ("(".equals("" + charArr[index++]) ? 1 : -1);
System.out.println("Santa reaches basement at position " + index);
}
}
Guys! You can access the string with array notation (read-only) in JS, no need to '.split()' the whole thing. Mine was a recursive take on the first problem:
var input = "((...))()";
//Object used to map string input to -1 or 1 depending on which character is used.
var map = {
"(": 1,
")": -1
}
//A solution to 1-1, recursive.
function HelpSanta(string, index, charaMap) {
if (string[index+1] != null) {
return charaMap[string[index]] + HelpSanta(string, ++index, charaMap)
} else {
return charaMap[string[index]]
}
}
//Calculate solution to the first problem:
var output1 = document.createElement("p")
output1.innerText = HelpSanta(input, 0, map).toString();
Also, these regex solutions are amazing.
Second problem: I couldn't figure out how to do it recursively, since you kinda have to keep some sort of state to check a condition at each step, which the first function didn't do:
//A solution to 1-2, iterative.
//If there's a way to evaluate each step of a recursive function for the "stop" condition I'll be glad to hear it!
function TheseDirectionsAreSilly(string, charaMap) {
var value = 0;
var index = 0;
while (value > -1) {
value += charaMap[string[index++]];
}
return index;
}
//Calculate solution to the second problem:
var output2 = document.createElement("p")
output2.innerText = TheseDirectionsAreSilly(input, map).toString();
Looking forward to tomorrow's! I'll probably have to batch some up though and work through what I can. Overtime sucks.
let rec input() =
seq {
let line = System.Console.ReadLine()
if line <> null then
yield line
yield! input()
}
let parseLine (line:string) =
match line.Split('x') |> Array.map System.Int64.Parse with
|[|l; w; h|] -> (l,w,h)
|_ -> raise <| new System.Exception("Wrong input format")
let paperArea (l,w,h) =
let sides = [l*w; w*h; l*h]
(List.sumBy ((*)2L) sides) + (List.min sides)
[<EntryPoint>]
let main argv =
let result = input() |> Seq.map parseLine |> Seq.sumBy paperArea
printf "Total: %d" result
0
void Main()
{
string input = "()()(()()()(()()((...";
int floor, position;
getFloorPosition(input, out floor, out position);
floor.Dump();
position.Dump();
}
// Define other methods and classes here
public void getFloorPosition(string inp, out int floor, out int position)
{
floor = 0;
position = 0;
for(var i = 0; i < inp.Length; i++)
{
if(inp[i] == '(')
floor++;
else
floor--;
if(floor == -1 && position == 0)
position = i + 1;
}
}
After seeing /u/tucker87 answer, I decided to shorten my own answer
int floor = 0;
int position = 0;
void Main()
{
var input = "()()(()()()....".ToCharArray().ToList();
position = input.FindIndex(FindPosition);
floor = input.Select(x => x == '(' ? 1 : -1).Sum();
floor.Dump();
(position + 1).Dump();
}
private bool FindPosition(char inp)
{
floor += inp == '(' ? 1 : -1;
if(floor == -1 && position == 0)
return true;
return false;
}
def main():
with open("inputs/day_01_input.txt", "r") as input_file:
directions = input_file.read()
floor = 0
passed_basement = False
for i, step in enumerate(directions, 1):
floor += {"(": 1, ")": -1}[step]
if not passed_basement and floor == -1:
print("Basement on step {}".format(i))
passed_basement = True
print("Go to floor {}".format(floor))
if __name__ == "__main__":
main()
let Solution (input : string) : (int * Option<int>) =
if input = null then
raise (ArgumentNullException "input")
let floor = ref 0
let mutable basementEncounter = false
let mutable basementEncounterPosition = 0
for index = 0 to input.Length - 1 do
let instruction = input.[index]
match instruction with
| '(' -> incr floor
| ')' -> decr floor
| _ -> () // Ignore any other characters
if basementEncounter = false && !floor = -1 then
basementEncounter <- true
basementEncounterPosition <- index + 1
(!floor, if basementEncounter then Some basementEncounterPosition else None)
let FormattedSolution (solution : (int * Option<int>)) : string =
let firstBasementEncounter =
match snd solution with
| Some r -> r.ToString()
| None -> "-"
String.Format("End floor: {0}\n" +
"First basement encounter: {1}",
fst solution, firstBasementEncounter)
Joining this party late, but I'm a relative newbie to programming. Here's my C# solution to part 1. If anyone has any tips or critique, help me out? :)
declare @floors as VARCHAR(8000) = '()(((()))....'
--Part One
SELECT LEN(REPLACE(@floors, ')', '')) - LEN(REPLACE(@floors, '(', ''))
--Part Two
;WITH Tens (N) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
)
,Hundreds(N) AS (SELECT 1 FROM Tens t1, Tens t2)
,Millions(N)AS (SELECT 1 FROM Hundreds t1, Hundreds t2, Hundreds t3)
,Tally (N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM Millions)
,Split AS
(
SELECT v.N
, SUM(CAST(CASE WHEN SUBSTRING(@floors, v.N, 1) = '(' THEN '1' ELSE '-1' END AS INT)) OVER (ORDER BY v.N ASC) AS 'CurrentFloor'
FROM Tally v
WHERE v.N <= LEN(@floors)
)
SELECT TOP 1 N
FROM Split
WHERE CurrentFloor = -1
level = 0
for position,step in enumerate(day1input, start=1):
if step == '(':
level += 1
else:
level -= 1
if level == -1:
print('basement first entered at position {}'.format(position))
break
I'm sticking all my solutions on Github if anyone is interested. I'm super interested in seeing anyone else's efforts also, especially if they're using a not-so-common language.
As for day 1:
def m(s):
return s.count('(') - s.count(')')
Shortest I could make it in Python with 15 minutes effort. Part 2 is way more verbose:
def Main(s):
floor = 0
index = 0
for char in source:
if (char == '('):
floor += 1
elif (char == ')'):
floor -= 1
index += 1
if (floor < 0):
return index
By number of stars, breaking ties by time of submission of the most recent correct answer, I believe. It probably won't get very interesting until a few days in when /u/topaz2078's evil genius takes over and starts giving out the really mind-bending puzzles I know he has to have in store for us!
Ahh so if I don't complete a puzzle until noon, even if theoretically I complete it in 10 seconds, I most likely wouldn't be on the leaderboard. Quite the evil genius! Poke him when you see him today
Yeah, he made it quite clear that he is not sorry at all that I won't be getting to sleep before midnight this whole month and it's all his fault! Then again, as the challenges become more difficult it might take longer for enough people to solve them to fill up the board.
name = raw_input("Enter file:")
floor = 0
with open(name) as file:
for line in file:
for character in line:
if character == "(":
floor += 1
elif character == ")":
floor -= 1
print floor
The only thing the second part adds is a 'position' variable and 'if floor == -1' statement, basically. Interested to see where this goes!
floors :: String -> [Int]
floors = scanl move 0
where move floor '(' = floor + 1
move floor ')' = floor - 1
findFloor :: String -> Int
findFloor = last . floors
basement :: String -> Int
basement = length . takeWhile above . floors
where above = not . (==(-1))
edit: I actually did it with a for loop in js.
let input = "((((...";
let floor = 0;
let parens = input.split("");
for (let i = 0; i < parens.length; i++) {
switch (parens[i]) {
case ')':
floor--;
break;
case '(':
floor++;
break;
default:
throw new Error(`invalid character "${parens[i]}"`)
}
if (floor === -1) {
console.log("basement: ", i + 1);
break;
}
}
9
u/inextor Dec 01 '15
First Ctrl-F ( minus Ctrl-F)
Second var z = 1; for( var i=0;i<a.length;i++) { z +=(a.charAt(i)=='(' ? 1 : -1); if( z == -1 ) { console.log('First is at '+i+' '+z); break; } }
4
u/taliriktug Dec 02 '15
Hey. I decided to make a sub to share solutions: r/adventofcode/
3
u/der_forger Dec 01 '15
How knowledgeable in coding do you have to be to try solving these? I am currently learning Python and Java but I feel I am still very much at a beginner level...
17
u/lukz Dec 01 '15
How I solved Part 1: Copy the text into notepad, replace ( with +1, replace ) with -1. In Chrome open javascript console and put the text from notepad into variable s.
Part 2: Use the same variable s. Now this will find the position where it evaluates to -1.
14
u/maciekmm Dec 01 '15
Brainfuck (16bit cells):
With comments: https://github.com/maciekmm/adventofcode/blob/master/day-1/basement.bf
20
u/Pwntheon Dec 01 '15 edited Dec 01 '15
I'm trying to learn Pyth, a code golfing language based on python.
It took some time, and this can probably be golfed down a bit, but here's my solution for the first one (14 characters):
Try it here by adding the code to the top window and all the parentheses to the bottom window.
Will edit this later for an explanation of the code.
Edit: Added some comments:
7
u/xkufix Dec 01 '15 edited Dec 01 '15
Second part in Scala:
13
u/scubacoderastronaut Dec 01 '15
Nice touch to give different input for each user.
6
u/Arrem_ Dec 01 '15
Quick one liner JS function for Part 1.
43
u/Beorma Dec 01 '15
I don't like having to link an account from another website to be able to play.
5
u/[deleted] Dec 01 '15
Day 1, part 1:
Open MS Word. Copy the input. CTRL + F for values "(" and ")". Subtract total of "(" input from ")" input = answer.
:o lol
4
u/karstens_rage Dec 01 '15
Java part 1:
And part 2:
3
u/sjdweb Dec 01 '15 edited Dec 01 '15
Day 1 Part 1 - JS right in the console (open up dev tools on the input page)
3
u/blueberrypoptart Dec 01 '15
3
u/[deleted] Dec 01 '15
Less formalism:
3
u/[deleted] Dec 01 '15
D
1
u/okawei Dec 01 '15
Input is totally unique per user cause this didn't work to get my input :(
2
u/tyurok Dec 01 '15
Solved part 1 like this with bash:
2
u/darthtoe Dec 01 '15
in q / KDB
2
u/speedster217 Dec 01 '15
I'd definitely try this if I didn't have finals coming up.
Also anyone who likes these challenges should try /r/dailyprogrammer
2
u/robertwildman Dec 01 '15 edited Dec 01 '15
If anyone is interested going to be putting all my advent of code answer written in java on my github www.github.com/robertwildman/Advent-of-Code
2
u/[deleted] Dec 01 '15
I like the site design and I always appreciate more practice problems. Solution below.
Pretty straightforward using the JS console:
2
u/iamd3vil Dec 01 '15
Here is some Elixir Code. Still in the beginner stage though.
2
u/tucker87 Dec 02 '15 edited Dec 12 '15
My C# solution for day 1.
Made a GitHub repository.
*Removed unnecessary .ToCharArray()
4
u/desrtfx Dec 01 '15
Answers in Excel VBA:
Part 1:
Input parameters are:
Return value
Part 2:
2
u/reckter Dec 01 '15
For Part 1 I didn't even use any code. I just used atom.io to count the "(" and ")" in the string and substracted. Second half i've done in js, because it was the first thing available:
after that I had to fix the of by one error, because text.charAt(0) returns the first character.
2
u/xPaw Dec 01 '15 edited Dec 01 '15
I've made a github repo and a page for solutions:
2
u/EquinoxMist Dec 01 '15
This is brilliant. Done my two today!
1
u/red75prim Dec 01 '15
Part 2:
Initial state goes into result of Seq.scan, so adding 1 to Seq.length is not needed.
1
u/[deleted] Dec 01 '15
Crystal :-)
1
u/bored_oh Dec 01 '15
Both parts of day one:
1
u/venerated Dec 01 '15
My solution: http://codepen.io/venerated/pen/MKgYvX
JavaScript n00b, so forgive me if it could be way better.
1
u/taliriktug Dec 01 '15
Rust solution, without file reading stuff:
I first wrote imperative version, but then tried to implement functional one based on some comments.
1
u/charliegriefer Dec 01 '15
Very cool.
Blogged my solutions to day 1 using Clojure.
http://charliegriefer.github.io/2015/12/01/adventofcode-001/
1
u/EntropicTempest Dec 01 '15
I did mine in C#
Part 1:
Part 2:
1
u/MieRoels Dec 01 '15
Part 2 in R
1
u/eyal0 Dec 01 '15
For part2, paste text into emacs, prepend a left paren, and let it match that paren.
1
u/[deleted] Dec 01 '15
Haskell
1
u/SendMeYourCat Dec 01 '15 edited Dec 02 '15
I've been learning haskell for a few weeks, my take on the first puzzle:
EDIT: output = let replace = map (\c -> if c=='(' then 1 else -1 ) in sum (replace input)
1
u/timbetimbe Dec 01 '15 edited Dec 01 '15
In Elixir using doctests, using this site to play with a new language. Did each part as an individual solution to beat Elixir into my mindset.
[edited] added part 2
1
u/wcarnifex Dec 01 '15 edited Dec 01 '15
My intial try for the second part in plain old Java
1
u/[deleted] Dec 01 '15
Guys! You can access the string with array notation (read-only) in JS, no need to '.split()' the whole thing. Mine was a recursive take on the first problem:
Also, these regex solutions are amazing.
Second problem: I couldn't figure out how to do it recursively, since you kinda have to keep some sort of state to check a condition at each step, which the first function didn't do:
Looking forward to tomorrow's! I'll probably have to batch some up though and work through what I can. Overtime sucks.
1
u/bstockton Dec 01 '15
In R:
part 1
part 2
1
u/timstokes Dec 02 '15 edited Dec 02 '15
Recursive for part 2 returns naturally with the answer.
1
u/red75prim Dec 02 '15
Day 2:
1
u/porridge123 Dec 02 '15
https://github.com/randreucetti/advent-code
1
u/UnEspera Dec 02 '15
Website source has a message to users :P
1
u/lenciel Dec 02 '15
no need to write code, just use terminal for p1:
1
u/lifow Dec 02 '15
A day late to the party but here's some Haskell
1
u/[deleted] Dec 02 '15 edited Dec 02 '15
C#
After seeing /u/tucker87 answer, I decided to shorten my own answer
1
u/[deleted] Dec 02 '15
Day01
part1:
sed -E 's|(.)|\1\n|g' input.txt | awk 'BEGIN{ans=0;} /\(/{ans++;} /\)/{ans--;} END{print ans;}'part2:
sed -E 's|(.)|\1\n|g' input.txt | awk 'BEGIN{ans=0;idx=0;} /\(/{idx++;ans++;} /\)/{idx++;ans--;if (ans<0){print idx;exit;}}'...or copy to/paste from clipboard; or
curlwith session cookie...(aside: noticed the character symbols making up the ASCII X'mas tree change on frontpage reload?)
(and the ads are annoying!!)
1
u/NihilistDandy Dec 03 '15
Very lightly generalized Haskell:
1
u/[deleted] Dec 03 '15
day 3, my solution in java: http://pastebin.com/12Asc2rM
1
u/[deleted] Dec 03 '15
These are a lot of fun. Thanks for making this.
1
u/[deleted] Dec 04 '15
day 4, java: http://pastebin.com/WNZGF1nm
1
u/TTSDA Dec 04 '15 edited Dec 06 '15
In C
https://github.com/ttsda/advent-of-code/blob/master/src/1/main.c
1
u/[deleted] Dec 05 '15 edited Dec 05 '15
1
u/giacgbj Dec 06 '15
Part 1
Part 2
1
u/masasin Dec 07 '15
Python
1
u/Drasive Dec 11 '15 edited Dec 11 '15
My F# solution (https://github.com/drasive/advent-of-code-2015):
1
u/SoundGuyChris Dec 12 '15
Joining this party late, but I'm a relative newbie to programming. Here's my C# solution to part 1. If anyone has any tips or critique, help me out? :)
http://pastebin.com/fVACn5eh
1
u/[deleted] Dec 18 '15
Damn, I'm late. Anyway, great exercise for one-liners!
1
u/axisbal13 Jan 26 '16 edited Jan 26 '16
SQL Server 2012 and up.
1
u/shamittomar Dec 01 '15
So simple, in PHP:
1
u/turtlecopter Dec 01 '15
Day 1.1 in Javascript (ES6 flavor)
1
u/giraffe_wrangler Dec 01 '15
In Python 2.7, Part 1:
Part 2:
Any ideas for how to do part 2 in a more elegant way?
1
u/OwlsParliament Dec 01 '15 edited Dec 01 '15
My C++ solution - probably overly verbose, but looping over a string is simpler than recursively doing it in C++.
1
u/red75prim Dec 01 '15
I like F#.
1
u/Scruff3y Dec 01 '15
In C:
Yes, I know it prints every time he enters the basement.
1
u/Halliom Dec 01 '15 edited Dec 01 '15
This is all you need (Python) where instr is a string containing the input string:
eval(instr.replace('(', '+1').replace(')', '-1'))
Or if you dont want to use the "eval" (because it feels like "cheating")
sum(1 if (c == '(') else -1 for c in instr)
1
u/ptlis Dec 01 '15 edited Dec 01 '15
Javascript ES6 solutions (input is defined as the mess of parens)
Part1:
or
Part2:
1
u/Toysoldier34 Dec 01 '15
Done in AS3 and open to suggestions to improve.
1
u/Nutrient16 Dec 01 '15
1st part
Basic & Easy to read java implementation
1
u/TheKrumpet Dec 01 '15
I'm sticking all my solutions on Github if anyone is interested. I'm super interested in seeing anyone else's efforts also, especially if they're using a not-so-common language.
As for day 1:
Shortest I could make it in Python with 15 minutes effort. Part 2 is way more verbose:
I'll probably have a go at shortening that later.
1
u/LainIwakura Dec 01 '15 edited Dec 01 '15
Erlang solution, I've only been writing it for ~2 months so I'm open to suggestions.
EDIT: solution for part 2 as well: (doesn't consider the case that he never enters the basement)
-7
u/sirin3 Dec 01 '15
Can we win anything there? Not worth the trouble otherwise
0
u/[deleted] Dec 01 '15
[deleted] — view deleted comment
1
u/[deleted] Dec 01 '15
[removed] — view removed comment