Finding the length of 2D slices in go - arrays

I want to check if the matrices are of the same size: if both matrices have the same number of rows and the same number of columns.
matrix1 := [][]int{{1,2,3} ,{4,5,6}}
matrix2 := [][]int{{7,8,9}, {10,11,12}}
I get len(matrix1) == len(matrix2) == 2. Which is the correct number of rows.
How can I check the length of each row (i.e. the number of columns, which should be 3) if I'm declaring the matrices as shown above?

Note that since every "row" in a 2D slice may have arbitrary length, you should check the length of each of the corresponding rows (having the same index) if they are equal.
Here's a function that does that:
func match(m1, m2 [][]int) bool {
if len(m1) != len(m2) {
return false
}
for i, row1 := range m1 {
row2 := m2[i]
if len(row1) != len(row2) {
return false
}
}
return true
}
See usage examples:
m1 := [][]int{{1, 2, 3}, {4, 5, 6}}
m2 := [][]int{{7, 8, 9}, {10, 11, 12}}
fmt.Println(match(m1, m2))
m1 = [][]int{{1, 2, 3}, {4, 5, 6, 7, 8}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12, 12, 13}}
fmt.Println(match(m1, m2))
m1 = [][]int{{1, 2, 3}, {4, 5, 6, 7, 8}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12, 12}}
fmt.Println(match(m1, m2))
m1 = [][]int{{1, 2, 3}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12, 12}}
fmt.Println(match(m1, m2))
Output (as expected):
true
true
false
false
Simplification for Special case:
If you have guarantee that in all of your matrices all rows have the same length, you can make a big simplification: in this case if number of rows matches, it's enough to compare the length of one of the rows only from each matrices, practically the first row.
It could look like this:
func match2(m1, m2 [][]int) bool {
if len(m1) != len(m2) {
return false
}
return len(m1) == 0 || len(m1[0]) == len(m2[0])
}
Testing it:
m1 = [][]int{{1, 2, 3}, {4, 5, 6}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12}}
fmt.Println(match2(m1, m2))
m1 = [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12}}
fmt.Println(match2(m1, m2))
Output:
true
false
Try these on the Go Playground.

Related

Output all the elements of every group with minimal count

Given an array of array: S = {s1, s2, ... , sn}, where si = {i1, i2, ..., im} and every element in array si is the integer from 1 to n with m ≤ n/2. For example, S = {{1, 2, 3}, {1, 3, 4}, {2, 5, 6}, {4, 5, 6}}, where m = 3 and n = 6.
If for any element si, sj in S they are disjoint with |si| + |sj| ≤ n, we say si and sj are in the same group g.
Question: For a given array S, I wonder if there is an efficient algorithm to output the group with minimal count. Still the example mentioned previously:
INPUT: S = {{1, 2, 3}, {1, 3, 4}, {2, 5, 6}, {4, 5, 6}}
OUTPUT:G1 = {{1, 2, 3}, {4, 5, 6}}, G2 = {{1, 3, 4}, {2, 5, 6}}, GroupCount = 2
The only method I can figure out is BF, I hope anyone can give an answer to this question or give some materials about this.

np.nditer doesn't assign values when iterates over subarray

