New answers tagged arrays
1
vote
Accepted
Uninitialized array literal
If the array was a fixed size, you could do this with a compound literal:
int *arr = condition ? (int[5]){} : NULL;
However you want to use a variable length array. Such arrays can't be initialized (...
1
vote
Why can't I assign an address to an array, but assigning an array to a pointer works in C++?
arr is an "automatic" variable. Its place in memory is usually fixed once the function in which it appears is invoked. Languagewise, you can not change it by reassigning it.
Even if you ...
0
votes
How do i loop over a geometric sequence. i need to loop some function over 1, 2, 4, 8, 16
A generator expression is a nice way of doing this:
for chunk_size in (2**i for i in range(10, 30)):
print(chunk_size)
0
votes
Declaring multiple sequential pointers/values in C
If you're trying to treat them as registers, I'd prefer macro approach as in my past pre-silicon simulator project. The loop thru assignment is only for the init which macro has already done, and for ...
-1
votes
Minimum number of operations for array of numbers to all equal one number
The brute force approaches below all take about 2/3 of the time the original approach took in Python 3.12. These are not algorithmic improvements, just constructs that happen to work faster due to ...
0
votes
How to use the output of a CONCAT() function as an array in Excel
CONCAT creates text, XLOOKUP requires a reference: a matrix or array that it will lookup
You can create references with INDIRECT("text") or related formulas, they don't return text as ...
1
vote
Minimum number of operations for array of numbers to all equal one number
As already answered, you can solve this with some preprocessing and binary search.
The preprocessing could consist of sorting a1 and then collecting the number of operations for when the values occur ...
0
votes
JS Find indices of duplicate values in array if there are more than two duplicates
Find all duplicate elements in an array:
const array = [4,2,34,4,1,12,1,4];
const newArray = [];
for (let i = 0 ; i < array.length; i++){
if(array.indexOf(array[i]) !== i && newArray....
0
votes
How to use the output of a CONCAT() function as an array in Excel
The solution for you:
=XLOOKUP(MetricDesired,INDIRECT(CONCAT("'",$B3,"'!$C:$C")),INDIRECT(CONCAT("'",$B3,"'!D:D")))
The INDIRECT function returns the reference ...
2
votes
Minimum number of operations for array of numbers to all equal one number
Well , I have a solution for this . Firstly, Sort the First array because Here position of the value of the first array doesn’t matter .
Secondly, Calculate prefix sum of the sorted array .
Thirdly, ...
0
votes
How to crop a numpy 2d array to non-zero values?
Here is a general purpose solution for N-dimensional arrays. I found that using np.any is 15x faster than np.argwhere for my application.
def crop_over_axis(vec:np.ndarray, axis:Tuple[int]) -> ...
0
votes
I have tried to implement search functionality in react, when I clear the input, I am not getting back the full list
Don't mutate your source of truth, e.g. the subscriber value/state being provided by the Context. Filtering is a reducing action, and once elements are removed from the source array they can't be ...
0
votes
Distinct for jsonb_path_query_array
directly you can not use DISTINCT, but a Combination from jsonb_path_query and array_agg would do the trick
Still you would need a unique column to do my approach
Schema (PostgreSQL v14)
create table ...
0
votes
Populate a 2d array partially from data in another multidimensional array
Use array_map() as a functional-style iterator. Demo
echo json_encode(
array_map(
fn($row) => [
'id' => 111,
'title' => $row['new'][0] . ' new',
...
0
votes
Dynamically populate a subarray inside of an array declaration
array_map() will elegantly allow you to dynamically populate the subarray without needing to break out of tour original array. Demo
$result = [
'label' => 'Assign to user',
'desc' => '...
0
votes
Filter sets of rows in a 3d array by the rows in a 2d blacklist array
Loop over the sets of data in your 3d input array and make filtering calls of array_udiff() upon each set leveraging the blacklist.
Code: (Demo)
$array = [
[
['itemid' => 1, 'name' =>...
0
votes
How to convert a String array to char array in Java
String value = "i love java to write";
Stream.of(value.split("")).filter(i -> !i.equals(" ")).forEach(System.out::println);
0
votes
Valid positions of `alignas` inside a plain array definition
alignas can only be applied to variables, non-static data members, and classes ([dcl.align]/1, [dcl.attr.grammar]/5).
In the example you give:
1 applies the alignment specifier to iarr1 ([dcl.pre]/4),...
0
votes
How to union ranges in google spreadsheets
Another way I just tested for two sheets with same format but distinct headers
=TRANSPOSE({TRANSPOSE('sheet 1'!A2:E), TRANSPOSE('sheet2'!A2:E)})
2
votes
Declaring multiple sequential pointers/values in C
The use of an array guarantees that the values will be sequential and properly aligned, so there is nothing you can improve on that.
If we really want to find something to improve, then there is a ...
-1
votes
How can I proxy [[set]] on all JavaScript array objects?
This code actually does not replace all Arrays... You can't actually do that. Also, when you cast [] then JavaScript will always use the native Array over the Array defined in your context...
There's ...
0
votes
Difference between passing in string vs. array parameters to recursive function
When passing a string to a recursive function, the string is immutable, meaning it cannot be modified directly. Any changes result in the creation of a new string in each recursive call (e.g., using ...
0
votes
Accepted
Difference between passing in string vs. array parameters to recursive function
This difference in behavior is due to the nature of mutable vs. immutable objects:
Immutable objects (like strings) create new objects when modified.
Mutable objects (like lists) are modified in-...
1
vote
TypeError: products.groupBy is not a function
groupBy was indeed introduced to standard JS API. However it is the static method of the Object class. You're trying to use it as instance method.
const groupByCategory = Object.groupBy(products, ...
0
votes
Fill array with numbers adding up to a nominated total without exceeding item maximum
Another technique is to implement a consuming recursive approach.
function fillArray($total, $nbreParChargement) {
if ($total <= $nbreParChargement) {
return [$total];
}
return ...
0
votes
Generate an associative 2d array with incremented column values using a flat array as first level keys
Loop only once using array_reduce() for functional-style iteration and use a static variable to allow the incrementation of the counter variable. Demo
$myArr = ["red", "green", &...
-2
votes
What is the difference between `int arr[10]{};` and `int arr[10] = {};`?
Both methods do the same thing behind the scenes.
List initialization
int arr[10]{};
Above code directly tells the compiler to initialize all elements to their default value 0.
Assignment ...
0
votes
Find index in map object using JavaScript
If you are dealing with "raw" input such as JSON data, it should not be in a Map.
You can build a "key" to index lookup Map on the side that can be used to speed up index checking.
...
0
votes
Create Pivot table and add additional columns from another dataframe
You could merge the grouped sum df2 to your pivot table from df1, then use assign to add the missing column.
df1.pivot_table(index='Counterparty', columns='Product', values='Value', aggfunc='sum')....
1
vote
Accepted
Create Pivot table and add additional columns from another dataframe
Total column can be generated by summing all present columns except the first. Must be done first prior to adding other columns.
out['Total'] = out[out.columns[1:]].sum(axis = 1)
col1 column is done ...
0
votes
Array showing incorrect data in SwiftUI sheet
UPDATED: Revised the code in light of the discussion in the comments and points raised by @loremipsum. I am adding this answer as an alternative solution to using .sheet(item: as shown in the other ...
2
votes
Array showing incorrect data in SwiftUI sheet
Instead of presentSheet, use selectedItem to use .sheet(item: $selectedItem). I added the @MainActor annotation for safety reasons, and you should use it, too. If you compile it with Swift 6, you will ...
2
votes
Sum of corresponding values from different arrays of the same size with Python
I've added empty_array = np.array([]) before my for loop but I don't know what to do next in the loop.
Almost right. You need to instantiate an array of the same shape as the arrays you will sum. ...
1
vote
Sum of corresponding values from different arrays of the same size with Python
Your snippet
for y in year:
for m in month:
for d in day:
start_date="%s"%y+"-%s"%m+"-%s"%d
end_date=start_date
...
0
votes
How could we sort a Map descending by values and then alphabetically by keys?
Here is one way. Uses record introduced in Java 16.
String[] names = {"COLIN","AMANDBA","AMANDAB","CAROL","PauL","JOSEPH"};
int[] weights = ...
1
vote
Need help understanding pointer to a type of n elements in C (int (*p)[10])?
printf("Value of *parr : %p\n", (*parr)); // 0x7fffd215b5d0 <---WHY?
parr is a pointer to an array, so *parr is the array itself. When an array appears in an expression, the actual ...
0
votes
Group data from lines of a log file by one column and create subarrays from another column
Parse your delimited log file lines with fscanf() and save your data in the desired groups. Demo
$result = [];
$handle = fopen('some.log', 'r');
while (fscanf($handle, '%*s | %s | %s', $name, $item)) {...
0
votes
Use values of a flat array as the keys in every row of a 2d array
Making mapped calls of array_combine() is direct and elegant. Demo
$keys = ['name', 'age'];
$rows = [
['Dave', 20],
['Steve', 25],
['Ace', 23],
];
var_export(
array_map(
fn($...
2
votes
Accepted
When did iterating on the span of an array become faster than iterating on the array itself
Iterating over a span has two advantages here:
it avoids an indirection into a field (rather than a local) for the array
the span's length is known in a predictable way
If it wasn't for _size also ...
0
votes
Group 2d array data into sets of recurring second level keys
If you don't know in advance how many rows belong in each group, push reference variables into the result array each time a reference (group) shares a key with the current row's key. While ...
4
votes
Accepted
Function to clear any value by assigning to it a default constructed value of same type
The first implementation is pedantically UB for multidimensional arrays, a T[M][N] is not accessible like a T[M * N].
The second implementation has undefined behaviour. There isn't a helper at that ...
0
votes
Need help understanding pointer to a type of n elements in C (int (*p)[10])?
What you correctly understand is that address is representing a section in memory where something is stored. A pointer to an address is representing the address and the value can be inferred via ...
0
votes
How to group and find average of object in nested arrays?
You can group the items with a map:
let arr = [
[
{date: 1578787200000, displacement: 0},
{date: 1580860800000, displacement: 1},
{date: 1593302400000, displacement: 2},...
0
votes
How to group and find average of object in nested arrays?
You'll need to know the amount of same dates before you can calculate the avarege.
Use reduce to add all displacement on the same date, keep track of the count.
Then map over the grouped result and ...
1
vote
Accepted
How to group and find average of object in nested arrays?
You could group first and then get average per group and result.
const
data = [[{ date: 1578787200000, displacement: 0 }, { date: 1580860800000, displacement: 1 }, { date: 1593302400000, ...
-2
votes
Need help understanding pointer to a type of n elements in C (int (*p)[10])?
I'll suggest you during your starting with pointers to make the notation a bit simpler:
int arr[] = {1,2,3,4,5,6,7,8,9,10}; // Array of numbers
int* parr[10] = &arr; // Array of ...
4
votes
Accepted
Need help understanding pointer to a type of n elements in C (int (*p)[10])?
An array decays into a pointer to its first element.
First, the basics.
arr is an array.
It has type int [10].
The array is located at 0x7fffd215b5d0.
parr is a pointer to an array.
It has type int (*...
0
votes
Need help understanding pointer to a type of n elements in C (int (*p)[10])?
In C, an array does not have a value that can be printed. Mathematically, the value of an array of n elements would be an ordered n-tuple of values, but C does not provide any way to work with ordered ...
0
votes
Need help understanding pointer to a type of n elements in C (int (*p)[10])?
An array is already pointing toward the values it contains.
arr[0] == *arr;
If *parr = &arr, it points towards a pointer that points towards others values.
So double pointing to point on the ...
0
votes
Need help optimizing Java program for Goldbach Conjecture
I used 1's as a true false indicator for your array. I set them all to 1 and then cleared the non primes to 0. Now you do not need to look for primes either num-j is prime or it isn't. I just went ...
Top 50 recent answers are included
Related Tags
arrays × 418199javascript × 93196
php × 72260
java × 52427
python × 34483
c × 30419
c++ × 27319
json × 25530
numpy × 19925
string × 19131
multidimensional-array × 18888
object × 18465
c# × 17689
sorting × 17233
jquery × 13605
loops × 11695
pointers × 10970
swift × 10317
reactjs × 8777
for-loop × 8688
list × 8276
algorithm × 8186
mysql × 8110
ruby × 7677
html × 7641