File structure refactor

master
E. Almqvist 3 years ago
parent f352cb6a82
commit d9b7a43c38
  1. 4
      rep2/1.rb
  2. 10
      rep2/2.rb
  3. 21
      rep2/3.rb
  4. 0
      rep2/hangman.rb
  5. 55
      rep2/rep2.rb
  6. 14
      rep2/replace_substring.rb

@ -0,0 +1,4 @@
# 1
def max_of_two(num1, num2)
return num1 > num2 ? num1 : num2
end

@ -0,0 +1,10 @@
# 2
def delete_char(str, char)
newstr = ""
str.split("").each do |c|
if( c == char ) then next end
newstr += c
end
return newstr
end

@ -0,0 +1,21 @@
# 3
def distribution_calc(path)
distro_hash = Hash.new(0)
# Ladda in allt i filen till hashen
fh = File.open(path, "r")
items = fh.readlines()
total = items.length()
items.each do |item|
name, type = item.chomp().split(/\ #/)
distro_hash[type.to_sym()] += 1
end
fh.close()
# Printa ut datan
puts("Total: #{total}")
distro_hash.each do |type, amount| puts("#{type.to_s}: #{amount*100.0/total}%") end
return nil
end

@ -1,55 +0,0 @@
# Repetition 2: Programmering 1
# 1
def max_of_two(num1, num2)
return num1 > num2 ? num1 : num2
end
# 2
def delete_char(str, char)
newstr = ""
str.split("").each do |c|
if( c == char ) then next end
newstr += c
end
return newstr
end
# 3
def distribution_calc(path)
distro_hash = Hash.new(0)
# Ladda in allt i filen till hashen
fh = File.open(path, "r")
items = fh.readlines()
total = items.length()
items.each do |item|
name, type = item.chomp().split(/\ #/)
distro_hash[type.to_sym()] += 1
end
fh.close()
# Printa ut datan
puts("Total: #{total}")
distro_hash.each do |type, amount| puts("#{type.to_s}: #{amount*100.0/total}%") end
return nil
end
# 4
def replace_substring(str, rep, sub, i=0, rep_len=nil)
rep_len = rep_len || rep.length
if( i >= str.length ) then
return str
else
if( str[i...i+rep_len] == rep ) then
str[i...i+rep_len] = sub
i += rep_len - 1
end
return replace_substring(str, rep, sub, i+1, rep_len)
end
end

@ -0,0 +1,14 @@
def replace_substring(str, rep, sub, i=0, rep_len=nil)
rep_len = rep_len || rep.length # längden av det som skall ersättas
if( i >= str.length ) then # om vi har kommit till slutet: sluta
return str
else
if( str[i...i+rep_len] == rep ) then # byt ut det som skall bytas ut (om det hittades)
str[i...i+rep_len] = sub
i += rep_len - 1 # -1 för vi tar +1 på rad 12
end
return replace_substring(str, rep, sub, i+1, rep_len) # rekursivt sök efter den nästa
end
end
Loading…
Cancel
Save