Main array doesn't update values during assigning method inside np.nditer when iterative array is used as subarray
array = np.arange(20)
with np.nditer(array[np.nonzero(array)],
op_flags=['readwrite']) as it:
for x in it:
x[...] = 5
array
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
Subarray assigns great without np.nditer
array[np.nonzero(array)] = 5
array
array([0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5])
There is a workaround over by using temporary array.
tmp_array = array[np.nonzero(array)]
array = np.arange(20)
with np.nditer(tmp_array,
op_flags=['readwrite']) as it:
for x in it:
x[...] = 5
array[np.nonzero(array)] = tmp_array
array
array([0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5])
Why main array doesn't update values when np.nditer uses subarray assignments?
Is there a more convenient way to workaround when subarray assigning in np.nditer happens?
In [48]: arr = np.arange(20)
...: with np.nditer(arr[np.nonzero(arr)],
...: op_flags=['readwrite']) as it:
...: for x in it:
...: x[...] = 5
...: arr
Out[48]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19])
This doesn't change arr because it isn't iterating on arr. Instead it is doing:
In [49]: arr = np.arange(20)
...: arr1 = arr[np.nonzero(arr)]
...: with np.nditer(arr1,
...: op_flags=['readwrite']) as it:
...: for x in it:
...: x[...] = 5
...: arr1
Out[49]: array([5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5])
In [50]: _.shape
Out[50]: (19,)
arr1 isn't a view of arr, it is selection, a new array without shared data buffer.
If you want to modify arr, you have to iterate on it, not a copy. Do the test, or anything fancy, inside the loop.
In [51]: arr = np.arange(20)
...: with np.nditer(arr,
...: op_flags=['readwrite']) as it:
...: for x in it:
...: if x > 0:
...: x[...] = 5
...: arr
Out[51]: array([0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5])
But why are you using nditer? You already know how to do this kind of selective assignment, using the non-iterative methods:
array[np.nonzero(array)] = 5
In this case the assignment = immediately follows the advanced indexing, and Python uses array.__setitem__ rather than arr.__getitem__.
Iterating on a slice, a view does change the source:
In [52]: arr = np.arange(20)
...: with np.nditer(arr[5:],
...: op_flags=['readwrite']) as it:
...: for x in it:
...: x[...] = 5
...: arr
Out[52]: array([0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5])

Find a sequence of integers in a given array

I would like to know if there is a better way (in the case my implementation is correct) to find a sub-sequence of integers in a given array. I have implemented the solution using golang (if this is an impediment for a review I could use a different language). If I am not mistaken the bellow implementation is close to O(b).
package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
r := match(a, b)
fmt.Println("Match found for case 1: ", r)
a = []int{1, 2, 3}
b = []int{4, 5, 6, 7, 8, 9}
r = match(a, b)
fmt.Println("Match found for case 2: ", r)
a = []int{1, 2, 3}
b = []int{1, 5, 3, 7, 8, 9}
r = match(a, b)
fmt.Println("Match found for case 3: ", r)
a = []int{1, 2, 3}
b = []int{4, 5, 1, 7, 3, 9}
r = match(a, b)
fmt.Println("Match found for case 4: ", r)
a = []int{1, 2, 3}
b = []int{4, 5, 6, 1, 2, 3}
r = match(a, b)
fmt.Println("Match found for case 5: ", r)
a = []int{1, 2, 3}
b = []int{1, 2, 1, 2, 3}
r = match(a, b)
fmt.Println("Match found for case 6: ", r)
a = []int{1, 2, 3, 4, 5}
b = []int{4, 1, 5, 3, 6, 1, 2, 4, 4, 5, 7, 8, 1, 2, 2, 4, 1, 3, 3, 4}
r = match(a, b)
fmt.Println("Match found for case 7: ", r)
a = []int{1, 2, 1, 2, 1}
b = []int{1, 1, 2, 2, 1, 2, 1}
r = match(a, b)
fmt.Println("Match found for case 8: ", r)
}
func match(a []int, b []int) bool {
if len(b) < len(a) {
return false
}
lb := len(b) - 1
la := len(a) - 1
i := 0
j := la
k := 0
counter := 0
for {
if i > lb || j > lb {
break
}
if b[i] != a[k] || b[j] != a[la] {
i++
j++
counter = 0
continue
} else {
i++
counter++
if k < la {
k++
} else {
k = 0
}
}
if counter >= la+1 {
return true
}
}
return counter >= la+1
}
Correctness
As discussed in the comment section, there are a family of string matching algorithms, which normally categorized into single pattern and multiple pattern matching algorithm. In your case it belongs to single pattern string matching problem.
From my knowledge, the most well-known algorithm is KMP algorithm which uses dynamic programming, and an alternative named Rabin-Karp's algorithm which uses rolling hash technique to speed up the process. Both runs in O(max(a,b)).
However, your code is not very alike to these algorithm's normal implementation, at least to my experience. Therefore I suspect the correctness of your code at the first place. You can try cases like a = {1, 2, 1, 2, 1}, b { 1, 1, 2, 2, 1, 2, 1 } to see it is not giving correct result.
Therefore you can
Abandon current algorithm and learn those standard one, implement them
Outline the logic and sketch a proof of your current algorithm, compared it with the logic behind those standard algorithms to verify its correctness
I will leave this part to you
Complexity
To directly answer your OP:
No, O(max(a,b)) is the optimal you can achieve in this problem, which is also the complexity of the standard known algorithms mentioned above.
My understanding is that, it actually makes sense as at worst case, you HAVE TO read each character of the longer string at least 1 time.
Your current algorithm is also O(b) clearly, as you loop using i from 0 to length of b, and no matter which condition you fall into i will increase by 1, giving total O(b)
Therefore complexity is actually not the problem, the correctness is the problem.
Since you are only looking for a sequence, i would probably convert everything to string type and use the standard strings package.
Playground
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Contains("1, 2, 3, 4, 5, 6, 7, 8, 9", "1, 2, 3"))
fmt.Println(strings.Contains("4, 5, 6, 7, 8, 9", "1, 2, 3"))
fmt.Println(strings.Contains("1, 5, 3, 7, 8, 9", "1, 2, 3"))
fmt.Println(strings.Contains("4, 5, 1, 7, 3, 9", "1, 2, 3"))
fmt.Println(strings.Contains("4, 5, 6, 1, 2, 3", "1, 2, 3"))
fmt.Println(strings.Contains("4, 5, 6, 1, 2, 3, 2", "1, 2, 2, 3"))
fmt.Println(strings.Contains("1, 2, 1, 2, 3", "1, 2, 3"))
}

