Combining a set of reversable paths - arrays

I need some help recognizing this problem and finding a solution. I don't need someone to code the solution, just to say how to go about solving it.
An array of hashes, each hash containing one path, its ID, and its order (forward (F) or reverse (R))
Each path is initialized in the F position
my #paths = (
{ id => 1, path => [ A, B ], order => 'F' },
{ id => 2, path => [ C, D, E ], order => 'F' },
{ id => 3, path => [ E, B ], order => 'F' }
);
Each node or vertex of each path also has an orientation ( + or - )
my %plus_minus;
$plus_minus{1}{A} = '+';
$plus_minus{1}{B} = '+';
$plus_minus{2}{C} = '+';
$plus_minus{2}{D} = '-';
$plus_minus{2}{E} = '-';
$plus_minus{3}{E} = '-';
$plus_minus{3}{B} = '-';
You can reverse the order of a path ( e.g., [A, B] to [B, A] )
When you reverse order from F => R or R => F you also switch the orientation of each node in the path from + to - or - to +
The paths with orientations look like this:
A+ : B+
C+ : D- : E-
E- : B-
This is the problem input
For output, I'd like to know whether or not it is possible by reversing path orders to create a consensus path, and also what is the way to do this such that you are guaranteed to find the consensus path.
For example, if we reversed path 1 we'd get:
B- : A-
C+ : D- : E-
E- : B-
and the resulting consensus path would be:
C+ : D- : E- : B- : A-
But it's not clear to reverse path 1 first. For example, what if we reverse 3 first? So you can't proceed randomly.
Does anyone recognize this problem or know how to solve it?

