loop through two variable in Haskell - loops

What is the haskell way to do this?
for (int i = 0 ; i < 1000 ; i++)
for (int j = 0 ; j < 1000 ; j++)
ret = foo(i , j ) #I need the return value.
More background:
I am solving euler problem 27 , and I have got:
value a b =
let l = length $ takeWhile (isPrime) $ map (\n->n^2 + a * n + b) [0..]
in (l, a ,b)
The next step is to get a list of tuple by looping through all the possible a and b and then do the following processing:
foldl (\(max,v) (n,a,b)-> if n > max then (n , a * b) else (max ,v) ) (0,0) tuple_list
but I have no idea how to loop through two variables ..Thanks.

Use a nested list comprehension. Here 'foo' is '(,)'':
[ (i,j) | i <- [0 .. 999], j <- [0 .. 999] ]
Or laid out to make the nesting clearer:
[ foo i j
| i <- [0 .. 999]
, j <- [0 .. 999]
]

As well as dons' answer, you can use the list monad:
do
i <- [0 .. 999]
j <- [0 .. 999]
return (foo i j)

You can also do this nicely using Control.Applicative
module Main where
import Control.Applicative
main :: IO ()
main = mapM_ putStrLn (foo <$> [0..3] <*> [0..3])
foo :: Int -> Int -> String
foo a b = "foo " ++ show a ++ " " ++ show b
Example run:
C:\programming>ghc --make Main.hs
[1 of 1] Compiling Main ( Main.hs, Main.o )
Linking Main.exe ...
C:\programming>main
foo 0 0
foo 0 1
foo 0 2
foo 0 3
foo 1 0
foo 1 1
foo 1 2
foo 1 3
foo 2 0
foo 2 1
foo 2 2
foo 2 3
foo 3 0
foo 3 1
foo 3 2
foo 3 3

Related

How do you invert euclidean (transform and rotation only) matrices in C?