Sum of ruby arrays in a loop

I want to find sum of arrays from 1 to 100.Each number is converted to array containing its own digits eg 97 will be [9,7].Here is what i have tried
(1..100).to_a.each do |i|
i.to_s.split("").map(&:to_i).inject(0) { |sum, number| sum + number }
end
But the sum of arrays are not displayed correctly!
For example;We first create an array of the digits and then return sum
[1]=1
[5]=5
[1, 0]=1
[1, 1]=2
[1, 2]=3
[1, 3]=4
[1, 4]=5
So sum of individual arrays is to be returned.
each will iterate the array, but not create a new array with the result of the block. If you want the results at the end, you need to use map:
result = (1..100).to_a.map do |i|
i.to_s.split("").map(&:to_i).inject(0) { |sum, number| sum + number }
end
result
#=> [1, 2, 3, 4, ...]
For summing an array you can also simply write
array.inject(:+)
# instead of
array.inject(0) { |sum, number| sum + number }
Also, the to_a is not necessary, you can directly call each and/or map on a range. So the simplified code would be
result = (1..100).map do |i|
i.to_s.split("").map(&:to_i).inject(:+)
end
result
#=> [1, 2, 3, 4, ...]
For your codes, you just need to change each method to map.
(1..100).to_a.map do |i|
i.to_s.split("").map(&:to_i).inject(0) { |sum, number| sum + number }
end
more simplicity way:
result = (1..100).to_a.map{ |e| e.to_s.split('').map(&:to_i).reduce(:+) }
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 1]
if you want to get the sum of result, just do like this:
result.reduce(:+)
If I understand your question correctly you want the sum of these new arrays, right? This should solve your problem:
(1..100).map { |i| i.to_s.split("").map(&:to_i).inject(:+) }.inject(:+)
digits and sum are newer methods, simplifying this to
(1..100).sum{|i| i.digits.sum}
Another alternative for modern newer versions of Ruby:
(1..100).flat_map(&:digits).sum

How get sets of integer which appear in at least K or more than K sub-array(s) from array. Each set must have exactly L elements ?

I want to write program with input an array which contains N sub-array(s). Each sub-array is an array of integers which has M element(s). N and M can be very large (e.g. 1.000.000). It assume that the arrays can be stored in physical memory. The program would output: All sets of integers which appear in at least K or more than K sub-array(s). Each set must have exactly L elements.
Ex:
Input:
N = 5
{1, 2, 3, 4, 5}
{1, 3, 2}
{1, 4, 3, 2, 9}
{2, 3, 4, 7, 9}
{3, 4, 5, 9, 10}
Output:
1. In case K = 3, L = 2
{1, 2}
{1, 3}
{2, 3}
{2, 4}
{3, 4}
{3, 9}
{4, 9}
2. In case K = 3, L = 3
{1, 2, 3}
{2, 3, 4}
How can I do ?
thanks

Resources