I have obtained the set of odd nodes of a graph and generated all its subsets. Now I want to separate those subsets whose size is odd.
I would appreciate it if you could help me :)
There are two solutions in my mind, the first one works correctly, but I have to add a null collection. And the second solution, I don't know how to write it correctly
range SS=1..ftoi(2^n_odd-1);
{int} Sub_odd[s in SS] = {item(odd_nodes,i-1) | i in 1..n_odd : (s div ftoi(2^(i-1))) mod 2 == 1};
{int} Sub_odd_odd[s in SS] = card(Sub_odd[s]) mod 2 ==1? Sub_odd[s]:{} ;
{int} Sub_odd_odd = union(Sub_odd[s] | s in SS : card(Sub_odd[s]) mod 2 ==1 );
If you consider the powerset example you can filter and keep the odd instances:
{string} s={"A","B","C","D"};
range r=1.. ftoi(pow(2,card(s)));
{string} s2 [k in r] = {i | i in s: ((k div (ftoi(pow(2,(ord(s,i))))) mod 2) == 1)};
{int} subr={i| i in r:card(s2[i]) mod 2==1};
{string} subs2[i in subr]=s2[i];
execute
{
writeln(s2);
writeln(subs2);
}
which gives
[{"A"} {"B"} {"A" "B"} {"C"} {"A" "C"} {"B" "C"} {"A" "B" "C"} {"D"} {"A" "D"}
{"B" "D"} {"A" "B" "D"} {"C" "D"} {"A" "C" "D"} {"B" "C" "D"} {"A"
"B" "C" "D"} {}]
[{"A"} {"B"} {"C"} {"A" "B" "C"} {"D"} {"A" "B" "D"} {"A" "C" "D"} {"B" "C"
"D"}]
Related
How can one get all the keys of a dictionary as a separate array in Julia.
For example:
Dict("a" => 123, "b" => 456, "c" => 789)
would give the following Array:
["a", "b", "c"]
Here is how you can do it (if an iterator is enough for you just use keys to avoid materializing the array):
julia> d = Dict("a" => 123, "b" => 456, "c" => 789)
Dict{String, Int64} with 3 entries:
"c" => 789
"b" => 456
"a" => 123
julia> keys(d)
KeySet for a Dict{String, Int64} with 3 entries. Keys:
"c"
"b"
"a"
julia> collect(keys(d))
3-element Vector{String}:
"c"
"b"
"a"
let items: [String] = ["A", "B", "A", "C", "A", "D"]
items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]
Does Swift 3 support a function like whatFunction(_: Element)?
If not, what is the most efficient logic?
You can filter the indices of the array directly, it avoids the extra mapping.
let items = ["A", "B", "A", "C", "A", "D"]
let filteredIndices = items.indices.filter {items[$0] == "A"}
or as Array extension:
extension Array where Element: Equatable {
func whatFunction(_ value : Element) -> [Int] {
return self.indices.filter {self[$0] == value}
}
}
items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]
or still more generic
extension Collection where Element: Equatable {
func whatFunction(_ value : Element) -> [Index] {
return self.indices.filter {self[$0] == value}
}
}
You can create your own extension for arrays.
extension Array where Element: Equatable {
func indexes(of element: Element) -> [Int] {
return self.enumerated().filter({ element == $0.element }).map({ $0.offset })
}
}
You can simply call it like this
items.indexes(of: "A") // [0, 2, 4]
items.indexes(of: "B") // [1]
You can achieve this by chain of:
enumerated() - add indexes;
filter() out unnecessary items;
map() our indexes.
Example (works in Swift 3 - Swift 4.x):
let items: [String] = ["A", "B", "A", "C", "A", "D"]
print(items.enumerated().filter({ $0.element == "A" }).map({ $0.offset })) // -> [0, 2, 4]
Another way is using flatMap, which allows you to check the element and return index if needed in one closure.
Example (works in Swift 3 - Swift 4.0):
print(items.enumerated().flatMap { $0.element == "A" ? $0.offset : nil }) // -> [0, 2, 4]
But since Swift 4.1 flatMap that can return non-nil objects become deprecated and instead you should use compactMap.
Example (works since Swift 4.1):
print(items.enumerated().compactMap { $0.element == "A" ? $0.offset : nil }) // -> [0, 2, 4]
And the cleanest and the most memory-cheap way is to iterate through array indices and check if element of array at current index equals to required element.
Example (works in Swift 3 - Swift 5.x):
print(items.indices.filter({ items[$0] == "A" })) // -> [0, 2, 4]
In Swift 3 and Swift 4 you can do that:
let items: [String] = ["A", "B", "A", "C", "A", "D"]
extension Array where Element: Equatable {
func indexes(of item: Element) -> [Int] {
return enumerated().compactMap { $0.element == item ? $0.offset : nil }
}
}
items.indexes(of: "A")
I hope my answer was helpful 😊
you can use it like that :
let items: [String] = ["A", "B", "A", "C", "A", "D"]
let indexes = items.enumerated().filter {
$0.element == "A"
}.map{$0.offset}
print(indexes)
just copy and paste
extension Array {
func whatFunction(_ ids : String) -> [Int] {
var mutableArr = [Int]()
for i in 0..<self.count {
if ((self[i] as! String) == ids) {
mutableArr.append(i)
}
}
return mutableArr
}
}
You can use that below code:
var firstArray = ["k","d","r","r","p","k","b","p","k","k"]
var secondArray = ["k","d","r","s","d","r","b","c"]
let filterArray = firstArray.filter { secondArray.contains($0) }
let filterArray1 = firstArray.filter { !secondArray.contains($0) }
let filterIndex = firstArray.enumerated().filter { $0.element == "k" }.map { $0.offset }
print(filterArray) --> // ["k", "d", "r", "r", "k", "b", "k", "k"]
print(filterArray1) --> // ["p", "p"]
print(filterIndex) --> // [0, 5, 8, 9]
this can be a way too
// MARK: - ZIP: Dictionary like
let words = ["One", "Two", "Three", "Four"]
let numbers = 1...words.count
for (word, number) in zip(words, numbers) {
print("\n\(word): \(number)")
}
For example finding the indices of p_last values that are in inds1 array: (swift 4+)
let p_last = [51,42]
let inds1 = [1,3,51,42,4]
let idx1 = Array(inds1.filter{ p_last.contains($0) }.indices)
idx1 = [0,1]
I'm new in Ruby. I have two arrays of hashes
arr1 = [{"one"=> {"1"=> "a", "2" => "b"}, "two" => {"3" => "n", "5" => "h", "7" => "k"}]
arr2 = [{"one"=> {"8"=> "f", "11" => "r"}, "two" => {"7" => "o", "6" => "b", "14" => "b"}]
and I want to have one array like this:
arr3 = [{
"one"=> {"1"=> "a", "2" => "b", "8"=> "f", "11" => "r"},
"two" => {3" => 'n", "5" => "h", "7" => "k", 7" => 'o", "6" => "b", "14" => "b"}
]
so I want to merge hashes by keys and "add" their values. Can anyone help?
arr1 = [{"one"=>{"1"=>"a", "2"=>"b"}, "two"=>{"3"=>"n", "5"=>"h", "7"=>"k"}}]
arr2 = [{"one"=>{"8"=>"f", "11"=>"r"}, "two"=>{"7"=>"o", "6"=>"b", "14"=>"b"}}]
(arr1+arr2).each_with_object({}) { |g,h| h.update(g) { |_,o,n| o.merge(n) } }
# => {"one"=>{"1"=>"a", "2"=>"b", "8"=>"f", "11"=>"r"},
# "two"=>{"3"=>"n", "5"=>"h", "7"=>"o", "6"=>"b", "14"=>"b"}}
This uses the form of Hash#update (aka merge!) that uses a block ({ |_k,o,n| o.merge(n) }) to determine the value of the key _k when both hashes being merged have that key. (_ in _k tells the reader that that block variable is not used in the block calculation.) o and n are the values of that key in h and g respectively.
For each key k equal to "one" or "two", if the values (hashes) of arr1.first[k] and arr2.first[k] have a common key l, the merge operation will cause the value of l in arr1 will be overwritten by the value of l in arr2. If, for example, arr1.first["one"] #=> {"1"=>"a", "2"=>"b"} and arr2.first["one"] #=> {"8"=>"f", "2"=>"r"}, the merge will return {"1"=>"a", "2"=>"r", "8"=>"f"}
Even though arr1 and arr2 each contain a single element (a hash), the code above works fine when the arrays contain multiple hashes, and when there are more than two arrays. If the arrays always contain a single hash, the arrays serve no purpose and we might instead just reference the hashes:
h1 = {"one"=>{"1"=>"a", "2"=>"b"}, "two"=>{"3"=>"n", "5"=>"h", "7"=>"k"}}
h2 = {"one"=>{"8"=>"f", "11"=>"r"}, "two"=>{"7"=>"o", "6"=>"b", "14"=>"b"}}
and replace arr1+arr2 with [h1+h2].
Maybe not the most elegant but this works:
arr1 = [{"one"=>{"1"=>"a", "2"=>"b"}, "two"=>{"3"=>"n", "5"=>"h", "7"=>"k"}}]
arr2 = [{"one"=>{"8"=>"f", "11"=>"r"}, "two"=>{"7"=>"o", "6"=>"b", "14"=>"b"}}]
arr3 = []
arr1[0].each_key{|k| arr3<< {k => arr1[0][k].merge(arr2[0][k])}}
arr3
If you don't know how many hashes your original array will contain, simply replace arr1[0].each_key with arr1.each_index{|i| arr1[i].each_key and replace 0 with i in the merge.
I'm using Ruby 2.4. I know how to find all the indexes in an array of elements matching a condition ...
arr.each_index.select{|i| arr[i] == 'x'}
but how do I find the index of the first element that matches a condition starting from a particular position in teh array? So what if I wanted to find a string with only a single character at or after index = 2? (If tehre are less than 2 elements the operation can return nil). So for example, if I have
["abc", "d", "efg", "h", "abcde"]
the operation would return "3", since element "h" is at position 3, only has a single character and is at or after index 2.
Using select would return all values where the block returns true for example:
p arr = ["abc", "d", "efg", "h", "abcde", "k"]
# => ["abc", "d", "efg", "h", "abcde", "k"]
p arr.each_index.select{|i| i >= 2 and arr[i].length == 1}
# => [3, 5]
Instead use detect if you want to return only the first value where the block returns true:
p arr = ["abc", "d", "efg", "h", "abcde", "k"]
# => ["abc", "d", "efg", "h", "abcde", "k"]
p arr.each_index.detect{|i| i >= 2 and arr[i].length == 1}
# => 3
Use Array#index with with_index:
arr = ["abc", "d", "efg", "h", "abcde"]
arr.index.with_index { |el, idx| el.length == 1 && idx > 2 }
=> 3
arr = ["abc", "d"]
arr.index.with_index { |el, idx| el.length == 1 && idx > 2 }
=> nil
def first_index_after(arr, min_ndx)
min_ndx.upto(arr.size-1).find { |i| yield(arr[i]) }
end
arr = ["abcdef", "h", "efgh", "h", "abcde", "h"]
min_ndx = 2
first_index_after(arr, min_ndx) { |e| e == "h" } #=> 3
first_index_after(arr, min_ndx) { |e| e =~ /\Ah\z/ } #=> 3
first_index_after(arr, min_ndx) { |e| e =~ /h/ } #=> 2
first_index_after(arr, min_ndx) { |e| e.size > 4 } #=> 4
first_index_after(arr, min_ndx) { |e| e == 'cat' } #=> nil
This assumes 0 <= min_ndx < arr.size. It may be desirable to add a first line to the method that returns nil or raises an exception if this requirement is not satisfied.
I have this nested array:
array = [
["A", "X"],
["B", "Y"],
["C", "Z"]
]
Is there a function that returns "B" when I provide "Y" and "C" when I provide "Z"?
rassoc might be what you need.
array.rassoc("Y") would return ["B", "Y"] and you can use first to get only the "B".
You can use find method.
array = [
["A", "X"],
["B", "Y"],
["C", "Z"]
]
str = "Y"
arr = array.find{|a| a[1] == str}
puts arr[0] if arr
# => B
Or, you can convert it to a Hash, if you need to do many lookups and the array is biggish:
hash = array.map(&:reverse).to_h
hash["Y"]
# => "B"
There is no such internal function out of the box, but one might easily create one:
▶ λ = ->(input) { array.detect { |e| e.last == input }.first rescue nil }
#⇒ #<Proc:0x0000000437f150#(pry):10 (lambda)>
▶ λ.('X')
#⇒ "A"
▶ λ.('Y')
#⇒ "B"
▶ λ.('QQQ')
#⇒ nil