Recent Entries 10
- pattern minor 112d agoRails method to match users according to language fluency levelThis code works fine, but I'm still learning, and feel like there is a more Railsy way to write this. Is there a good rails ActiveRecord method I should learn more about? Please let me know if you know a shorter, more direct way to run this same code. Scenario: A user can have many languages, and `level` is an attribute of languages. I want to iterate through languages_users and find all the languages of a user, and then find where another user has 2 of the same languages, but at opposite levels. user.rb ``` class User :languages_users end ``` controller ``` #Fluent languages and nonfluent languages can change depending on this situation, but here is good example: @fluent_languages = LanguagesUser.where(user: current_user.id).where("level > 4") @nonfluent_language = LanguagesUser.where(user: current_user.id).where("level < 5") email_matches(@fluent_languages, @nonfluent_languages) def email_matches(fluent_languages, nonfluent_languages) @fluent_languages = fluent_languages @nonfluent_languages = nonfluent_languages #array of user's fluent language_ids @fluent_langs = [] @fluent_langs << @fluent_languages #array of user's nonfluent language_ids @nonfluent_langs = [] @nonfluent_languages.each do |lang| @nonfluent_langs << lang.language_id end @fluent_les = LanguagesUser.select(:user_id).where(language_id: @fluent_langs, level: 1..4) @fluent_users_ids = [] @fluent_les.each do |le| @fluent_users_ids << le.user_id end @nonfluent_les = LanguagesUser.select(:user_id).where(language_id: @nonfluent_langs, level: 5) @nonfluent_user_ids = [] @nonfluent_les.each do |le| @nonfluent_user_ids << le.user_id end @matches = @fluent_users_ids & @nonfluent_user_ids @new_matches = User.where(id: @matches, status: "Active").order('last_seen DESC').limit(10) @new_matches.each do |user| UserMailer.new_match(user, current_user).deliver_later end end ``` Let me
- pattern minor 112d agoRuby banking system programAs a beginner I'd like to get any kind of feedback. The more the better. Any optimization and style mistakes? ``` class Account attr_reader :name, :balance def initialize(name, balance=100) @name = name @balance = balance end private def pin @pin = 789 end def pin_check puts "Welcome to the banking system, #{@name}!\n" + "To access your account, input PIN please" @input_pin = gets.chomp.to_i end def pin_error return "Access denied: incorrect PIN." end public def access if pin_check == pin puts "Input d: to deposit money, s: to show balance or w: to withdraw money" action = gets.chomp.downcase case action when "d" deposit when "s" display_balance when "w" withdraw else puts "Try again" end else puts pin_error end end def amount puts "Input the amount" @money = gets.to_i end def over_error print "You don't own that kind of money, dude! Your balance: $#{@balance}" end def deposit @balance += amount puts "Deposited: $#{@money}. Updated balance: $#{@balance}." end def display_balance puts "Balance: $#{@balance}." end def withdraw if amount <= @balance @balance -= @money puts "Withdrew: $#{@money}. Updated balance: $#{@balance}." else puts over_error end end end checking_account = Account.new("James Bond", 520_000) checking_account.access ```
- pattern minor 112d agoPrint combinations of balanced parenthesesSolved the below problem. Would love to hear your feedback, especially on performance improvements (granted, the solution should remain recursive). Especially concerned about the `obj.include? elem` check I had to add to prevent duplicates. Don't know a better way to do without it. ``` # Implement an algorithm to print all valid (e.g., properly # opened and closed) combinations of n-pairs of parentheses. # EXAMPLE # Input: 3 # Output: ((())), (()()), (())(), ()(()), ()()() def brackets(n) return ["()"] if n == 1 brackets(n-1).each_with_object([]) do |p, obj| for i in 0..p.length # stuff the "()" in every possible position within 'p' elem = p.dup.insert(i, "()") obj << elem unless obj.include? elem end end end ```
- pattern minor 112d agoCounting the elements of one array that are less than or equal to some other numbersI have a method which compares two array `О(n2)`, `maxes` with each element in `nums` against `<=` condition then it prints out the new array with total count for each case, but it's too slow for large arrays, what's the most efficient way to solve this problem? ``` def counts(nums, maxes) total = 0 total_array = [] maxes.each do |m| nums.each do |n| if n # [1,0,3,4] # Explanation: # 1. maxes[0] >= nums[0] # 2. maxes[1] >= 0 # 3. maxes[2] >= nums[0], nums[2], nums[3] # 4. maxes[3] >= nums[0], nums[2], nums[3], nums[4] ```
- pattern minor 112d ago"Can a given array be made strictly increasing by removing one number?"The premise of the problem is that given an array of numbers, can you remove only one to make it a strictly increasing sequence? - `[1, 1, 1, 2, 3]` would be `false` because if you remove one of the `1`s the array would still start off non-increasing because of the other two remaining `1`s before it increased. - `[1, 2, 3, 4, 99, 5, 10]` would be `true` because you can remove the `99` and the remaining array `[1, 2, 3, 4, 5, 10]` would be strictly increasing. - `[1, 88, 2, 3, 4, 99, 5, 6]` would be `false` because removing any number would still leave an array that would not strictly increase. For `[1, 1]` it would return `true` because even though removing one of the `1`s would only leave one `1` which by definition can't increase sequentially because it is only one thing, I did not write the problem and this is the response they wanted. and so on.... My questions I've clearly made this code too complex, but it does work. Below my code is the tests that I used to check it with the expected returns commented out next to each. How can I refactor this code to simplify it? Is there a way to do this without using `chunk_while`? ``` def almost_increasing_sequence(sequence) array_of_arrays = sequence.chunk_while {|i, j| i 2 puts false else if (array_of_arrays[0].last array_of_arrays[1].first) == 1 if (array_of_arrays[0][-2] array_of_arrays[1][0]) == -1 puts true elsif (array_of_arrays[0].last array_of_arrays[1][1]) == -1 puts true elsif (array_of_arrays[0][-2]) == nil puts true else puts false end else puts true end end end almost_increasing_sequence([1, 2, 3, 4, 99, 5, 6]) #true almost_increasing_sequence([1, 3, 2]) #true almost_increasing_sequence([10, 1, 2, 3, 4, 5]) #true almost_increasing_sequence([0, -2, 5, 6]) #true almost_increasing_sequence([1, 2, 3, 4, 3, 6]) #true almost_increasing_sequence([1, 1]) #true almost_increasing_sequence([100, 200, 300, 400, 99, 50
- pattern minor 112d agoRuby sudoku solver using backtracking (interview)I was required to implement the code to a spec file I was provided in Ruby. I was rejected with the message "The quality of your code isn't sufficient for this position". Can you please tell me what can be improved in order to achieve higher quality? `game_board_spec.rb` (file provided) ``` require './game' require './game_board' describe GameBoard do it "should correctly solve the board" do @game = Game.new # Each '0' is a blank cell @game.load_board 0, 0, 8, 3, 4, 2, 9, 0, 0, 0, 0, 9, 0, 0, 0, 7, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 6, 4, 7, 3, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 8, 5, 1, 6, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 3, 6, 9, 7, 5, 0, 0 @solved_board = GameBoard.new 6, 7, 8, 3, 4, 2, 9, 5, 1, 3, 2, 9, 1, 8, 5, 7, 6, 4, 4, 5, 1, 7, 6, 9, 8, 2, 3, 5, 1, 6, 4, 7, 3, 2, 8, 9, 8, 3, 7, 9, 2, 6, 4, 1, 5, 9, 4, 2, 8, 5, 1, 6, 3, 7, 7, 6, 5, 2, 1, 4, 3, 9, 8, 2, 9, 4, 5, 3, 8, 1, 7, 6, 1, 8, 3, 6, 9, 7, 5, 4, 2 @game.solve.should == @solved_board end it "should correctly solve the board" do @game = Game.new # Each '0' is a blank cell @game.load_board 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 7, 0, 2, 0, 0, 3, 6, 0, 8, 0, 0, 0, 0, 1, 0, 0, 0, 6, 2, 9, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 6, 1, 8, 0, 0, 0, 7, 0, 0, 0, 0, 6, 0, 1, 3, 0, 0, 4, 0, 2, 0, 0, 0, 2, 0, 0, 0, 4,
- pattern minor 112d agoRuby command-line app that outputs from JSON fileI made this application that runs fine, but I feel the code is sloppy as there are many if statements. I'm a beginner so I'm not sure how to improve it, at least not without messing everything up. Any suggestions? ``` #!/usr/bin/ruby require 'thor' require 'json' class ListTrends "--api-key", :type => :string, :required => true option :format, :type => :string, :desc => "one line format" option :no_country_code, :aliases => "--no-country-code", :desc => "remove country code", :type => :boolean def list_trends(keyword=nil) json = File.read('trends_available.json') trends_hash = JSON.parse(json) re = /^(?=.*[a-zA-Z])(?=.*[0-9]).{8,}$/ keyword = keyword.to_s.downcase if re.match(options[:api_key]) trends_hash.each do |trend| if trend["country"].downcase.include?(keyword) if options[:format] output = trend.values[0..2] output.delete_at(1) if options[:no_country_code] puts output.join(" ") else # Complete output trend.each do |k, v| if v.is_a?(Hash) v.each do |i, j| puts "Trend location type #{i}: #{j}" end else puts "Trend #{k}: #{v}" end end # trend.each do puts "" end # if options[:format] end # if trend["country"] end # trends_hash.each else puts "Invalid API Key, operation abort..." end # if re.match end # list_trends end ListTrends.start(ARGV) ```
- pattern minor 112d agoPhone number to words based on the dictionaryThis is the problem: Given a 10 digit phone number, you must return all possible words or combination of words from the provided dictionary, that can be mapped back as a whole to the number. With this we can generate numbers like 1-800-motortruck which is easier to remember then 1-800-6686787825 The phone number mapping to letters is as follows: ``` 2 = a b c 3 = d e f 4 = g h i 5 = j k l 6 = m n o 7 = p q r s 8 = t u v 9 = w x y z ``` The phone numbers will never contain a 0 or 1. Words have to be at least 3 characters. To get give you an initial verifiation, the following must be true: - `6686787825` should return the following list `[["motor", "usual"], ["noun", "struck"], ["nouns", "truck"], ["nouns", "usual"], ["onto", "struck"], "motortruck"] # These words exist in a dictionary file`. - The conversion of a 10 digit phone number should be performed within 1000ms. My solution works but takes longer than 1 sec. How can I improve my code so execution time will be less than 1 sec? ``` class NumberToWord def letter_combinations(digits) #return if number not valid return [] if digits.nil? || digits.length != 10 || digits.split('').select{|a|(a.to_i == 0 || a.to_i == 1)}.length > 0 #number to letters mapping letters = {"2" => ["a", "b", "c"],"3" => ["d", "e", "f"],"4" => ["g", "h", "i"],"5" => ["j", "k", "l"],"6" => ["m", "n", "o"],"7" => ["p", "q", "r", "s"],"8" => ["t", "u", "v"],"9" => ["w", "x", "y", "z"]} # Read dictionary file and hold all values in a array dictionary = [] file_path = "dictionary.txt" File.foreach( file_path ) do |word| dictionary.push word.chop.to_s.downcase end # get all letters for numbers in form of array keys = digits.chars.map{|digit|letters[digit]} results = {} total_number = keys.length - 1 # total numbers #Loo through all letters and get matching records with dictionary for i in (2..total_number) first_array = k
- pattern minor 112d agoRails 5 controller to get information about Steam usersI've done a bit of modifications and finally got it working, and did a lot of reading about `@` vs `@@` vs just declaring and I came up with. It goes to Steam's API to return information (JSON Format) based on the endpoint. A list of games they own, a list of games they recently played, profile information, etc. ``` class SteamController < ApplicationController def initialize @steamKey = ENV["steam_api_key"] @ISteamUrl = "http://api.steampowered.com/ISteamUser/" @IPlayerUrl = "http://api.steampowered.com/IPlayerService/" end def get_steam_summary_per_user #/steam/:id @steamEndpoint = "GetPlayerSummaries/v0002/?key="+@steamKey+"&steamids=" @steamId = User.find(params[:id]).steamId @playerUrl = @ISteamUrl + @steamEndpoint + @steamId.to_s @games = HTTParty.get(@playerUrl).to_json render json: @games end def get_steam_recently_played_per_user #/game/:id @recPlayedEndpoint = "GetRecentlyPlayedGames/v0001/?key="+@steamKey+"&steamid=" @steamId = User.find(params[:id]).steamId @playerUrl = @IPlayerUrl + @recPlayedEndpoint + @steamId.to_s @games = HTTParty.get(@playerUrl).to_json render json: @games end def get_steam_owned_games_per_user #/allGames/:id @allGamesUrl = "GetOwnedGames/v0001/?key="+@steamKey+"&steamid=" @steamId = User.find(params[:id]).steamId @playerUrl = @IPlayerUrl + @allGamesUrl + @steamId.to_s @games = HTTParty.get(@playerUrl).to_json render json: @games end end ``` `Routes` ``` get '/steam/:id', to: 'steam#get_steam_summary_per_user' get '/games/:id', to: 'steam#get_steam_recently_played_per_user' get '/allgames/:id', to: 'steam#get_steam_owned_games_per_user' ``` I originally just has `@baseUrl` but realized they have multiple services and versions, but even before that I couldn't figure out why doing `@baseUrl = "http://api.steampowered.com/"+@recPlayedEndpoint+"etcetc` wouldn't work - I assumed it was related to initializing the `@recPlayedEndpoint
- pattern minor 112d agoParent-child relationshipI am implementing a parent-child relationship, represented by hashes that look like this: ``` parent = { 'parent' => nil, 'id' => 3 } child = { 'parent' => parent, 'id' => 7 } ``` These hashes are data given to me, for example, through a JSON API. (As per a question in the comments, the JSON for the child would look like:) ``` { "parent": { "parent": null, "id": 3, ...etc.}, "id": 7, ...etc. } ``` Parent and child have more keys like `name`, etc. (they are a lot so I am only showing the `id` as an example). They both have the same keys. There are only parents and children, i.e., no grandchildren or grandparents, etc. There is only one "level". Each child has only one parent, but each parent may have several children. I wrapped the data in a class to represent it, so that my application can use an object. Both parent and child are represented by the same class. So I did this: ``` class Item def initialize(data) @data = data end def parent @parent ||= Item.new(data['parent']) if data['parent'] end def id data['id'] end private attr_reader :data end ``` Every key in the hash has its method to retrieve it, and `Item` is the class that represents parents and children. I use it like this: ``` describe 'children' do let(:subject1) { Item.new(child) } it 'is an item' do subject1.class.must_equal(Item) end it 'has an id' do subject1.id.must_equal(7) end it 'has a parent' do subject1.parent.id.must_equal(3) end end describe 'parent' do let(:subject2) { subject1.parent } it 'is also an item' do subject2.class.must_equal(Item) end it 'does not have a parent' do assert_nil(subject2.parent) end end ``` With this, children know who is their parent, and for a parent to know its children we can iterate through all the children and compare their parent's id with the id we are searching. However, I have a bad feeling about calling `Item.new` inside of `Item`. Is like a lot of things coul