Hot answers tagged

5

Your code is repetitive. To solve that I'll show some array-related easy cheats. As @Olivier said, Array implements IEnumerable. Thus you can iterate it with foreach. Array is parent type for any array. Then you may upcast any array to Array. Method Buffer.BlockCopy can copy bytes from array to another array regardless of data type but accepts a data item ...


4

I want to present an alternative solution. In .NET, arrays implement IEnumerable. This allows us to iterate multi dimensional arrays as if they were flat. The downside is that we must calculate the indexes in the output array. Here is an example for a 3-d array: public static TOutput[,,] ConvertAll<TInput, TOutput>(TInput[,,] input, ...


3

Just use Array.ConvertAll that is already exist. For instance, you want to convert array from string[] to int[] you can do this : var converted = Array.ConvertAll(array , item => int.TryParse(item?.ToString() , out int result) ? result : 0); Another point is, if you only targeting one-dimension array, then you don't need to use the abstract class Array, ...


3

There are a few alternative solutions which might work LINQ It is possible to use Enumerable.Cast<T>() to achieve the same results (at least for a 1D array) [TestMethod] public void CheckConversion() { // One Dimensional Array with int element convert to int[] var array1 = Array.CreateInstance(typeof(int), 10); for (int i = 0; i < ...


3

After reading the code in question it seems every method is doing exactly the same hence I will focus only on one method and tell you what I would change: public static int[] ToIntArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!...


3

As long as this input array is static in its depth and structure, the best and fastest technique (due to lowest overhead) is to use old-school loops. Beyond that, I would: Not declare variable that will not be used Use square brace pushing syntax Avoid excessively wide lines of code which demand the developer to horizontally scroll Use words as variable ...


3

When I see that many recurrences like this then it is a good sign for me that this is a perfect place to introduce meta-programming via T4. Step #1 Separate the overloads from the core logic: using System; namespace Sample.Core { internal static class Converter { public static Array ConvertArray<T, TResult>(Array array, Converter<T, ...


3

It seems like your end goal is to apply ConvertAll to all of the different types of C# arrays, nested or not, and with with lower bounds not equal to zero. All arrays can be manipulated through the Array base class and any level of nesting can be handled by using recursion. First some plumbing is needed to enumerate all possible indices of an array of ...


2

Welcome to the Code Review Community. General Observations The use of small functions is very good and makes the code more readable, but overall the readability can be improved. The code does seem to follow the concept of the single responsibility principle. I'm going to address the code in 2 phases, one is dealing with improving the use of C programming and ...


2

You have been posting in CodeReview for about 1 year, so while you are still learning C# and a hobbyist, you are not a total newbie. Therefore, you should expect the reviews to be a little more critical. Do understand that "critical" does not mean "mean spirited" but rather more blunt while also being constructive. What disappoints me ...


2

A reference variable will save you from that wicked code bloat! You can make iterative calls of this Stack Overflow answer from 2012. Code: (Demo) function assignArrayByPath(&$arr, $path, $value, $separator = '_') { $keys = explode($separator, $path); foreach ($keys as $key) { $arr = &$arr[$key]; } $arr = $value; } ...


2

Unit testing Definitely write some test cases for your code. JUnit would be one possibility, but there are many test frameworks to choose from. With any test framework, and at least one test per public method, this goof would have been immediately apparent: public boolean isEmpty() { return size() > 0; } As Timothy Truckle points out in a ...


2

Nice example of const generics! In general your code is well organized and idiomatic. Some comments: In your new() function, you are using an argument as a default value. It's more idiomatic to use the Default trait for this: pub fn new(dim: [usize; N]) -> Self where T: Clone + Default, { let cap = Self::calculate_capacity(&dim); NdArray {...


2

Maybe this can help (if you don't want to use numpy): headers = ['foo', 'bar', 'baz', 'other'] l = len(headers) arr = [["xxx" for i in range(l)] for j in range(l)] # adding top row arr = [headers] + arr # adding first column headers_mod = ['Title'] + headers new_arr = [[headers_mod[i]]+arr[i] for i in range(l+1)] for i in new_arr: print(*i) ...


1

Passing everything in global variables might seem convenient for this small program, but is a poor practice more generally, since it makes it hard to reason about any function in isolation. In particular, big_array_copy, array_print and count seem to be used only for short-term storage, so should be local to their respective functions. The functions are ...


1

Good formatting Good use of (u)intN_t types When printing, use a matching format specifier: printf("%" PRI16u , array_print[0]); Avoid naked magic numbers Define constants for flexibility and clarity // int user_num[5] = { 0] }; //uint16_t big_array[10][5] = { 0 }; #define BIG_ARRAY_MAXJ 10 #define BIG_ARRAY_MAXI 5 int user_num[BIG_ARRAY_MAXI] = { ...


1

return size() > 0; Typo, should be (less than or) equal zero. for(int i = 0; i < length; i++) { elements[i] = null; } length = 0; It might be interesting to actually throw the array away and get a clean one in place, for example if this list was previously filled with 100 million entries. public boolean add(T element) { ...


1

You already have a good answer from Roland, but I'll add a few small points. It's good practice to make every function declaration a prototype - specify the number and type of the arguments it accepts. So instead of int main(), we write int main(void) to indicated that it can only be called with no arguments. We can reduce scope of the index variables i, j ...


1

The code looks reasonably short and clear, that's good. It's obvious that you are a beginner though since your code layout is inconsistent in a few places. Formatting the code consistently is mostly a boring task, that's why several people wrote programs to perform this formatting automatically. There are many different formatting styles, try one that fits ...


1

numpy is excellent for tables, but for a labeled table like this pandas might be better for your needs. Solution using numpy: import numpy as np # The header that i want to add headers = ['foo', 'bar', 'baz', 'other'] ll = len(headers)+1 data = [['xxx' for _ in range(ll)] for j in range(ll)] data = np.array(data, dtype=object) data[0,0] = 'Title' data[0,...


1

The code breaks at .Applyto with the following error: Run-time error "458" Variable uses an Automation type not supported in Visual Basic. I passed a worksheet range to an Array and this, by definition, creates a 2D array. Here is my testing code. Note: I verified that arr1 gets allocated with the passed Range. Dim arr1() As Variant arr1 = Range(&...


1

Since your ordering array contains all of the ids in your data array, you can prepare the two arrays to have relatable keys then just call array_replace(). This means a fully "functional style" instead of classic foreach loops (if you like them). The foreach() loops often outperform function calls due to having less overhead, but with my snippet ...


1

The default behavior of array_filter() is greedy about destroying falsey values. $new_query = array_filter($new_query, function($element) { return !empty($element);}); is identical in functionality to: $new_query = array_filter($new_query); I recommend consistently using curly braces on all constructs and logical tabbing to make your code more readable. ...


1

You don't need to call any sort() functions because your input and response arrays have a 1-to-1 relationship. Flip your input array so that the values become keys. Use array_column()'s third parameter to assign temporary keys to the response array. Now that the two arrays have relatable keys, you can just overwrite the flipped input array with the newly-...


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