Advent of Code #3

source_file = open("data.txt", "r")
contents = source_file.read()
data_list = contents.split("\n")
source_file.close()
my_array=[]
counter=0
def invert(binary):
bit_s = binary
inverse_s = ''
for i in bit_s:
if i == '0':
inverse_s += '1'
else:
inverse_s += '0'
return (inverse_s)
## function end
def my_function(pos):
bit0_count=0
bit1_count=0
for x in data_list:
if (x[pos]) == "0" :
bit0_count+=1
else:
bit1_count+=1
if (bit0_count > bit1_count):
my_array.append("0")
else :
my_array.append("1")
## function end
for i in range(12) :
my_function(counter)
counter+=1
gamma= ("".join(my_array))
epsilon=invert(gamma)
a=(int(gamma, 2))
b=(int(epsilon, 2))
answer=a * b
print("answer = ",answer)

Category: code | Comments Off on Advent of Code #3

Advent of Code #2

#open file to be read
source_file = open("sonar2.txt", "r")
contents = source_file.read()
sonar_list = contents.split("\n")
source_file.close()
length_of_sonar_list = len(sonar_list)
list_pointer = 0
forward = 0
depth = 0
the_end = length_of_sonar_list
while (list_pointer < the_end):
 element = sonar_list[list_pointer]
 first_char = element[0]
 last_num = int(element[-1])
 if (first_char == "f") :
  forward=forward+last_num
 elif (first_char =="d") :
  depth=depth+last_num
 else :
  depth=depth-last_num
 list_pointer=list_pointer+1
print("forward =", forward)
print("depth =", depth)
print(forward*depth)

 

Category: code | Comments Off on Advent of Code #2

Advent of Code #1

import string
print("reading file..")
#open file to be read
source_file = open("sonar.txt", "r")
contents = source_file.read()
sonar_list = contents.split("\n")
source_file.close()
#examine contents
print(sonar_list)
#total length of list
length_of_sonar_list = len(sonar_list)
#some variables
list_pointer = 0
increased = 1
the_end = length_of_sonar_list -1
print("Number of elements in the list: ", length_of_sonar_list)
#main loop
while (list_pointer < the_end):
 element1 = sonar_list[list_pointer]
 element2 = sonar_list[list_pointer+1]
 if (element2 > element1) :
  increased=increased+1
  print(element1, element2,"***increased")
 else:
  print(element1, element2,"---decreased")
 list_pointer=list_pointer+1
print()
print("Total increases = ",increased)

 

output:

Category: code | Comments Off on Advent of Code #1