How do you invert 4x3 matrices that are only translation and rotation, no scale? The sort of thing you would use to do an OpenGL Matrix inverse (just without scaling)?
Assuming your TypeMatrix3x4 is a [3][4] matrix, and you are only transforming a 1:1 scale, rotation and translation matrix, the following code seems to work -
This transposes the rotation matrix and applies the inverse of the translation.
TypeMatrix3x4 InvertHmdMatrix34( TypeMatrix3x4 mtoinv )
{
int i, j;
TypeMatrix3x4 out = { 0 };
for( i = 0; i < 3; i++ )
for( j = 0; j < 3; j++ )
out.m[j][i] = mtoinv.m[i][j];
for ( i = 0; i < 3; i++ )
{
out.m[i][3] = 0;
for( j = 0; j < 3; j++ )
out.m[i][3] += out.m[i][j] * -mtoinv.m[j][3];
}
return out;
}
You can solve that for any 3 dimensional affine transformation whose 3x3 transformation matrix is invertible. This allows you to include scaling and non conformant applications. The only requirement is for the 3x3 matrix to be invertible.
Simply extend your 3x4 matrix to 4x4 by adding a row all zeros except the last element, and invert that matrix. For example, as shown below:
[[a b c d] [[x] [[x']
[e f g h] * [y] = [y']
[i j k l] [z] [z']
[0 0 0 1]] [1]] [1 ]] (added row)
It's easy to see that this 4x4 matrix, applied to your vector produces exactly the same vector as before the extension.
If you get the inverse of that matrix, you'll have:
[[A B C D] [[x'] [[x]
[E F G H] * [y'] = [y]
[I J K L] [z'] [z]
[0 0 0 1]] [1 ] [1]]
It's easy to see that it this works in one direction, it needs to be in the reverse direction, if A is the image of B, then B will be the inverse throug the inverse transformation, the only requisite is the matrix to be invertible.
More on... if you have a list of vectors you want to process, you can apply Gauss elimination method to an extended matrix of the form:
[[a b c d x0' x1' x2' ... xn']
[e f g h y0' y1' y2' ... yn']
[i j k l z0' z1' z2' ... zn']
[0 0 0 1 1 1 1 ... 1 ]]
to obtain the inverses of all the vectors you do the Gauss elimination vector to get from above:
[[1 0 0 0 x0 x1 x2 ... xn ]
[0 1 0 0 y0 y1 y2 ... yn ]
[0 0 1 0 z0 z1 z2 ... zn ]
[0 0 0 1 1 1 1 ... 1 ]]
and you will solve n problems in one shot, because the column vectors above will be the ones, that once transformed produce the former ones.
You can get a simple implementation I wrote to teach my son about linear algebra of Gauss/Jordan elimination method here. It's opensource (BSD license) and you can modify/adapt it to your needs. This method uses the last approach, and you can use it out of the box by trying the sist_lin program.
If you want the inverse transformation, put the following contents in the matrix, and apply Gauss elimination to:
a b c d 1 0 0 0
e f g h 0 1 0 0
i j k l 0 0 1 0
0 0 0 1 0 0 0 1
as input to sist_lin and you get:
1 0 0 0 A B C D <-- these are the coefs of the
0 1 0 0 E F G H inverse transformation
0 0 1 0 I J K L
0 0 0 1 0 0 0 1
you will have:
a * x + b * y + c * z + d = X
e * x + f * y + g * z + h = Y
i * x + j * y + k * z + l = Z
0 * x + 0 * y + 0 * z + 1 = 1
and
A * X + B * Y + C * Z + D = x
E * X + F * Y + G * Z + H = y
I * X + J * Y + K * Z + L = z
0 * X + 0 * Y + 0 * Z + 1 = 1

Multiplying a sparse matrix by an array without copying

I have a 1d array (vector of size M), a pretty large one, and I definitely don't want to be copying it in memory. I also have a sparse matrix of window N (arbitrary size, basically all elements except the diagonal & N pseudo diagonals are zero).
I want to multiply this sparse matrix by the vector, without having to copy the vector in memory. What's the easiest and most efficient way of doing this? There has to be a neat solution, but I don't know the proper literature and I'm not educated enough to figure this out.
There is a solution for N=1 (where matrix is: a on the diagonal, and b on two closest pseudo diagonals). The solution looks smth like this (e.g., in python):
tmp2 = array[0]
i = 1
while (i < len(array) - 1):
tmp1 = b * (array[i - 1] + array[i + 1]) + a * array[i]
array[i - 1] = tmp2
i += 1
tmp2 = b * (array[i - 1] + array[i + 1]) + a * array[i]
array[i - 1] = tmp1
i += 1
But I can't manage to generalize this for an arbitrary N.
Notes: I absolutely don't want to be copying the size M vector in memory. However, using a temporary array of size 2N+1 is ok, since M >> N. I'm looking for an actual algorithm description, not a smart custom library that does the job.
Thanks in advance!
Consider the matrix
[
1 2 3 0 0 0
2 1 2 4 0 0
3 2 1 2 5 0
0 7 2 1 2 6
0 0 8 2 1 2
0 0 0 9 2 1
]
and the vector v [1,2,3,4,5,6]
For each row, below the involves coeff of v:
[1,2,3]
[1,2,3,4]
[1,2,3,4,5]
[ 2,3,4,5,6]
[ 3,4,5,6]
[ 4,5,6]
As you have noticed, you just need to keep track of a window of v.
That window is originally [1,2,3,4,5] (for i = 0, 1, 2)
Then you shift that window to the right every i (and eventually truncate it for the last rows not to be out of bounds of v...)
Now notice that when you shift to the right, you only need to know the next value from v, and as long as you have not dirtied that value (by writing to v) your new window is valid.
For row i, window is [i-n;i+n] and the coeff which will be modified is v[i]. For the next window, you need to know v[i+n+1] which has not been dirtied. So all good.
So algo be like
window = circularbuffer(2n+1) //you push to the right, and if length > 2n+1, you remove first elem
for i = 0; i<v.size()
v[i] = prod(row_i, window) // only for the row_i coeffs...
if i >= n && < M-3
window.push(v[i+n+1])
else if i>= M-3
window.shift() // just remove the first value
const N = 2
const M_SIZE = 10
function toString(M){
return M.map(x=>x.join(' ')).join('\n')
}
const { M, v } = (_ => {
const M = Array(M_SIZE).fill(0).map(x=>Array(M_SIZE).fill(0))
let z = 1
for(let i = 0; i<M_SIZE; ++i){
for(let j = -N; j<=N; ++j){
if(i+j >= 0 && i+j <M_SIZE){
M[i][i+j] = (z++ % (N*2))+1
}
}
}
const v = Array(M.length).fill(0).map((x,i)=>i)
return { M, v}
})()
function classic(M, v){
return M.map(r => r.reduce((acc, x, j) => acc + v[j]*x, 0))
}
function inplace(M, v){
// captn inefficiency
const circBuf = (init => {
let buf = init
return {
push (x) {
buf.push(x)
buf.shift()
},
shift() {
buf.shift()
},
at (i) { return buf[i] },
toString() {
return buf.join(' ')
}
}
})(v.slice(0, 2 * N + 1))
const sparseProd = (row, buf) => {
let s = 0
row.forEach((x, j) => s += x * buf.at(j))
return s
}
const sparseRows = M.map(r => r.filter(x => x !== 0))
sparseRows.forEach((row, i) => {
v[i] = sparseProd(row, circBuf)
if (i >= sparseRows.length - 3 ) {
circBuf.shift()
} else {
if (i >= N) {
circBuf.push(v[i + N + 1])
}
}
})
}
console.log('classic prod', classic(M, v))
inplace(M, v)
console.log('inplace prod', v)
So I ended up doing something like this. It seems like a generalization of what was done for the N=1 case.
In general, my weights are basically the non-zero components of the central row in my sparse matrix. I.e. if the matrix looks like this (as was noted in the comments, it's usually symmetric, but not necessarily):
| a b c 0 0 ... 0 0 0 0 0 |
| b a b c 0 ... 0 0 0 0 0 |
| c b a b c ... 0 0 0 0 0 |
| 0 c b a b ... 0 0 0 0 0 |
| 0 0 c b a ... 0 0 0 0 0 |
| ... ... ... |
| 0 0 0 0 0 ... a b c 0 0 |
| 0 0 0 0 0 ... b a b c 0 |
| 0 0 0 0 0 ... c b a b c |
| 0 0 0 0 0 ... 0 c b a b |
| 0 0 0 0 0 ... 0 0 c b a |
then the weights vector is simply [c, b, a, b, c] (i.e., N = 2).
So for the general case where N = ntimes I ended doing something like this:
def sparse_multiply(array, weights):
ntimes = (len(weights) - 1) / 2
# reduced dot product
def product(a_, i_, w_):
dot = 0.0
for k, j in enumerate(range(i_ - ntimes, i_ + ntimes + 1)):
if (j >= 0 and j < len(a_)):
dot += a_[j] * w_[k]
return dot
tmp = np.zeros(ntimes + 1)
for i in range(ntimes):
tmp[i] = array[i]
i = ntimes
while (i <= len(array)):
for t in range(-1, ntimes):
tmp[t] = product(array, i, w)
array[i - ntimes] = tmp[t + 1]
i += 1
return array
The only sacrifice you make, is the temporary array of size O(N), which is fine, because as I said, N << M.
Yes, yes, I know some of the operations (like the reduced dot product) could have been done with some python magic. But my point was to transfer this into old school C/Fortran, so that wouldn't help much.
Applications
Actually the application I was interested was to apply a gaussian filter: a_i = 0.5 * a_i + 0.25 * (a_{i-1} + a_{i+1}) to an array N times without having to do N passes and without having to copy the whole array.
So what you can do, is you can raise the sparse matrix of 0.5 on diagonals, and 0.25 on pseudo diagonals to the Nth power, and you will end up with the weights vector and a matrix that looks like the one I showed earlier (but with N nonzero pseudo diagonals). Then you can apply these weights to the array using the method above, so that you don't modify a_i before having to use it for other components, but at the same time get away without copying the whole array.
PS. Unfortunately I did not quite follow #grodzi's answer. A bit more explanation would certainly help.

Syntax understanding in task with matlab

can comeone help to understand in MAtlab this:
k=2
n = (0:-1:-4)+k
the result; 2 1 0 -1 -2
how it works?
You are dealing with a colon operator and a vectorized sum at the same time. Let's split the problem into smaller, stand-alone problems:
In Matlab, if you add or subtract between a scalar value to a matrix, the arithmetic operation is performed on all the elements of the matrix, in a vectorized way. Example:
A = [1 2; 3 4]; % 2-by-2 matrix
S1 = A + 2 % output: S1 = [3 4; 5 6]
B = [1 2 3 4] % 1-by-5 matrix, also called column vector
S2 = B - 5 % output: S2 = [3 4 5 6]
The column operator in Matlab can be used in many situation: indexing, for iterations and vector creation. In your case, its purpose is the third one and it's syntax is START(:STEP):END. The default STEP, if not specified, is 1. The START and END parameters are never exceeded. Example:
A = 1:5 % output: A = [1 2 3 4 5]
B = -2.5:2.5:6 % output: B = [-2.5 0 2.5 5]
C = 1:-1:-5 % output: C = [1 0 -1 -2 -3 -4 -5]
D = -4:-2:0 % output: D = []
In all the programming languages, an operator precedence criterion is defined so that a one-liner calculation that uses multiple operators is atomized into smaller calculations that respect the given priority, unless parentheses are used to redefine the default criterion... just like in common maths. Example
A = 2 * 5 + 3 % output: A = 13
B = 2 * (5 + 3) % output: B = 16
Let's put all this together to provide you an explaination:
n = (0:-1:-4) + k
% vector creation has parentheses, so it's executed first
% then, the addition is executed on the result of the first operation
Let's subdivide the calculation into intermediate steps:
n_1 = 0:-1:-4 % output: n_1 = [0 -1 -2 -3 -4]
n_2 = n_1 + k % output: n_2 = [2 1 0 -1 -2]
n = n_2
Want to see what happens without parentheses?
n = 0:-1:-4+k % output: n = [0 -1 -2]
Why? Because the addition has priority over the colon operator. It's like writing n = 0:-1:(-4+k) and adding k to the END parameter of the colon operator. Let's subdivide the calculation into intermediate steps:
n_1 = -4 + k % output: n_1 = -2
n_2 = 0:-1:n_1 % output: n_2 = [0 -1 -2]
n = n_2
Basic Matlab syntax, you're dealing with range operators. There are two patterns:
[start]:[end]
and
[start]:[step]:[end]
Patterns like this result in arrays / vectors / "1D matrices".
In your example, you will get a vector first, stepping through the numbers 0 to -4 (step == -1). Then, you are adding k == 2 to all numbers in this vector.
octave:1> k = 2
k = 2
octave:2> n = (0:-1:-4)+k
n =
2 1 0 -1 -2
octave:3> 0:-1:-4
ans =
0 -1 -2 -3 -4
The parenthesizes expression determines an array. The the first number there is the first element, the second is the step and the last one is the last element. So the parenthesizes returns 0 -1 -2 -3 -4. Next we add k=2 to each element that results in 2 1 0 -1 -2

Idiomatic way to detect sequences of x times same object in an Array in Smalltalk?

What's the idiomatic way to detect sequences of x times the same object (or an object with a specific matching parameter) in an OrderedCollection or Array?
E.g. does the Array contain 10 times the number 5 in a row?
I like Uko's answer and would like to provide a different solution which addresses the "matching parameter" part of your question. In SequenceableCollectiondefine:
contains: m consecutiveElementsSatisfying: block
| n i |
self isEmpty ifTrue: [^m = 0].
n := self size - m + 1.
i := 1.
[i <= n] whileTrue: [| j |
(block value: (self at: i)) ifTrue: [
j := 2.
[j <= m and: [block value: (self at: i + j - 1)]]
whileTrue: [j := j + 1].
j > m ifTrue: [^true]].
i := i + 1].
^false
Now, for example the two following expressions would evaluate to true
#(2 1 1 1 2) contains: 3 consecutiveElementsSatisfying: [:e | e = 1]
#(2 1 0 1 2) contains: 3 consecutiveElementsSatisfying: [:e | e squared = e]
Note: If you want the startingAt: n version of this method just initialize i := n instead of i := 1 just before the main loop.
EDIT:
And, of course, we can complete the protocol with the following method in SequenceableCollection:
contains: m consecutiveTimes: anObject
^self contains: m consecutiveElementsSatisfying: [:e | e = anObject]
And the example:
#(2 1 1 1 2) contains: 3 consecutiveTimes: 1
Getting the sequences of repeating objects is as simple as:
({ 1. 1. 2. 2. 2. 5. 5. 3. 9. 9. 9. 9. } as: RunArray) runs
=> #(2 3 2 1 4)
If you want to test if there is a run satisfying specific constraints, you can do something like the following:
meetsConstraint := false.
({ 1. 1. 2. 2. 2. 5. 5. 3. 9. 9. 9. 9. } as: RunArray) runsAndValuesDo: [:run :value |
meetsConstraint := (value = 9 and: [run > 3])].
If you want to test for a certain property of an object instead of object equality, you can easily create a RunArray of this property by doing a collect: on it.
So the generalized solution would look something like this:
SequenceableCollection >> containsRunOf: anElement withAtLeast: nElements
(self as: RunArray) runsAndValuesDo: [:run :value |
(value = anElement and: [run >= nElements]) ifTrue: [^ true]].
^ false
And then:
({ 'aa'. 'bb'. 'c'. 'ddd'. } collect: [:each | each size])
containsRunOf: 2 withAtLeast: 3
=> false
I'd say that you have to follow a pattern like this:
(collectionToTest
indexOfSubCollection: (
Array
new: numberOfRepetitions
withAll: desiredObject)
startingAt: 1
) isZero not
Maybe I don't know some of useful methods in Pharo, but if you define the ones like:
SequenceableCollection >> indexOfSubCollection: aSubCollection
^ aSubCollection indexOfSubCollection: aSubCollection startingAt: 0
SequenceableCollection >> containsSubCollection: aSubCollection
^ (aSubCollection indexOfSubCollection: aSubCollection) isZero not
Object >> asArrayOf: aLength
^ Array new: aLength withAll: self
then the definition can be flattened into:
collectionToTest containsSubCollection:
(desiredObject asArrayOf: numberOfRepetitions)
or for your example:
anArray containsSubCollection: (5 asArrayOf: 10)
P.S. I'm not sure about the method names. Maybe inArrayOf: can be better then asArrayOf: and so on.

Printing a 2d array in haskell

I'm messing around with printing a random 2d array of Ints, in this simple image format (PPM)
0 1 0 0 1
1 0 0 1 0
0 1 1 0 0
0 1 1 1 0
0 0 0 1 0
Below is my code, which works, but seems like way too much code for such a simple operation. Is there a better way to do this?
import System.Random
import Data.Array.IArray
main = do
g <- newStdGen
let img = listArray ((0,0),(5,5)) ( myRands g ) :: Array (Int,Int) Int
putStrLn $ printArray img
myRands :: RandomGen g => g -> [Int]
myRands g = randomRs (0,1) g
make2dRange :: Int -> Int -> Int -> Int -> [(Int,Int)]
make2dRange x1 y1 x2 y2 = range ((x1,y1),(x2,y2))
printArray :: ( Array (Int,Int) Int ) -> String
printArray arr = unlines rows
where rows = map (unwords . map (show . (!) arr)) rowIndices
rowIndices = map ( \y -> make2dRange 0 y 5 y ) [0..5]
Other than the obvious, of course (array dimensions are hardcoded, for example)
I would use list comprehensions to manipulate the indices.
printArray arr =
unlines [unwords [show (arr ! (x, y)) | x <- [0..5]] | y <- [0..5]]
per: http://lambda.haskell.org/platform/doc/current/packages/split-0.2.2/doc/html/Data-List-Split.html#v%3achunksOf
chunksOf :: Int -> [e] -> [[e]]
chunksOf n splits a list into length-n pieces. The last piece will be shorter if n does not evenly divide the length of the list. If n <= 0, chunksOf n l returns an infinite list of empty lists.
using chunksOf my implementation would be..
printArray arr = mapM_ (putStrLn . unwords) $ map (map show) $ chunksOf 5 arr
usage:
Prelude System.Random Data.List Data.List.Split> printArray [0..25]
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
25

Resources