Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group matrix 9x9 elements into 3 row by 3 cols in Scala

Tags:

scala

matrix

Let's say i have the following matrix:


val grid = Array(
  Array( 1, 2, 3,  4, 5, 6,  7, 8, 9), 
  Array(11,12,13, 14,15,16, 17,18,19), 
  Array(21,22,23, 24,25,26, 27,28,29), 

  Array(31,32,33, 34,35,36, 37,38,39), 
  Array(41,42,43, 44,45,46, 47,48,49), 
  Array(51,52,53, 54,55,56, 57,58,59), 

  Array(61,62,63, 64,65,66, 67,68,69), 
  Array(71,72,73, 74,75,76, 77,78,79), 
  Array(81,82,83, 84,85,86, 87,88,89)
)

How can i, preferably in functional way, convert them this matrix:


val gridWithFields = Array(
  Array(1,2,3, 11,12,13, 21,22,23),
  Array(4,5,6, 14,15,16, 21,22,23),
  Array(7,8,9, 17,18,19, 27,28,29),
  ... 
)

*Updated*
I've done some benchmarking, but not sure wether memory result are correct or not. Any way here they are:

@maxmc for's solution

alg1 in Cycles: 10    Time: 2712683ns Memory: 459572
alg1 in Cycles: 100   Time: 914297ns  Memory: 458191
alg1 in Cycles: 1000  Time: 85102ns   Memory: 457944
alg1 in Cycles: 10000 Time: 68742ns   Memory: 457943

@Daniel C. Sobral solution

alg2 in Cycles: 10    Time: 3747031ns Memory: 458889
alg2 in Cycles: 100   Time: 1796564ns Memory: 457951
alg2 in Cycles: 1000  Time: 186215ns  Memory: 457220
alg2 in Cycles: 10000 Time: 122642ns  Memory: 456708

@Or Peles solution

alg3 in Cycles: 10    Time: 741475ns Memory: 457472
alg3 in Cycles: 100   Time: 542181ns Memory: 457914
alg3 in Cycles: 1000  Time: 248020ns Memory: 457911
alg3 in Cycles: 10000 Time: 119105ns Memory: 457919

@Hbf solution

alg4 in Cycles: 10    Time: 179093ns Memory: 457472
alg4 in Cycles: 100   Time: 121072ns Memory: 457069
alg4 in Cycles: 1000  Time: 78123ns  Memory: 456719
alg4 in Cycles: 10000 Time: 75948ns  Memory: 455913

@Eastsun solution

alg5 in Cycles: 10    Time: 144037ns Memory: 457512
alg5 in Cycles: 100   Time: 40672ns  Memory: 457059
alg5 in Cycles: 1000  Time: 42236ns  Memory: 456119
alg5 in Cycles: 10000 Time: 46480ns  Memory: 455952

I've tested it on MacMini(2012). Memory results are realy strange, so sources are here, if there are some bad mistakes and anti-patterns please tell me =) https://github.com/Stimphonier/MatrixBench

like image 607
4lex1v Avatar asked Jan 18 '26 08:01

4lex1v


1 Answers

The 'for' approach:

for(x <- 0 until 9 by 3) yield
  (for {
    row <- 0 until 9;
    col <- x until x + 3 by 3;
    i <- col until col + 3
  } yield grid(row)(i)).toArray   
like image 89
maxmc Avatar answered Jan 20 '26 16:01

maxmc