Skip to content

Instantly share code, notes, and snippets.

@juuh42dias
Last active November 9, 2024 23:00
Show Gist options
  • Save juuh42dias/5e5508949b66ba4def504a4fa89af9e7 to your computer and use it in GitHub Desktop.
Save juuh42dias/5e5508949b66ba4def504a4fa89af9e7 to your computer and use it in GitHub Desktop.
Brincando com algoritmos

Python version:

def tower_of_hanoi(n, source, target, auxiliary):
    if n == 1:
        print(f"Move disk 1 from {source} to {target}")
        return
    tower_of_hanoi(n - 1, source, auxiliary, target)
    print(f"Move disk {n} from {source} to {target}")
    tower_of_hanoi(n - 1, auxiliary, target, source)

# Example usage:
n = 3  # Number of disks
tower_of_hanoi(n, 'A', 'C', 'B')

Ruby version:

def tower_of_hanoi(n, source, target, auxiliary)
  if n == 1
    puts "Move o disco 1 de #{source} para #{target}"
    return
  end

  tower_of_hanoi(n - 1, source, auxiliary, target)
  puts "Move o disco #{n} de #{source} para #{target}"
  tower_of_hanoi(n - 1, auxiliary, target, source)
end

n = 3  # Number of disks
tower_of_hanoi(n, 'A', 'C', 'B')

Ruby version otimizada pelo bot Llama do grupinho do Ruby Brasil off topic:

def tower_of_hanoi(n, source, target, auxiliary, &block)
  yield "Move disk #{n} from #{source} to #{target}" if n == 1
  return if n == 1

  tower_of_hanoi(n - 1, source, auxiliary, target, &block)
  yield "Move disk #{n} from #{source} to #{target}"
  tower_of_hanoi(n - 1, auxiliary, target, source, &block)
end

def display_moves(n, source, target, auxiliary)
  tower_of_hanoi(n, source, target, auxiliary) { |move| puts move }
end

display_moves(3, 'A', 'C', 'B')

Codigaiada

def binary_search_meu(array, x)
  low = 0
  high = array.size - 1
  mid = 0

  while low <= high do
    mid = (high + low) / 2

    if array[mid] < x
      low = mid + 1
    elsif array[mid] > x
      high = mid - 1
    else
      return mid
    end
  end
end


def binary_search_bot(array, x)
  low, high = [0, array.size - 1]
  while low <= high
    mid = (low + high) >> 1
    case
    when array[mid] < x
      low = mid + 1
    when array[mid] > x
      high = mid - 1
    else
      return mid
    end
  end
  "Non ecziste" # Caso o elemento não seja encontrado
end


# a=[1,2,3,4,5,6,9]
# p binary_search(a, 5)
# p binary_search(a, 7)

require 'benchmark'

n = (1..5_000_000).to_a

Benchmark.bm do |x|
  x.report { puts "meu"; p binary_search_meu(n, 750_000) }
  x.report { puts "bot"; p binary_search_bot(n, 750_000) }
end
def factorial_recursive(n): 
    if n == 0 or n == 1: 
        return 1 
    else: 
        return n * factorial_recursive(n - 1) 
print(factorial(10))
def factorial_recursive(n)
  if n == 0 || n == 1
    1
  else
    n * factorial_recursive(n -1)
  end
end

p factorial_recursive(10)


def factorial_recursive(n)
  return 1 if n == 0 || n == 1
  
  n * factorial_recursive(n -1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment