source
stringclasses
1 value
repo
stringlengths
5
63
repo_url
stringlengths
24
82
path
stringlengths
5
167
language
stringclasses
1 value
license
stringclasses
5 values
stars
int64
10
51.4k
ref
stringclasses
23 values
size_bytes
int64
200
258k
text
stringlengths
137
258k
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/controllers/sessions_controller.rb
Ruby
mit
88
master
361
class SessionsController < ApplicationController def create if user = User.from_omniauth(request.env["omniauth.auth"]) session[:user_id] = user.id end flash[:info] = "Hi #{current_user.name} 👋" redirect_to plants_path end def destroy session.clear flash[:bye] = "Come back soon! 👋"...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/controllers/api/v1/plants_controller.rb
Ruby
mit
88
master
976
module Api module V1 class PlantsController < ApiController def index respond_with Plant.all end def find_by respond_with Plant.find_by(plant_params) end def show respond_with Plant.find(params[:id]) end def create respond_with Plant.cre...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/controllers/api/v1/api_controller.rb
Ruby
mit
88
master
329
module Api module V1 class ApiController < ApplicationController protect_from_forgery with: :null_session before_action :restrict_access respond_to :json private def restrict_access head :unauthorized unless ApiKey.exists?(api_key: params[:api_key]) end end ...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/controllers/users/unlocks_controller.rb
Ruby
mit
88
master
582
# frozen_string_literal: true class Users::UnlocksController < Devise::UnlocksController # GET /resource/unlock/new # def new # super # end # POST /resource/unlock # def create # super # end # GET /resource/unlock?unlock_token=abcdef # def show # super # end # protected # The path...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/controllers/users/passwords_controller.rb
Ruby
mit
88
master
650
# frozen_string_literal: true class Users::PasswordsController < Devise::PasswordsController # GET /resource/password/new # def new # super # end # POST /resource/password # def create # super # end # GET /resource/password/edit?reset_password_token=abcdef # def edit # super # end # ...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/controllers/users/omniauth_callbacks_controller.rb
Ruby
mit
88
master
670
# frozen_string_literal: true class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController # You should configure your model like this: # devise :omniauthable, omniauth_providers: [:twitter] # You should also create an action method in this controller like this: # def twitter # end # Mo...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/controllers/users/confirmations_controller.rb
Ruby
mit
88
master
663
# frozen_string_literal: true class Users::ConfirmationsController < Devise::ConfirmationsController # GET /resource/confirmation/new # def new # super # end # POST /resource/confirmation # def create # super # end # GET /resource/confirmation?confirmation_token=abcdef # def show # super ...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/controllers/users/registrations_controller.rb
Ruby
mit
88
master
1,437
# frozen_string_literal: true class Users::RegistrationsController < Devise::RegistrationsController # before_action :configure_sign_up_params, only: [:create] # before_action :configure_account_update_params, only: [:update] # GET /resource/sign_up # def new # super # end # POST /resource # def cr...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/controllers/users/sessions_controller.rb
Ruby
mit
88
master
515
# frozen_string_literal: true class Users::SessionsController < Devise::SessionsController before_action :configure_sign_in_params, only: [:create] # GET /resource/sign_in def new super end # POST /resource/sign_in def create super end # DELETE /resource/sign_out def destroy super en...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/services/edamam_service.rb
Ruby
mit
88
master
561
class EdamamService def initialize @_connection = Faraday.new(url: 'https://api.edamam.com') end def all(plant) parse(connection.get '/search', { q: plant, app_id: app_id, app_key: app_key }) end def find(id) parse(connection.get '/search', { r: id, app_id: app_id, app_key: app_key }) end p...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/services/farm_sense_service.rb
Ruby
mit
88
master
798
class FarmSenseService def initialize @_connection = Faraday.new(url: "http://farmsense-prod.apigee.net/v1/frostdates/") end def get_stations(lat, lon) id = parse(connection.get "stations/", {lat: lat, lon: lon}).first[:id] get_frosts(id) end def get_frosts(id) # both fall and spring frosts ...
github
damwhit/harvest_helper
https://github.com/damwhit/harvest_helper
app/serializers/plant_serializer.rb
Ruby
mit
88
master
299
class PlantSerializer < ActiveModel::Serializer attributes :id, :name, :description, :optimal_sun, :optimal_soil, :planting_considerations, :when_to_plant, :growing_from_seed, :transplanting, :spacing, :watering, :feeding, :other_care, :diseases, :pests, :harvesting, :storage_use, :image_url end
github
capistrano/notification-center
https://github.com/capistrano/notification-center
capistrano-nc.gemspec
Ruby
mit
88
master
773
# -*- encoding: utf-8 -*- Gem::Specification.new do |gem| gem.name = 'capistrano-nc' gem.version = '0.2.0' gem.authors = ['Kir Shatrov'] gem.email = ['shatrov@me.com'] gem.summary = "Capistrano 3 integration with the macOS Notification Center" gem.description = 'https://...
github
capistrano/notification-center
https://github.com/capistrano/notification-center
lib/capistrano-nc/tasks/nc.rake
Ruby
mit
88
master
956
require 'terminal-notifier' module CapistranoNc def self.nc_supported? `uname`.strip == 'Darwin' && os_x_version >= Gem::Version.new('10.8') end def self.os_x_version Gem::Version.new(`sw_vers -productVersion`.strip) end end namespace :nc do task :finished do if CapistranoNc.nc_supported? ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/zero_matrix_spec.rb
Ruby
mit
88
master
412
require_relative '../../algorithms/zero_matrix' describe 'Matrix#zero_matrix' do let(:matrix) do Matrix.new( [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [1, 0, 3, 4, 5]]) end let(:zeroed_matrix) do Matrix.new( [[0, 0, 0, 0, 0], [0, 0, 7, 8, 9], [0, 0, 0, 0, 0]]) end it 're...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/remove_duplicates_spec.rb
Ruby
mit
88
master
249
require_relative '../../algorithms/remove_duplicates' describe 'remove_duplicate_characters' do it 'removes all the duplicate letters in "Hello, World!!"' do expect(remove_duplicate_characters('Hello, World!!')).to eq('Helo, Wrd!') end end
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/pascals_triangle_spec.rb
Ruby
mit
88
master
237
require_relative '../../algorithms/pascals_triangle' describe 'PascalsTriangle' do it 'returns the first four rows' do four_rows = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]] expect(pascals_triangle(4)).to eq(four_rows) end end
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/largest_internal_binary_search_tree_spec.rb
Ruby
mit
88
master
1,001
require_relative '../../algorithms/largest_internal_binary_search_tree' describe 'largest_internal_binary_search_tree' do it 'returns the entire binary tree' do root = Node.new(10) root.left = Node.new(9) root.right = Node.new(11) expect(largest_internal_binary_search_tree(root).count).to eq(...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/rate_limiter_spec.rb
Ruby
mit
88
master
707
require_relative '../../algorithms/rate_limiter' describe 'RateLimiter' do let(:rate_limitor) { RateLimiter.new } specify '#hit_endpoint does not allow 11 requests within 10 seconds' do request_statuses = [] 11.times do request_statuses << rate_limitor.hit_endpoint end request_statuses[0..9]...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/string_rotation_spec.rb
Ruby
mit
88
master
544
require_relative '../../algorithms/string_rotation' describe 'rotation?' do let(:str) { 'waterbottle' } let(:rotation) { 'erbottlewat' } let(:nonrotation) { 'wterbottlew' } it 'returns true when the strings are rotations of each other' do expect(rotation_1? str, rotation).to eq true expect(rotation_2?...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/loop_detection_spec.rb
Ruby
mit
88
master
868
require_relative '../../algorithms/loop_detection' describe 'detection of a loop in a linked list' do let!(:linked_list1) { LinkedList.new } let!(:linked_list2) { LinkedList.new } before do linked_list1.add('h') linked_list1.add('e') linked_list1.add('l') linked_list1.add('p') linked_list1.ad...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/sum_lists_spec.rb
Ruby
mit
88
master
792
require_relative '../../algorithms/sum_lists' describe 'sum_lists' do let!(:one) { Node.new(1) } let!(:two) { Node.new(2) } let!(:three) { Node.new(3) } let!(:four) { Node.new(4) } let!(:five) { Node.new(5) } let!(:six) { Node.new(6) } let!(:seven) { Node.new(7) } before do # 125 (521) one.next...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/string_compression_spec.rb
Ruby
mit
88
master
461
require_relative '../../algorithms/string_compression.rb' describe 'compress_string' do let(:not_compressed) { 'abcabcabc' } let(:compressable) { 'abbcccdddd' } let(:compressed) { 'a1b2c3d4' } it 'returns the original string when it can not be compressed' do expect(compress_string not_compressed).to eq no...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/invert_binary_tree_spec.rb
Ruby
mit
88
master
552
require_relative '../../algorithms/invert_binary_tree' require_relative '../../data-structures/tree_node' describe 'invert_binary_tree' do it 'inverts a binary tree' do root = Node.new('root') left = Node.new('L') right = Node.new('R') left_left = Node.new('L-L') root.left = l...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/remove_duplicates_in_linked_list_spec.rb
Ruby
mit
88
master
496
require_relative '../../algorithms/remove_duplicates_in_linked_list' describe 'remove_duplicates' do let!(:a) { Node.new('a') } before do a2 = Node.new('a') b = Node.new('b') b2 = Node.new('b') c = Node.new('c') c2 = Node.new('c') a.next = a2 a2.next = b b.next = b2 b2.next ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/animal_shelter_spec.rb
Ruby
mit
88
master
1,005
require_relative '../../algorithms/animal_shelter' describe 'AnimalShelter' do let(:cat1) { Animal.new(:cat) } let(:cat2) { Animal.new(:cat) } let(:cat3) { Animal.new(:cat) } let(:dog1) { Animal.new(:dog) } let(:dog2) { Animal.new(:dog) } let(:shelter) { AnimalShelter.new } before do shelter.enqueue...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/intersection_spec.rb
Ruby
mit
88
master
1,062
require_relative '../../algorithms/intersection' describe 'intersection of two lists' do let!(:linked_list1) { LinkedList.new } let!(:linked_list2) { LinkedList.new } let!(:linked_list3) { LinkedList.new } before do linked_list1.add('h') linked_list1.add('e') linked_list1.add('l') linked_list1....
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/sort_stack_spec.rb
Ruby
mit
88
master
407
require './algorithms/sort_stack' describe 'Stack#sort' do it 'sorts elements of a stack so that the smallest elements is on top' do stack = SortStack.new first_ten = (0..9).to_a first_ten.each { |n| stack.push n } sorted_stack = stack.sort sorted_array = 10.times.each_with_object([]) { |n, arr| ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/delete_middle_node_spec.rb
Ruby
mit
88
master
483
require_relative '../../algorithms/delete_middle_node' describe 'delete_middle_node' do let!(:a) { Node.new('a') } let!(:b) { Node.new('b') } let!(:c) { Node.new('c') } let!(:d) { Node.new('d') } before do a.next = b b.next = c c.next = d end it 'removes a middle node' do expect(a.to...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/rotate_matrix_spec.rb
Ruby
mit
88
master
679
require_relative '../../algorithms/rotate_matrix' describe 'Matrix rotation' do let(:matrix) do Matrix.new( [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]) end let(:rotated_matrix) do Matrix.new( [[12, 8, 4, 0], [13, 9, 5, 1], [14, 10, 6, 2], ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/one_edit_away_spec.rb
Ruby
mit
88
master
559
require_relative '../../algorithms/one_edit_away.rb' describe 'one_edit_away?' do it 'returns true when strings are one edit away' do expect(one_edit_away?('hello', 'hello2')).to be true expect(one_edit_away?('hello', 'hell')).to be true expect(one_edit_away?('hello', 'bello')).to be true end it 're...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/partition_linked_list_spec.rb
Ruby
mit
88
master
761
require_relative '../../algorithms/partition_linked_list' describe 'partition_linked_list' do let!(:a) { Node.new(1) } let!(:b) { Node.new(2) } let!(:c) { Node.new(3) } let!(:d) { Node.new(4) } let!(:e) { Node.new(4) } let!(:f) { Node.new(1) } let!(:g) { Node.new(5) } before do a.next = b b.ne...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/permutation_strings_spec.rb
Ruby
mit
88
master
538
require_relative '../../algorithms/permutation_strings' describe 'permutation?' do let(:cat) { 'iamacatmeow' } let(:cat_permutation) { 'iamcatameow' } let(:dog) { 'iamadog' } it 'returns true when two strings are permutations' do expect(permutation_1?(cat, cat_permutation)).to eq true expect(permutati...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/is_unique_spec.rb
Ruby
mit
88
master
555
require_relative '../../algorithms/is_unique' describe 'unique?' do let(:unique_str) { 'meowcats' } let(:duplicate_str) { 'meowmeow' } it 'returns true when all characters are unique' do expect(unique_1?(unique_str)).to eq true expect(unique_2?(unique_str)).to eq true expect(unique_3?(unique_str)).t...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/permutation_of_palindrome_spec.rb
Ruby
mit
88
master
410
require_relative '../../algorithms/permutation_palindrome' describe 'permutaiton_of_palindrome?' do it 'returns true when a string is a permutation of a palindrome' do expect(permutation_of_palindrome?('meow iamacatm eowiamac atX')).to eq true end it 'returns false when a string is not a permutation of a pa...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/return_kth_to_last_element_spec.rb
Ruby
mit
88
master
454
require_relative '../../algorithms/return_kth_to_last_element' describe 'kth_to_last_element' do let!(:a) { Node.new('a') } before do b = Node.new('b') c = Node.new('c') d = Node.new('d') e = Node.new('e') a.next = b b.next = c c.next = d d.next = e end it 'returns the seco...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/algorithms/palindrome_spec.rb
Ruby
mit
88
master
2,188
require_relative '../../algorithms/palindrome' describe 'palindrome linked lists' do let!(:linked_list_palindrome) { LinkedList.new } let!(:linked_list_palindrome_2) { LinkedList.new } let!(:linked_list_meow) { LinkedList.new } before do linked_list_palindrome.add('h') linked_list_palindrome.add('e') ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/data-structures/min_heap_spec.rb
Ruby
mit
88
master
618
require_relative '../../data-structures/min_heap.rb' describe 'MinHeap' do let(:heap) { MinHeap.new } before { (0..7).to_a.shuffle.each { |n| heap.insert n } } it '#extract_min extracts the lowest number each time' do 7.times do |n| expect(heap.extract_min).to eq n end end it '#insert will pr...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/data-structures/set_of_stacks_spec.rb
Ruby
mit
88
master
694
require_relative '../../data-structures/set_of_stacks' describe 'SetOfStacks' do let(:stack) { SetOfStacks.new(3) } before do (1..9).each { |n| stack.push(n) } end it 'can adds 9 elements and creates three stacks' do expect(stack.instance_variable_get('@stacks').size).to eq 3 end it 'pops element...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/data-structures/queue_using_two_stacks_spec.rb
Ruby
mit
88
master
405
require './data-structures/queue_using_two_stacks' describe 'Queue using two stacks' do it 'adds items and removes them in the order they were added (FIFO)' do queue = MyQueue.new five_numbers = (1..5).to_a five_numbers.each { |n| queue.add n } queue_output = 5.times.each_with_object([]) { |_, arr| a...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/data-structures/binary_tree_spec.rb
Ruby
mit
88
master
1,247
require_relative '../../data-structures/binary_tree' describe 'BinaryTree' do let(:tree) { BinaryTree.new } specify '#insert adds data to the tree' do numbers = [1, 2] numbers.each do |number| tree.insert number end tree_data = [] tree.traverse_bfs do |datum| tree_data << datum ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/data-structures/linked_stack_spec.rb
Ruby
mit
88
master
995
require_relative '../../data-structures/linked_stack' describe LinkedStack do let(:linked_stack) { LinkedStack.new } specify '#peek will reveal the top of the stack' do linked_stack.push('hello') expect(linked_stack.peek).to eq('hello') expect(linked_stack.length).to eq(1) end specify '#push adds...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/data-structures/singly_linked_list_spec.rb
Ruby
mit
88
master
926
require_relative '../../data-structures/singly_linked_list' describe 'LinkedList' do let!(:linked_list) { LinkedList.new } it 'creates missing elements when setting values' do linked_list[1] = 'one' expect(linked_list[0]).to eq(nil) expect(linked_list[1]).to eq('one') end it 'enumerates with each...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/data-structures/doubly_linked_list_spec.rb
Ruby
mit
88
master
1,240
require_relative '../../data-structures/doubly_linked_list' describe 'LinkedList' do let!(:linked_list) { LinkedList.new } it 'creates missing elements when setting values' do linked_list[1] = 'one' expect(linked_list[0]).to eq(nil) expect(linked_list[1]).to eq('one') end it 'enumerates with each...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
spec/javascripts/support/jasmine_helper.rb
Ruby
mit
88
master
542
# Use this file to set/override Jasmine configuration options # You can remove it if you don't need it. # This file is loaded *after* jasmine.yml is interpreted. # # Example: using a different boot file. # Jasmine.configure do |config| # config.boot_dir = '/absolute/path/to/boot_dir' # config.boot_files = lambda ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
data-structures/singly_linked_list.rb
Ruby
mit
88
master
1,080
require_relative 'node.rb' class LinkedList include Enumerable attr_accessor :length def initialize @length = 0 end def [](pos) return nil if pos >= @length || pos < 0 # bounds check index = 0 current_node = @head while index < pos current_node = current_node.next i...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
data-structures/binary_tree.rb
Ruby
mit
88
master
1,432
class Node attr_accessor :parent, :left, :right, :data def initialize(data = nil, parent = nil, left = nil, right = nil) @parent = parent @left = left @right = right @data = data end end class BinaryTree attr_accessor :length def insert(data) return create_root(data) if @root.nil? ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
data-structures/tree_node.rb
Ruby
mit
88
master
242
class Node attr_accessor :left, :right, :data def initialize(data) self.data = data end def to_s "(Data: #{@data}) : (Left: #{@left&.data}) : (Right: #{@right&.data})" end def ==(other) data == other.data end end
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
data-structures/queue_using_two_stacks.rb
Ruby
mit
88
master
988
# CtCI 6th Edition Problem 3.4 # Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks. class MyStack attr_reader :size def initialize @stack = [] @size = 0 end def push(el) @size += 1 @stack << el end def pop return if @size.zero? @size -= 1 ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
data-structures/doubly_linked_list.rb
Ruby
mit
88
master
1,256
require_relative 'node.rb' class LinkedList include Enumerable attr_accessor :length def initialize @length = 0 @index = -1 end def [](pos) return if pos >= length || pos < 0 # bounds check delta = pos > @index ? 1 : -1 # set direction until @index == pos # trave...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
data-structures/stack_min.rb
Ruby
mit
88
master
577
# CtCI 6th Edition Problem 3.2 # Stack Min: How would you design a stack which, in addition to push and pop, has a function min # which returns the minimum element? Push, pop and min should all operate in 0(1) time. # Keep track of the minimum element at each point in the stack. Then you don't need # to calculate it w...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
data-structures/min_heap.rb
Ruby
mit
88
master
3,257
class MinHeap attr_accessor :nodes def initialize @nodes = [] end # Peek the minimum element def min @nodes.first end # Remove and return the root def extract_min @nodes.shift.tap do # Move the last node to the root position and then heapify down @nodes.unshift @nodes.pop unle...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
data-structures/set_of_stacks.rb
Ruby
mit
88
master
1,488
# CtCI 6th Edition Problem 3.3 # Stack of Plates: Imagine a (literal) stack of plates. If the stack gets too high, it might topple. # Therefore, in real life, we would likely start a new stack when the previous stack exceeds some # threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should b...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
data-structures/linked_stack.rb
Ruby
mit
88
master
396
require_relative 'singly_linked_list' class LinkedStack < LinkedList def empty? @length == 0 end def push(data) new_head = Node.new(data) new_head.next = @head @length += 1 @head = new_head end def pop return nil if empty? data = @head.data @head = @...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/difference_between_arrays.rb
Ruby
mit
88
master
305
# Write a function (similar to _.difference) that takes two arrays # and returns two arrays containing the elements not present in the other def difference(arr1, arr2) result_1 = arr1.reject { |num| arr2.include?(num) } result_2 = arr2.reject { |num| arr1.include?(num) } [result_1, result_2] end
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/binary_tree_preorder_traversal.rb
Ruby
mit
88
master
644
# Given a binary tree, return the preorder traversal of its nodes' values. # # Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} root # @return {Integer[]} de...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/permutation_palindrome.rb
Ruby
mit
88
master
687
# CtCI Edition 6 Problem 1.4 # Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. # A palindrome is a word or phrase that is the same forwards and backwards. A permutation # is a rearrangement of letters. The palindrome does not need to be limited to just dictionar...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/make_change.rb
Ruby
mit
88
master
1,832
# dynamic programming version def make_change(amount, coins) result = Array.new(amount + 1, 0) result[0] = 1 coins.each do |coin| (coin..amount).each do |higher_amount| remainder = higher_amount - coin result[higher_amount] += result[remainder] end end result[amount] end ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/danny_search.rb
Ruby
mit
88
master
1,294
class Node attr_accessor :char, :locations def initialize(char = nil) self.char = char self.locations = Hash.new { |h, k| h[k] = [] } end def occurrences self.locations.keys end def [](pos) self.locations[pos] end def insert(location, left_node, right_node) self.locations[l...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/add_reversed_linked_list_digits.rb
Ruby
mit
88
master
731
# Add two numbers represented by linked lists # Input: # First List: 7->5->9->4->6 // represents number 64957 # Second List: 8->4 // represents number 48 # Output # Resultant list: 5->0->0->5->6 // represents number 65005 def add_reversed_digits(list1, list2) return false unless list1 && list2 current1 =...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/reverse_characters_and_string.rb
Ruby
mit
88
master
448
def reverse_sentence(str) reverse_in_place(str, 0, str.length - 1) word_beginning = 0 (0..str.length).each do |i| if i == str.length || str[i] == ' ' reverse_in_place(str, word_beginning, i - 1) word_beginning = i + 1 end end str end def reverse_in_place(str, start, len) while start <...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/partition_linked_list.rb
Ruby
mit
88
master
2,024
# CtCI 6th Edition Problem 2.4 # Partition: Write code to partition a linked list around a value x, such that all nodes less than x come # before all nodes greater than or equal to x. lf x is contained within the list, the values of x only need # to be after the elements less than x (see below). The partition element x...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/isomorphic_strings.rb
Ruby
mit
88
master
355
# @param {String} s # @param {String} t # @return {Boolean} def isomorphic?(s, t) return false unless s.length == t.length map = {} (0...s.length).each do |i| map['s' + s[i]] = t[i] unless map['s' + s[i]] map['t' + t[i]] = s[i] unless map['t' + t[i]] return false if t[i] != map['s' + s[i]] || s[i] !=...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/remove_duplicates.rb
Ruby
mit
88
master
300
# @param {String} text # @return {String} def remove_duplicate_characters(text) visited_characters = Set.new new_text = '' text.each_char do |character| new_text += character unless visited_characters.include? character visited_characters << character end new_text end
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/dijkstras.rb
Ruby
mit
88
master
830
# Will find the shortest path between a source node and any other node in the graph. # https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Using_a_priority_queue def dijkstra(graph, source_node) priority_queue = PriorityQueue.new distance = Hash.new(Float::INFINITY) distance[source_node] = 0...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/graph_depth_first_search.rb
Ruby
mit
88
master
560
class DFS attr_reader :graph def initialize(graph, s) @graph = graph @s = s @visited = [] @edge_to = {} dfs(@graph, @s) end def dfs(graph, s) @visited << s @graph[s].each do |node| next if @visited.include? node dfs(graph, node) @edge_to[node] = s end...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/invert_binary_tree.rb
Ruby
mit
88
master
386
# Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # # @param {TreeNode} root # @return {TreeNode} def invert_binary_tree(root) root.right, root.left = invert_binary_tree(root....
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/rate_limiter.rb
Ruby
mit
88
master
381
# Create a class that limits hitting an external API to # 10 attempts per second. class RateLimiter def initialize @request_times = Array.new(10) { 0 } end def hit_endpoint current_time = Time.now.to_i if current_time - @request_times.first >= 10 @request_times.shift @request_times << cu...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/linked_list_palindrome.rb
Ruby
mit
88
master
458
def palindrome?(head) stack = [] slow_runner = fast_runner = head while !fast_runner.nil? && !fast_runner.next.nil? stack.push(slow_runner.val) fast_runner = fast_runner.next.next slow_runner = slow_runner.next end unless fast_runner.nil? slow_runner = slow_runner.next end until s...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/summary_ranges.rb
Ruby
mit
88
master
707
# Given a sorted integer array without duplicates, return the summary of its ranges.# # example: [0,1,2,4,5,7], return ["0->2","4->5","7"]. # # @param {Integer[]} numbers # @return {String[]} def summary_ranges(numbers) ranges = [] last_number = numbers.shift current_range = [last_number] (0..numbers...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/lowest_common_ancestor.rb
Ruby
mit
88
master
513
# Find the lowest common ancestor in a Binary Tree. # The lowest common ancestor of two nodes v and w in a tree is the lowest (i.e. deepest) node # that has both v and w as descendants. def lowest_common_ancestor(node1, node2) parents = Set.new parent1 = node1.parent parent2 = node2.parent until parents.includ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/tree_path_equals_sum.rb
Ruby
mit
88
master
619
# Given a binary tree and a sum, determine if the tree has a root-to-leaf path # such that adding up all the values along the path equals the given sum. # Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right =...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/valid_binary_tree.rb
Ruby
mit
88
master
472
MAX_INT = 99_999_999_999_999_999_999 LOW_INT = -99_999_999_999_999_999_999 def valid_binary_tree(root) stack = [[root, LOW_INT, MAX_INT]] while stack.length > 0 node, low_bounds, high_bounds = stack.pop if node.val < low_bounds || node.val > high_bounds return false end if node.left s...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/minimum_depth_of_binary_tree.rb
Ruby
mit
88
master
436
# Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} treeNode # @return {Integer} def minimum_depth_of_binary_tree(tree_node) if tree_node.nil? 0 else ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/remove_duplicates_in_linked_list.rb
Ruby
mit
88
master
1,182
# CtCI 6th Edition Problem 2.1 # Remove Dups: Write code to remove duplicates from an unsorted linked list. # How would you solve this problem if a temporary buffer is not allowed? class Node attr_accessor :data, :next def initialize(data) @data = data @next = nil end def to_s data_str = '' cu...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/zero_matrix.rb
Ruby
mit
88
master
1,344
# CtCI Edition 6 Problem 1.8 # Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and # column are set to O. # Matrix is NxM class Matrix def initialize(matrix_array) @matrix = matrix_array @rows = @matrix.length - 1 @cols = @matrix[0].length - 1 end # retu...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/one_edit_away.rb
Ruby
mit
88
master
1,150
# CtCI Edition 6 Problem 1.5 # One Away: There are three types of edits that can be performed on strings: insert a character, # remove a character, or replace a character. Given two strings, write a function to check if they are # one edit (or zero edits) away. # Loops through the largest string, so it is O(n) def one...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/anagrams.rb
Ruby
mit
88
master
773
# Given a single input string, write a function that produces all possible anagrams # of a string and outputs them as an array. At first, don't worry about # repeated strings. What time complexity is your solution? # # Extra credit: Deduplicate your return array without using uniq(). # def anagrams(word) return fal...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/merge_sorted_arrays.rb
Ruby
mit
88
master
313
def merge(nums1, m, nums2, n) while m >= 0 && n >= 0 if nums1[m] > nums2[n] nums1[m + n - 1] = nums1[m] m -= 1 else nums1[m + n - 1] = nums2[n] n -= 1 end end while n > 0 nums1[m + n - 1] = nums2[n - 1] n -= 1 end end
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/delete_kth_node.rb
Ruby
mit
88
master
367
def delete_kth_node(head, k) return false unless head current = head count = 1 while current.next current = current.next count += 1 end return false if count - k < 0 current = head (0...count - k).each do current = current.next end current.value = current.next.value || nil curren...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/binary_tree_inorder_traversal.rb
Ruby
mit
88
master
655
# Given a binary tree, return the inorder traversal of its nodes' values. # # Definition for a binary tree node: # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} root # @return {Integer[]} def...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/sum_lists.rb
Ruby
mit
88
master
1,697
# CtCI 6th Edition Problem 2.5 # Sum Lists: You have two numbers represented by a linked list, where each node contains a single # digit. The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a # function that adds the two numbers and returns the sum as a linked list. # EXA...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/return_kth_to_last_element.rb
Ruby
mit
88
master
1,076
# CtCI 6th Edition Problem 2.2 # Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list. class Node attr_accessor :data, :next def initialize(data) @data = data @next = nil end def to_s data_str = '' current = self until current.nil? data_...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/string_compression.rb
Ruby
mit
88
master
1,039
# CtCI 6th Edition Problem 1.6 # String Compression: Implement a method to perform basic string compression using the counts # of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the # "compressed" string would not become smaller than the original string, your method should return # th...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/is_unique.rb
Ruby
mit
88
master
840
# CtCI 6th Edition Problem 1.1 # Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you # cannot use additional data structures? # O(n) solution # The string length will be the same as the set length if it is all unique characters def unique_1?(str) str.split('').to_set.len...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/min_change_sum.rb
Ruby
mit
88
master
417
# write a function to determine the minimum number of coins used that sum to a value # ex coins = [1, 3, 5] total = 11 def min_change_sum(coins, total) totals = Array.new(total + 1, 1_000_000_000_000) totals[0] = 0 (1..total).each do |i| coins.each do |coin| if coin <= i && (totals[i - coin] + 1 < ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/string_rotation.rb
Ruby
mit
88
master
998
# CtCI 6th Edition Problem 1.9 # String Rotation: Assume you have a method isSubst ring which checks if one word is a substring # of another. Given two strings, 51 and 52, write code to check if 52 is a rotation of 51 using only one # call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat"). # Looping i...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/maximum_depth_of_binary_tree.rb
Ruby
mit
88
master
432
# Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} root # @return {Integer} def maximum_depth_of_binary_tree(tree_node) if tree_node.nil? 0 else ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/graph_breadth_first_search.rb
Ruby
mit
88
master
654
class BFS attr_accessor :graph, :s, :visited, :edge_to def initialize(graph, s) @graph = graph @s = s @visited = [@s] @edge_to = {} bfs end def bfs queue = [@s] while queue.length > 0 node = queue.shift @graph[node].each do |child_node| next if @visite...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/permutation_strings.rb
Ruby
mit
88
master
772
# CtCI Edition 6 problem 1.2 # Check Permutation: Given two strings, write a method to decide if one is a permutation of the # other. # Sorting is O(nlogn) and comparing is O(n) making this O(aloga + blogb) def permutation_1?(str1, str2) # Sorted permutations are the same str1.split('').sort == str2.split('').sort...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/delete_middle_node.rb
Ruby
mit
88
master
1,003
# CtCI 6th Edition Problem 2.3 # Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but # the first and last node, not necessarily the exact middle) of a singly linked list, given only access to # that node. # EXAMPLE # Input: the node c from the linked list a->b->c->d->e->f # Res...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/largest_internal_binary_search_tree.rb
Ruby
mit
88
master
1,847
require_relative '../data-structures/tree_node' # Given a binary tree, return its largest internal binary search tree. # @param {TreeNode} root # @return {TreeNode.val[]} def largest_internal_binary_search_tree(root) binary_search_trees = [] nodes_to_visit = [root] while nodes_to_visit.count > 0 curre...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/sort_stack.rb
Ruby
mit
88
master
1,021
# CtCI 6th Edition Problem 3.5 # Sort Stack: Write a program to sort a stack such that the smallest items are on the top. You can use # an additional temporary stack, but you may not copy the elements into any other data structure # (such as an array). The stack supports the following operations: push, pop, peek, and i...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/rotate_matrix.rb
Ruby
mit
88
master
2,443
# CtCI 6th Edition Problem 1.7 # Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 # bytes, write a method to rotate the image by 90 degrees. Can you do this in place? # Matrix is always NxN class Matrix def initialize(matrix_array) @matrix = matrix_array end # M...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/caesar_cipher.rb
Ruby
mit
88
master
270
LOWER_Z = 122 def caesar_cipher(text, shift) ciphered_text = '' shift = shift % LOWER_Z text.each_char do |letter| ciphered_text += letter.ord + shift > LOWER_Z ? (letter.ord + shift - LOWER_Z).chr : (letter.ord + shift).chr end ciphered_text end
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/longest_common_prefix.rb
Ruby
mit
88
master
215
# @param {String[]} strs # @return {String} def longest_common_prefix(strs) return '' if strs.empty? min, max = strs.minmax idx = min.size.times { |i| break i unless min[i] == max[i] } min[0...idx] end
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/topological_sort.rb
Ruby
mit
88
master
751
# Topological ordering of a directed graph is a linear ordering of # its vertices such that for every directed edge uv from vertex u to vertex v, # u comes before v in the ordering. class Dag attr_accessor :nodes def topological_sort # Tarjan's algorithm @sorted_nodes = [] @unmarked_nodes = @nodes....
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/animal_shelter.rb
Ruby
mit
88
master
1,333
# CtCI 6th Edition problem 3.6 # Animal Shelter: An animal shelter, which holds only dogs and cats, operates on a strictly"first in, first # out" basis. People must adopt either the "oldest" (based on arrival time) of all animals at the shelter, # or they can select whether they would prefer a dog or a cat (and will re...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/balanced_binary_tree.rb
Ruby
mit
88
master
507
def balanced_binary_tree(node) depths = [] stack = [] stack.push([node, 0]) while stack.length > 0 node, depth = stack.pop if !node.left && !node.right unless depths.include?(depth) depths << depth if depths.length > 2 || (depths.length == 2 && (depth[0] - depth[1]).abs > 1) ...
github
Dbz/Algorithms
https://github.com/Dbz/Algorithms
algorithms/string_is_substring.rb
Ruby
mit
88
master
395
# Assume you have a method is_substring(s1, s2) which checks if one word is a substring # of another string. Given 2 strings s1, s2, write code to check if s2 is a rotation # of s1 using only one call to is_substring. ex. waterbottle -> erbottlewat def string_is_substring(s1, s2) return false if s1.length != s2.leng...