Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(data.table)
- library(plyr)
- library(dplyr)
- library(magrittr)
- library(Rcpp)
- mat = fread('No, A, B, C, D, E, F, G
- 1, 1, 3, 0, 0, 4, 2, 1
- 2, 1, 0, 0, 0, 2, 0, 3
- 3, 0, 1, 0, 3, 0, 0, 0
- 4, 1, 3, 2, 1, 0, 0, 0
- 5, 0, 6, 0, 0, 0, 0, 0
- 6, 0, 0, 0, 0, 2, 2, 1
- ') %>% as.matrix
- sourceCpp(code = '
- #include <Rcpp.h>
- using namespace Rcpp;
- // [[Rcpp::export]]
- NumericMatrix move_left_f(NumericMatrix mat, double replacedValue = 0.0, bool drop = false) {
- int nc = mat.ncol(), nr = mat.nrow();
- std::vector< std::vector<double> > out(nr);
- for (int j =0; j < nc; j++)
- {
- for (int i = 0; i < nr; i++)
- {
- if (mat(i,j)!=replacedValue)
- out[i].push_back(mat(i,j));
- }
- }
- std::size_t outNumCol = 0;
- if (drop)
- {
- for (int i = 0; i < nr; i++)
- outNumCol = (outNumCol > out[i].size()) ? outNumCol : out[i].size();
- }
- else
- outNumCol = nc;
- NumericMatrix outMat(nr, outNumCol);
- for (int j = 0; j < (int) outNumCol; j++)
- {
- for (int i = 0; i < nr; i++)
- {
- if (j < (int) out[i].size())
- outMat(i, j) = out[i][j];
- else
- outMat(i, j) = 0.0;
- }
- }
- return outMat;
- }')
- move_left_f(mat, 0.0, FALSE)
- # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
- # [1,] 1 1 3 4 2 1 0 0
- # [2,] 2 1 2 3 0 0 0 0
- # [3,] 3 1 3 0 0 0 0 0
- # [4,] 4 1 3 2 1 0 0 0
- # [5,] 5 6 0 0 0 0 0 0
- # [6,] 6 2 2 1 0 0 0 0
- move_left_f(mat, 0.0, TRUE)
- # [,1] [,2] [,3] [,4] [,5] [,6]
- # [1,] 1 1 3 4 2 1
- # [2,] 2 1 2 3 0 0
- # [3,] 3 1 3 0 0 0
- # [4,] 4 1 3 2 1 0
- # [5,] 5 6 0 0 0 0
- # [6,] 6 2 2 1 0 0
Advertisement
Add Comment
Please, Sign In to add comment