Hot answers tagged

32

The NumPy Reference should be the first place you look when you have a problem like this. The operations you need are nearly always in there somewhere. And functions that you find while browsing the reference are sure to come in useful later in your NumPy career. For the first row, you could use numpy.arange and numpy.repeat: >>> np.repeat(np....


25

private static final int RANDOM_NUMBER = 10; Everyone knows the true random number is 4. Less jokingly, what's the RANDOM_NUMBER for? Consider adding comments to explain the purpose of your variables... or better yet renaming them (to RANDOM_GRIDVALUE_MAX, perhaps). static Random rand = new Random(); public int numberColumns; public int numberRows; int []...


24

public class tenxten { Java classes should start with a capital letter, and according to Java conventions should be named with something called "PascalCase". A name like TenXTen would adhere to that convention. static int numberRows = 10; static int numberColumns = 10; These are effectively used as constants (they do not change). Therefore they can be: ...


22

You can use NumPy module that's good with arrays and matrices. It has a built-in for exactly that purpose - import numpy as np np.rot90(image).tolist() With array manipulations, that's essentially same as performing matrix/array transpose and then flipping the rows - np.asarray(image).T[::-1].tolist() If the input is already an array, we can skip the ...


22

I believe the time complexity is \$O(n^2)\$, but I'd like to know for sure There's a general method for figuring out the time complexity for a piece of code, which is to annotate each line with the count of times it executes, and the average time it takes to execute, and then multiply and add. Before we do this it helps to rewrite the code so that just one ...


20

Compared to Python's NumPy, my matrix multiplication is quite a bit slower. Can it be made faster without using sophisticated matrix multiplication algorithms like Strassen's? One issue is that you use a vector of vectors - your memory accesses aren't going to be as contiguous. Typically one represents a matrix as a single really long vector, and then ...


18

I think your code is complete, but not the most efficient it could be. There are two areas where there are inefficiencies: there is no need to have a comprehensive row-column flag matrix... you only need two arrays, one for row, one for columns. you have very inefficient zeroing of the rows/columns because you will potentially do many cells many times. (...


17

Static and void All your variables are static. All your methods return void. This is not good. Java is an object-oriented language. You're not using it that way. You're using it more as a procedural language by having everything as static and using only void methods. Although this works (apparently), you're losing flexibility. I have a mission for you: ...


16

How about using Python built-ins to do the job? img = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] list(reversed(list(zip(*img)))) [(3, 30, 300), (2, 20, 200), (1, 10, 100)]


15

You ask many questions on CodeReview, which in itself is good, but you have to start helping the reviewers actually review your code. You have this habit of dumping code and expecting a review. It does not work that way (very well). For a start, let's review the ideal process for a 'real' review: you present neat and working code for review. you include a ...


15

Declare by interface and not implementation Instead of ArrayList<ArrayList<Integer>> linked = new ArrayList<ArrayList<Integer>>(); use: List<List<Integer>> linked = new ArrayList<List<Integer>>(); Or, if you're using Java 7+: List<List<Integer>> linked = new ArrayList<>(); Edit: When ...


15

Don't store data in static fields The biggest issue in this program is that all the data is stored in static fields. It would make sense to make everything non-static except the main method, so that you can have multiple instances. No need for multiple Random instances private static int randomInt(int from, int to) { Random rand = new Random(); ...


15

I will mostly focus on performance in this review because you have specifically asked for it and the other reviews did not cover it yet. Performance The first thing to do when optimizing for performance always is to measure. So I wrote a small benchmark for your matrix multiplication. public static void main(final String[] args) { final int maxSize = ...


15

Here is a short write-up of things I noticed while reading the code. Please excuse the missing structure, I might restructure it properly later. Please ask if the reasoning behind points is unclear. Instead of build-in arrays use std::array. Then you will not need to pass rowCount and colCount. It is also much safer, because you cannot pass std::arrays with ...


15

Here are a few of the high- and low-level ideas: too many comments. Remember, comments tend to age and outdate, they need to be maintained as the code changes. And, if they are over-used, they hurt readability, not improve it. See more at Coding Without Comments convert some of the comments preceding the functions and methods to proper documentation strings ...


14

Welcome to CodeReview! Class naming Maybe it's a term I'm not familiar with but Matrixer does not seem to ring a bell. Is it supposed to identify a "creator of matrixes"? Is it the name of your project? If you haven't made a conscious decision for this name, I would suggest turning it into something "universally" descriptive like MatrixCalculator (pretty ...


13

Field Visibility Restrict field visibility as much as possible. Use private final wherever you can (the compiler will let you know if you can't). Using this. in constructor In your constructor, you can use this. to assign your fields. This will allow you to use the same parameter names as field names. For example: public NumberGrid(int numberRows, int ...


13

Just create a list of 18 ones and 18 twos, shuffle it, then reshape to 6x6: from random import shuffle from numpy import reshape nums = [1]*18 + [2]*18 shuffle(nums) arr = reshape(nums, (6, 6)) Produces (for example): array([[1, 2, 2, 1, 2, 1], [2, 2, 2, 2, 2, 1], [2, 2, 2, 1, 1, 2], [1, 1, 1, 1, 2, 2], [2, 1, 1, 2, 1, 1], ...


12

No. Let's first look at it as two dimensional arrays, so we know what we're talking about: int i[4][4]; int j[4][4]; int k[4][4]; for (int x = 0; x < 4; x++) { // row number of output for (int y = 0; y < 4; y++) { // column number of output k[x][y] = 0; for (int z = 0; z < 4; z++) { // four elements are added for this output ...


12

That global array is indeed not good. You'll need to pass around an array, but you shouldn't do it with a C-style array. Doing that will cause it to decay to a pointer, which you should avoid in C++. If you have C++11, you could use std::array, which will be set at an initial size. But if you don't have C++11, and also want to adjust the size, use an std:...


12

You can swap entire rows. public static void swapRows(int[][] m) { for (int i = 0, k = m.length - 1; i < k; ++i, --k) { int[] x = m[i]; m[i] = m[k]; m[k] = x; } } public static void rotateByNinetyToLeft(int[][] m) { transpose(m); swapRows(m); } public static void rotateByNinetyToRight(int[][] m) { swapRows(m)...


12

This is by no means a full review, but I did notice something. The way you raise errors could use a little work if you're striving for maintainable code. Err.Raise vbObjectError + 1, "Matrix.Add", "Could not Add matrices: the Rows and Columns must be the same. The left matrix is (" & Me.Rows & ", " & Me.Cols & ") and the right matrix is (...


11

So, I looked at the problem spec, expecting to see a 3-word description o the title of the problem, and not much else, followed by 'Looking for optimizations, and confirmation that compelxity is O(n log(n) ). Fortunately, I was disappointed ;-) Your description is improved over previous questions, and I can actually follow it without having to google-search ...


11

White-Space You really need some white-space in your code. This is the first thing that will help to read your code easily. I have not read a lot your since it's really to read those kind of exppresions : if(i+ni<0 || j+nj<0 || i+ni>labels.length-1 || j+nj>labels[0].length-1) With some white-spaces, it will be easier to easily see what's ...


11

The first rule of matrix classes in C++ is that you don't write them by yourself; there are already dozens around, often highly optimized with [smart] expression templates and other cryptic stuff: Boost.uBLAS, Eigen, Blaze, Gmm++, Armadillo, Blitz++, etc... That said, I would lie to you if I told you that I never tried to reimplement my own matrix class. I ...


11

Use automatic tests In your doc-string you state: [2, 0, 2, 4] should return [4, 4, 0, 0] [0, 0, 2, 2] should return [4, 0, 0, 0] [2, 2, 0, 0] should return [4, 0, 0, 0] [2, 2, 2, 2, 2] should return [4, 4, 2, 0, 0] [8, 16, 16, 8] should return [8, 32, 8, 0] But I either Test all this inputs manually (very boring) Trust you (nothing ...


11

A couple of typical patterns to iterate over pairs of items in Python are: for prev, next in zip(nums[:-1], nums[1:]): ... and prev = None for next in nums: if prev is None: prev = next continue ... In your case, I think the second fits the bill better: def merge(nums): prev = None store = [] for next_ in nums: ...


11

In addition to what Hosch has told you: Make use of try with resources You utilize several classes which implement the Closable interface, but aren't explicitly freeing resources you use. Employing a try-with-resources statement will amend that with the benefit of reducing the scope of some variables you currently declare outside. As an example, rather ...


10

At first when I took a look at your question I was thinking: Why do you first set values in a boolean matrix to true? I quickly realized, "Oh. That's why." Overall, well done. I like your code. I would have solved it in the same way. Your coding style is consistent, which makes it easy to follow your code, even though I don't agree with the coding style ...


10

Naming: There are a lot of names I'd change. Some of them matter more than others (local names in a let are not that big a deal even if they're terrible, but a name for a widely used function should be suggestive, if possible). Some of them I'm more sure of than others. I'd change borrow to within. The old name isn't bad, but I think the new one is ...


Only top voted, non community-wiki answers of a minimum length are eligible