A
A
Alexander2020-11-08 14:37:24
Mathematics
Alexander, 2020-11-08 14:37:24

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

1 answer(s)
A
AVKor, 2020-11-09
@AVKor

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."

Notes:
  1. I didn’t bother with data entry, I just hardcoded three examples.
  2. You can implement ordered pairs in many ways, I used hashes. It could have been implemented in a different way (Struct, for example).
  3. For sets, I used Set.
  4. Checking the correctness of input data is implemented partially. You might want to add something.
  5. In examples: x - set X; y - set Y; r is the relation between X and Y (which needs to be tested to be a function).
  6. You can run it like this: save it to a file, say, test.rb and run the command in the terminal:irb test.rb

Do it yourself in C++.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question