What you're asking for isn't easy, and I'm not exactly clear about your requirements
This partial solution takes the brute-force approach of creating a directed graph, adding all the paths from your data and their reversals, and finding the longest path in the resulting data structure
Using your sample data, it produces the reverse of the consensus path that you expect, but according to your rules there will always be two equally valid answers if there are any at all, and because of the random nature of Perl hashes, either one may be presented as the result from one run to the next
If I have understood you correctly then you also need to ensure that the result contains all of the paths in the original data
use strict;
use warnings 'all';
use feature 'say';
use Graph::Directed;
use List::Util 'max';
use List::MoreUtils 'first_index';
my #paths = (
{ id => 1, path => [ qw[ A B ] ], order => 'F' },
{ id => 2, path => [ qw[ C D E ] ], order => 'F' },
{ id => 3, path => [ qw[ E B ] ], order => 'F' },
);
my %plus_minus;
$plus_minus{1}{A} = '+';
$plus_minus{1}{B} = '+';
$plus_minus{2}{C} = '+';
$plus_minus{2}{D} = '-';
$plus_minus{2}{E} = '-';
$plus_minus{3}{E} = '-';
$plus_minus{3}{B} = '-';
# index the array by ID
#
my %paths;
$paths{$_->{id}} = $_ for #paths;
# Incorporate the inexplicably separate plus-minus data
#
for my $id ( keys %plus_minus ) {
my $nodes = $plus_minus{$id};
for my $node ( keys %$nodes ) {
my $sign = $nodes->{$node};
my $nodes = $paths{$id}{path};
my $i = first_index { $_ eq $node } #$nodes;
die sprintf "Node $node not found in path ID $id" if $i < 0;
$nodes->[$i] .= $sign;
}
}
# Add the reverse paths to the hash:
# - Change the `order` field to `R` (original is reliably `F`)
# - Reverse the order of the elements of `path`
# - Reverse the sign of the elements of `path`
#
my $n = max map { $_->{id} } values %paths;
for my $path ( #paths ) {
my $nodes = $path->{path};
my $new_id = ++$n;
$paths{$new_id} = {
id => $new_id,
order => 'R',
path => [
map {
s/([+-])/ $1 eq '+' ? '-' : '+' /er or die;
} reverse #$nodes
],
};
}
# Build the directed graph
#
my $g = Graph::Directed->new;
for my $path ( values %paths ) {
my $nodes = $path->{path};
for my $i ( 0 .. $#$nodes - 1 ) {
$g->add_edge(#{$nodes}[$i, $i+1]);
}
}
# Report the longest path
#
say join ' : ', $g->longest_path;
output
C+ : D- : E- : B- : A-

Related

Ruby Iterating over an array and find match in an hash and replace the element in array

I would like someone to clarify how can I possibly iterating over an array, find an exact match in an hash[value], and replace the element in the array with the hash[key].
As example, if I have a morse directory morse_dict = {
"a" => ".-","b" => "-...","c" => "-.-.","d" => "-..","e" => ".","f" => "..-.","g" => "--.","h" => "....","i" => "..","j" => ".---","k" => "-.-","l" => ".-..","m" => "--","n" => "-.","o" => "---","p" => ".--.","q" => "--.-","r" => ".-.","s" => "...","t" => "-","u" => "..-","v" => "...-","w" => ".--","x" => "-..-","y" => "-.--","z" => "--.."," " => " ","1" => ".----","2" => "..---","3" => "...--","4" => "....-","5" => ".....","6" => "-....","7" => "--...","8" => "---..","9" => "----.","0" => "-----"
}
and I want a method that for a given string in morse code returns a string in regular alphabet.
This is the codewars kata.
I am not interested in the solution to the challenge itself, I would like to understand the principle of this.
So far I have thought of proceeding this way:
def morse_code(arr)
arr.split(" ").each {|element|
element.each_char {|char|
(morse_dict.include?(char)) ? (print "true") : (print "false")}
}
end
I only print false, which means that I am not actually looking for match into the hash.
Using Hash#key without replacing the array, rather creating a new one (use map! for replacement):
array = [1,2,3,4,5]
hash = {a: 4, b: 7, c: 3}
array.map { |el| hash.key(el) }
# => [nil, nil, :c, :a, nil]
You may want to think about using Hash#invert and simply referencing the elements by keys for performance reasons as Hash#key is O(n) while Hash#[] is O(1).
array = [1,2,3,4,5]
hash = {a: 4, b: 7, c: 3}
inverted_hash = hash.invert
array.map { |el| inverted_hash[el] }
# => [nil, nil, :c, :a, nil]
I understand from the kata that letters are to be separated by one space and words by three spaces.
As a first step I will two changes to the hash morse_dict: remove the key ' '; and add key-value pairs for some punctuation characters. The space character key is not needed; the need for punctuation codes is discussed in the kata.
PUNCTUATION = { "."=>".-.-.-", ","=>"--..--", "?"=>"..--..", "!"=>"-.-.--" }
ALPHA_TO_MORSE = dict.reject { |k,_| k == " " }.merge(PUNCTUATION)
#=> {"a"=>".-", "b"=>"-...", "c"=>"-.-.", "d"=>"-..", "e"=>".", "f"=>"..-.",
# "g"=>"--.", "h"=>"....", "i"=>"..", "j"=>".---", "k"=>"-.-", "l"=>".-..",
# "m"=>"--", "n"=>"-.", "o"=>"---", "p"=>".--.", "q"=>"--.-", "r"=>".-.",
# "s"=>"...", "t"=>"-", "u"=>"..-", "v"=>"...-", "w"=>".--", "x"=>"-..-",
# "y"=>"-.--", "z"=>"--..", "1"=>".----", "2"=>"..---", "3"=>"...--",
# "4"=>"....-", "5"=>".....", "6"=>"-....", "7"=>"--...", "8"=>"---..",
# "9"=>"----.", "0"=>"-----", "."=>".-.-.-", ","=>"--..--", "?"=>"..--..",
# "!"=>"-.-.--"}
I obtained the Morse codes for the punctuation characters from the Morse Code Wiki. Additional punctuation characters could be added if desired.
The hash ALPHA_TO_MORSE is used in encoding text. The inverse of this hash is needed for decoding messages in Morse code. Also needed for decoding is the key value pair "...---..."=>"sos".
MORSE_TO_ALPHA = ALPHA_TO_MORSE.invert.merge("...---..."=>"sos")
#=> {".-"=>"a", "-..."=>"b", "-.-."=>"c", "-.."=>"d", "."=>"e", "..-."=>"f",
# "--."=>"g", "...."=>"h", ".."=>"i", ".---"=>"j", "-.-"=>"k", ".-.."=>"l",
# "--"=>"m", "-."=>"n", "---"=>"o", ".--."=>"p", "--.-"=>"q", ".-."=>"r",
# "..."=>"s", "-"=>"t", "..-"=>"u", "...-"=>"v", ".--"=>"w", "-..-"=>"x",
# "-.--"=>"y", "--.."=>"z", ".----"=>"1", "..---"=>"2", "...--"=>"3",
# "....-"=>"4", "....."=>"5", "-...."=>"6", "--..."=>"7", "---.."=>"8",
# "----."=>"9", "-----"=>"0", ".-.-.-"=>".", "--..--"=>",",
# "..--.."=>"?", "-.-.--"=>"!""...---..."=>"sos"}
One more hash is needed to deal with cases where the message "sos" (or "SOS"--Morse code is case insensitive), or "sos" followed by a punctuation character (e.g., "sos!") is to be encoded.1 See the Wiki.
SOS_WITH_PUNCTUATION = PUNCTUATION.each_with_object({}) { |(k,v),h|
h["sos#{k}"] = "...---... #{v}" }.merge('sos'=>"...---...")
#=> {"sos."=>"...---... .-.-.-", "sos,"=>"...---... --..--",
# "sos?"=>"...---... ..--..", "sos!"=>"...---... -.-.--", "sos"=>"...---..."}
The encoding and decoding methods follow. encode checks to see if each word in the string is a key in the hash SOS_WITH_PUNCTUATION. If it is, the value of key is the Morse code for the word; else, the word is divided into letters and each letter is translated into Morse code.
def encode(str)
str.strip.downcase.split.map do |word|
if SOS_WITH_PUNCTUATION.key?(word)
SOS_WITH_PUNCTUATION[word]
else
word.each_char.map { |c| ALPHA_TO_MORSE[c] }.join(' ')
end
end.join (' ')
end
def decode(morse)
morse.strip.split(/ {3}/).map do |word|
word.split.map { |c| MORSE_TO_ALPHA[c] }.join
end.join(' ')
end
We can now try out these two methods.
str = " Is now the time for you, and 007, to send an SOS?"
morse = encode str
#=> ".. ... -. --- .-- - .... . - .. -- . ..-. --- .-. -.-- --- ..- --..-- .- -. -.. ----- ----- --... --..-- - --- ... . -. -.. .- -. ...---... ..--.."
decode morse
#=> "is now the time for you, and 007, to send an sos?"
1 It would be simpler to have a pre-processing step that would convert, say, "sos." to "sos .", but when the resulting Morse code were decoded there would be a space between "sos" and ".". I suppose that cryptographers could deal with that, but I've chosen to avoid the insertion of the space.
assuming: arr = 'a b c d', which is not an arr, so please make that morse_string
def morse_code(morse_string)
new_elements = []
# iterate over each character in the string,
morse_string.split(" ").each do |element|
if morse_dict[element]
# https://apidock.com/ruby/Array/push
new_elements.push( morse_dict[element] )
else
# whatever you want to do when there is no match
end
end
# re-create the string again, but with braille
# https://apidock.com/ruby/Array/join
new_elements.join(' ')
end
morse_string = 'a b c d'
morse_code(morse_string)

Perl: array and hash

Further to finding an answer to my earlier question Perl: slicing an array of hashes, I am stuck again and unable to see what I have done wrong.
What I have is
Array( Array0(Hash0,Hash1),Array1(Hash0,Hash1),Array2(Hash0,Hash1)...)
use strict;
use warnings;
my #DDs = ();
my #Ds = ();
my %hsh = ();
my %dot1 = ( 'x' => 1, 'y' => 2, 'r' => 3 );
my %dot2 = ( 'x' => 4, 'y' => 5, 'r' => 6 );
my %dot3 = ( 'x' => 7, 'y' => 8, 'r' => 9 );
my %dot4 = ( 'x' => 1.1, 'y' => 1.2, 'r' => 1.3 );
my %dot5 = ( 'x' => 2.1, 'y' => 2.2, 'r' => 2.3 );
my %dot6 = ( 'x' => 3.1, 'y' => 3.2, 'r' => 3.3 );
my %dot7 = ( 'x' => 4.1, 'y' => 4.2, 'r' => 4.3 );
my %dot8 = ( 'x' => 5.1, 'y' => 5.2, 'r' => 5.3 );
my #dotsA = ( \%dot1, \%dot2 );
my #dotsB = ( \%dot3, \%dot4 );
my #dotsC = ( \%dot5, \%dot6 );
my #dotsD = ( \%dot7, \%dot8 );
my %Ds = ( \#dotsA, \#dotsB, \#dotsC, \#dotsD );
#DDs = $Ds[1]; #expect #dotsB with scalar of 2
###"Can't use an undefined value as HASH reference" error here
%hsh = %{ $DDs[0] }; #expect %dot3
print scalar #DDs, "\n"; #expect 2 but has value of 1
print $hsh{'x'}, "\n";
Reference found where even-sized list expected at /Users/schwern/tmp/test.plx line 10.
Line 10 is this:
my %dot1 = {'x'=>1,'y'=>2,'r'=>3};
This is Perl's cryptic way of saying you fed a hash reference to a hash. Perl, unfortunately, distinguishes very strongly between things and references to that thing.
%dot1 is a hash. It takes a list and turns it into a hash. A list like ( x => 1, y => 2, r => 3). { x => 1, y => 2, r => 3 } creates a hash reference. That's a single thing, a scalar. It's like saying my %dot1 = (42). It doesn't make any sense.
%dot1 is a hash, it wants a list like (x => 1, y => 2)
$dot1 is a scalar, it can store a hash reference like { x => 1, y => 2 }.
my %Ds = (\#dotsA,\#dotsB,\#dotsC,\#dotsD);
A hash requires a key and a value, pairs. last_name => "Schwern". When you give it a bunch of array references like that, it will read them as key1, value1, key2, value2... but what is it using as the key? It's using the stringification of that reference, something like ARRAY(0x7fb721800468).
If you asked for $D{\#dotsA} you'll get back a reference to #dotsB. You will not be able to get #dotsA back, a Perl hash key is just a string, not a reference.
This isn't a very good way to store an array in a hash. I'm not sure what you're trying to accomplish, but you probably want to reference them by name.
# A hash of lists.
my %Ds = ( A => \#dotsA, B => \#dotsB, C => \#dotsC, D => \#dotsD );
# Get back a reference to #dotsA.
my $dotsA = $Ds{A};
But looking at the following code, #DDs = $Ds[1];, I think you meant to initialize #Ds instead of %Ds.
#Ds = (\#dotsA,\#dotsB,\#dotsC,\#dotsD);
And now the following works... sort of. More later.
#DDs = $Ds[1]; #expect #dotsB with scalar of 2
Unlike in PHP, hashes and arrays are totally different things. my #Ds and my %Ds declare totally different variables. It doesn't help that you access them both with $Ds. In Perl5, the sigil indicates what's going to get returned. $Ds[1] and $Ds{foo} both use $Ds because they're returning a scalar. #Ds[1,2] and #Ds{(foo, bar)} use #Ds because they're returning a list (known as a slice). Confusing, but that's how it works.
#DDs = $Ds[1]; #expect #dotsB with scalar of 2
You're not getting #dotsB, you're getting a reference to #dotsB. All complex data structures in Perl store references, not the actual value. This is like $DDs[0] = \#dotsB. If you want to get the actual value you have to dereference it.
#DDs = #{$Ds[1]}; # Now #DDs has a copy of #dotsB
And finally it works.
#!/usr/bin/perl
use strict;
use warnings;
use v5.10; # for say()
my %dot1 = ('x'=>1,'y'=>2,'r'=>3);
my %dot2 = ('x'=>4,'y'=>5,'r'=>6);
my %dot3 = ('x'=>7,'y'=>8,'r'=>9);
my %dot4 = ('x'=>1.1,'y'=>1.2,'r'=>1.3);
my %dot5 = ('x'=>2.1,'y'=>2.2,'r'=>2.3);
my %dot6 = ('x'=>3.1,'y'=>3.2,'r'=>3.3);
my %dot7 = ('x'=>4.1,'y'=>4.2,'r'=>4.3);
my %dot8 = ('x'=>5.1,'y'=>5.2,'r'=>5.3);
my #dotsA = (\%dot1,\%dot2);
my #dotsB = (\%dot3,\%dot4);
my #dotsC = (\%dot5,\%dot6);
my #dotsD = (\%dot7,\%dot8);
my #Ds = (\#dotsA,\#dotsB,\#dotsC,\#dotsD);
my #DDs = #{$Ds[1]}; #expect #dotsB
my %hsh = %{$DDs[0]}; #expect %dot3
say scalar #DDs; #expect 2
say $hsh{'x'};
I would also advise that you get comfortable working directly with references since that's what complex data structures are: references. Converting back and forth from references to values is confusing. Working with references is one less thing to convert in your code, in your head, and less copying done in your program.
#!/usr/bin/perl
use strict;
use warnings;
use v5.10; # for say()
my $dot1 = {'x'=>1,'y'=>2,'r'=>3};
my $dot2 = {'x'=>4,'y'=>5,'r'=>6};
my $dot3 = {'x'=>7,'y'=>8,'r'=>9};
my $dot4 = {'x'=>1.1,'y'=>1.2,'r'=>1.3};
my $dot5 = {'x'=>2.1,'y'=>2.2,'r'=>2.3};
my $dot6 = {'x'=>3.1,'y'=>3.2,'r'=>3.3};
my $dot7 = {'x'=>4.1,'y'=>4.2,'r'=>4.3};
my $dot8 = {'x'=>5.1,'y'=>5.2,'r'=>5.3};
my $dotsA = [$dot1,$dot2];
my $dotsB = [$dot3,$dot4];
my $dotsC = [$dot5,$dot6];
my $dotsD = [$dot7,$dot8];
my $Ds = [$dotsA,$dotsB,$dotsC,$dotsD];
my $DDs = $Ds->[1]; #expect $dotsB
my $hsh = $DDs->[0]; #expect $dot3
say scalar #$DDs; #expect 2
say $hsh->{'x'};
You should review perlreftut and the Nested Data Structures chapter of Modern Perl.

Perl: using variable as an array element to divide major array into smaller arrays

I have a major array #major that I want to divide in a given number of minors arrays #minor , by setting the number of slices I want (let's say 4 here, but I wish to be able to chose whatever number I want), like this pseudo-code:
(I know it's not correct, but it sort of gives you the idea)
#major = A,B,C,D,E,F,G,H,I,J
$slice = 4;
$arraySize = $#array + 1;
$slicesize = $arraySize / $slice;
#minor1 = #major[0..$slicesize]
#minor2 = #major[($slicesize+1)..(2*$slicesize)]
#minor3 = #major[((2*$slicesize)+1)..(3*$slicesize)]
#minor4 = #major[((3*$slicesize)+1)..(4*$slicesize)]
The goal here is that I want to be able to change this size of the initial array #major and/or the number of slices $slice and that all values which set the size of the differents minor arrays (($slicesize+1), (2*$slicesize), and so on).
I know this looks a bit complex but I don't know to expose it in another way.
Do you have any idea about how to achieve this ?
I am not pretty sure you meant like this, but here it is how I understood your point:
#!/usr/bin/perl
use strict; use warnings; use 5.010;
my #array = ( 'A' .. 'Z' );
my $length_of_slice = $ARGV[0] || 5 ;
while ( #array ) {
local $" = ', ';
my #minor = splice #array, 0, $length_of_slice;
say "#minor";
}
When you have a complex data structure requirement, my first thought is - use an object. Perl supports object oriented programming, which allows you to do all manner of insanely complicated things like what you're trying to do.
It'd go something like this:
#!/usr/bin/perl
use strict;
use warnings;
package TestObject;
my #major = qw(A B C D E F G H I J );
sub new {
my ( $class, $slice_count ) = #_;
my $self = {};
if ( defined $slice_count ) { $self->{slice_count} = $slice_count }
$self->{major} = #major;
bless( $self, $class );
return $self;
}
sub get_slices {
my ( $self, $count ) = #_;
my #tmp = #major;
my #array_of_slices;
for ( 1 .. $count ) {
my $tmp_arr_ref = ();
for ( 0 .. ( #major / $count ) ) {
if ( #tmp ) { push( #$tmp_arr_ref, shift(#tmp) ) };
}
push( #array_of_slices, $tmp_arr_ref );
}
return (#array_of_slices);
}
Called by:
#!/usr/bin/perl
use strict;
use warnings;
use TestObject;
use Data::Dumper;
my $first = TestObject->new();
my #array_of_refs = $first->get_slices(4);
print Dumper \#array_of_refs;
And giving result of:
$VAR1 = [
[
'A',
'B',
'C'
],
[
'D',
'E',
'F'
],
[
'G',
'H',
'I'
],
[
'J'
]
];
Something like that (you'll have to adjust it a bit to get precisely what you have in mind depending on how you want to handle edge cases/rounding).

How to get the last element of an array and show the rest?

How do I get the last element of an array and show the rest of the elements?
Like this :
#myArray = (1,1,1,1,1,2);
Expected output :
SomeVariable1 = 11111
SomeVariable2 = 2
# print last element
print $myArray[-1];
# joined rest of the elements
print join "", #myArray[0 .. $#myArray-1] if #myArray >1;
If you don't mind modifying the array,
# print last element
print pop #myArray;
# joined rest of the elements
print join "", #myArray;
Сухой27 has given you the answer. I wanted to add that if you are creating a structured output, it might be nice to use a hash:
my #myArray = (1,1,1,1,1,2);
my %variables = (
SomeVariable1 => [ #myArray[0 .. $#myArray -1] ],
SomeVariable2 => [ $myArray[-1] ]
);
for my $key (keys %variables) {
print "$key => ",#{ $variables{$key} },"\n";
}
Output:
SomeVariable1 => 11111
SomeVariable2 => 2

Append data to new cell arrays using Token

I have a problem I couldnt solve it. I have a set of data present in lines (generally text that are organized in number of sentences)
Example of my text in sentence:
1. Hello, world, It, is, beautiful, to, see, you, all
2. ,Wishing, you, happy, day, ahead
I am using the strtok
[token remain] = strtok(remain, ', ');
% token = strtrim(token);
CellArray {NumberOFCells} = token(1:end) ;
NumberOFCells= NumberOFCells+1;
I am using the CellArray to store the Token into the cells however what my code does is it takes the first sentences and put into cells and once it iterates to the second sentence and it deletes the pre-assigned cells thus it replaces it with token of the second sentences.
Expected Output
[ nxn ] [ nxn ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] ......
'Hello' 'world' 'It' 'is' 'beautiful' 'to' see' 'you' 'all' 'Wishing' 'you' 'happy' 'day' 'ahead'
The question is how can I append the second sentence strings to the cells without clearing the pre-filled cells.
Thank you and looking forward to meet experts matlab programmer
My Code .. Ignore commented lines... Retrieved is basically in this form.
[Index,Retrieved] = system(['wn ' keyword type ]);
Retrieved;
arrowSymbol = ' => ';
CommaSymbol= ', '
NumberOfSense= 'Sense ';
% let's look for the lines with '=> ' only?
senses = regexp(Retrieved, [arrowSymbol '[\w, ]*\n '], 'match');
SplitIntoCell = regexp(senses, [CommaSymbol '[\w, ]*\n'], 'match');
% now, we take out the '=> ' symbol
for i = 1:size(senses, 2)
senses{i} = senses{i}(size(arrowSymbol,2):end);
SplitIntoCell{i}= SplitIntoCell{i}(size(CommaSymbol,2): end);
% SeperateCells= senses ([1:2 ; end-1:end]);
% SplitCellContentIntoSingleRows{i}= strtok (SeperateCells, ['\n' ])
numberCommas = size(regexp(senses{i}, CommaSymbol), 2);
remain = senses{i};
RestWord= SplitIntoCell{i};
NumberOFCells=1;
for j = 2:numberCommas + 1 + 1 % 1 for a word after last comma and 1 because starts at index 2
% RemoveCellComma= regexp (Conversion,',');
% CellArray = [CellArray strsplit(remain, ', ')];
% [str,~] = regexp(remain,'[^, \t]+', 'match', 'split');
% CellArray = [CellArray str];
% [token remain] = strtok(remain, ', ');
% token = strtrim(token);
% CellArray {NumberOFCells} = token(1:end) ;
%
% % CellArray =[CellArray strsplit(remain, ', ')]
% [str, ~]= regexp(remain,'[^, \t]+', 'match', 'split');
% CellArray = [CellArray str];
% NumberOFCells= NumberOFCells+1;
[token remain] = strtok(remain, ', ');
token = strtrim(token);
CellArray {NumberOFCells} = token;
NumberOFCells= NumberOFCells+1;
Retrieved=
cat, true cat
=> feline, felid
=> carnivore
=> placental, placental mammal, eutherian, eutherian mammal
=> mammal, mammalian
=> vertebrate, craniate
=> chordate
=> animal, animate being, beast, brute, creature, fauna
=> organism, being
=> living thing, animate thing
=> object, physical object
=> physical entity
=> entity
Your question is a little confusing, but reading it (and other comments) a couple of times, I think I understand what you're asking.
Eitan T is correct about using regexp for this, and when it comes to cell arrays, be careful of the difference in indexing/concatenation with [] and {}: see Combining Cell Arrays. Assuming your using a loop to go through each sentence, you can do something like:
CellArray = [CellArray strsplit(next_sentence, ', ')];
Using regexp (or it's case-insensitive alternative regexpi), try adding 'split' as another one of the function options, for example:
[str,~] = regexp(next_sentence,'[^, \t]+', 'match', 'split');
CellArray = [CellArray str];

Resources