Answer the question
In order to leave comments, you need to log in
How to check if there is a given correspondence between the elements of two sets by a correctly given mapping?
Write a program that takes two finite sets and a correspondence between the elements of these sets as input and determines whether the given correspondence is a properly defined mapping.
Mapping from set X to set Y - each element from set X associates some element from set Y.
In fact, it is necessary to check whether there is any element from the first set X for which there is no pair from set Y. If there is, then the correspondence is not is a display. If not, then it is a properly defined mapping.
Tell me how can this be done? Should I use arrays or something else? What is the verification algorithm?
I will be sincerely grateful!
Answer the question
In order to leave comments, you need to log in
Here is the Ruby code:
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'set'
def relation_is_func?(xset, yset, rset)
x_is_correct = (rset.map(&:keys).flatten - xset.to_a).empty?
y_is_correct = (rset.map(&:values).flatten - yset.to_a).empty?
r_is_correct = rset.map(&:keys).flatten.sort == xset.to_a.sort
x_is_correct && y_is_correct && r_is_correct ? 'Function.' : 'Not function.'
end
x = Set[1, 2, 3, 4]
y = Set['a', 'b', 'c', 'd', 'e']
r = Set[{ 2 => 'b' }, { 1 => 'b' }, { 3 => 'b' }, { 4 => 'a' }]
relation_is_func?(x, y, r) #=> "Function."
x = Set[1, 2, 3, 4]
y = Set['a', 'b', 'c', 'd', 'e']
r = Set[{ 1 => 'b' }, { 2 => 'b' }, { 3 => 'b' }, { 4 => 'b' }, { 2 => 'c' }]
relation_is_func?(x, y, r) #=> "Not function."
x = Set[1, 2, 3, 4]
y = Set['a', 'b', 'c', 'd', 'e']
r = Set[{ 1 => 'c' }, { 2 => 'a' }, { 4 => 'b' }]
relation_is_func?(x, y, r) #=> "Not function."
irb test.rb
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question