Row And Column Major Solidity - multidimensional-array

I'm curious to know for a multi-dimension array in Solidity, are the data stored as a row-major or column major order.
Thank you in advance

Generally in row-major order. This is valid for all arrays in memory and calldata locations, and for fixed-size arrays in storage.
One exception: Dynamic-size arrays in storage are accessible using a hash of their variable storage slot ID and indexes. So the rows might not be consequent. But the values are still stored in row-major.
Docs: https://docs.soliditylang.org/en/latest/internals/layout_in_storage.html#mappings-and-dynamic-arrays
pragma solidity ^0.8;
contract MyContract {
uint[2][2] public fixedArray;
uint[][] public dynamicArray;
constructor() {
fixedArray[0][0] = 1;
fixedArray[0][1] = 2;
fixedArray[1][0] = 3;
fixedArray[1][1] = 4;
// workaround - cannot resize in-memory dynamic-size arrays
// so we declare a "dynamic array with predefined length" in memory
uint[] memory dynamicArrayNested1 = new uint[](2);
dynamicArrayNested1[0] = 5;
dynamicArrayNested1[1] = 6;
dynamicArray.push(dynamicArrayNested1);
uint[] memory dynamicArrayNested2 = new uint[](2);
dynamicArrayNested2[0] = 7;
dynamicArrayNested2[1] = 8;
dynamicArray.push(dynamicArrayNested2);
}
}
Storage debug:
Fixed-size array:
Dynamic-size array:
First value is size of the top array (== 2)
Second value is size of the first nested array (== 2)
Followed by values of the first nested array
Then there's size of the second nested array (== 2)
And finally values of the second nested array

Related

How add data in nested relation? I have" Must be non-negative and less than the size of the collection" error [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 7 years ago.
I'm getting one of the following errors:
"Index was out of range. Must be non-negative and less than the size of the collection"
"Insertion index was out of range. Must be non-negative and less than or equal to size."
"Index was outside the bounds of the array."
What does it mean, and how do I fix it?
See Also
IndexOutOfRangeException
ArgumentOutOfRangeException
Why does this error occur?
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.
How indexing arrays works
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.
How other collections work
Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.

Combination Sum in Go

/*
Given an array: [1,2] and a target: 4
Find the solution set that adds up to the target
in this case:
[1,1,1,1]
[1,1,2]
[2,2]
*/
import "sort"
func combinationSum(candidates []int, target int) [][]int {
sort.Ints(candidates)
return combine(0, target, []int{}, candidates)
}
func combine(sum int, target int, curComb []int, candidates []int) [][]int {
var tmp [][]int
var result [][]int
if sum == target {
fmt.Println(curComb)
return [][]int{curComb}
} else if sum < target {
for i,v := range candidates {
tmp = combine(sum+v, target, append(curComb, v), candidates[i:])
result = append(result,tmp...)
}
}
return result
}
This is a problem in Leetcode and I use recursion to solve it.
In line 18, I print every case when the sum is equal to the target.
The output is :
[1,1,1,1]
[1,1,2]
[2,2]
And that is the answer that I want!
But why is the final answer (two-dimensional):
[[1,1,1,2],[1,1,2],[2,2]]
Expected answer is : [[1,1,1,1],[1,1,2],[2,2]]
Please help me find the mistake in the code. Thanks for your time.
This happens because of the way slices work. A slice object is a reference to an underlying array, along with the length of the slice, a pointer to the start of the slice in the array, and the slice's capacity. The capacity of a slice is the number of elements from the beginning of the slice to the end of the array. When you append to a slice, if there is available capacity for the new element, it is added to the existing array. However, if there isn't sufficient capacity, append allocates a new array and copies the elements. The new array is allocated with extra capacity so that an allocation isn't required for every append.
In your for loop, when curComb is [1, 1, 1], its capacity is 4. On successive iterations of the loop, you append 1 and then 2, neither of which causes a reallocation because there's enough room in the array for the new element. When curComb is [1, 1, 1, 1], it is put on the results list, but in the next iteration of the for loop, the append changes the last element to 2 (remember that it's the same underlying array), so that's what you see when you print the results at the end.
The solution to this is to return a copy of curComb when the sum equals the target:
if sum == target {
fmt.Println(curComb)
tmpCurComb := make([]int, len(curComb))
copy(tmpCurComb, curComb)
return [][]int{tmpCurComb}
This article gives a good explanation of how slices work.

How get random item from es6 Map or Set

I have a project that uses arrays of objects that I'm thinking of moving to es6 Sets or Maps.
I need to quickly get a random item from them (obviously trivial for my current arrays). How would I do this?
Maps and Sets are not well suited for random access. They are ordered and their length is known, but they are not indexed for access by an order index. As such, to get the Nth item in a Map or Set, you have to iterate through it to find that item.
The simple way to get a random item from a Set or Map would be to get the entire list of keys/items and then select a random one.
// get random item from a Set
function getRandomItem(set) {
let items = Array.from(set);
return items[Math.floor(Math.random() * items.length)];
}
You could make a version that would work with both a Set and a Map like this:
// returns random key from Set or Map
function getRandomKey(collection) {
let keys = Array.from(collection.keys());
return keys[Math.floor(Math.random() * keys.length)];
}
This is obviously not something that would perform well with a large Set or Map since it has to iterate all the keys and build a temporary array in order to select a random one.
Since both a Map and a Set have a known size, you could also select the random index based purely on the .size property and then you could iterate through the Map or Set until you got to the desired Nth item. For large collections, that might be a bit faster and would avoid creating the temporary array of keys at the expense of a little more code, though on average it would still be proportional to the size/2 of the collection.
// returns random key from Set or Map
function getRandomKey(collection) {
let index = Math.floor(Math.random() * collection.size);
let cntr = 0;
for (let key of collection.keys()) {
if (cntr++ === index) {
return key;
}
}
}
There's a short neat ES6+ version of the answer above:
const getRandomItem = iterable => iterable.get([...iterable.keys()][Math.floor(Math.random() * iterable.size)])
Works for Maps as well as for Sets (where keys() is an alias for value() method)
This is the short answer for Sets:
const getRandomItem = set => [...set][Math.floor(Math.random()*set.size)]

java 8: How to convert following code to functional?

Instead of using the for loop, how do I use the Stream API of Java 8 on array of booleans? How do I use methods such as forEach, reduce etc.?
I want to get rid of the two variables totalRelevant and retrieved which I am using to maintain state.
As in a lambda expression, we can only reference final variables from its lexical context.
import java.util.Arrays;
import java.util.List;
public class IRLab {
public static void main(String[] args) {
// predefined list of either document is relevant or not
List<Boolean> documentRelivency = Arrays.asList(true, false, true, true, false);
System.out.println("Precision\tRecall\tF-Measure");
// variables for output
double totalRelevant = 0.0;
double retrieved = 0.0;
for (int i = 0; i < documentRelivency.size(); ++i) {
Boolean isRelevant = documentRelivency.get(i);
// check if document is relevant
if (isRelevant) totalRelevant += 1;
// total number of retrieved documents will be equal to
// number of document being processed currently, i.e. retrieved = i + 1
retrieved += 1;
// storing values using formulas
double precision = totalRelevant / retrieved;
double recall = totalRelevant / totalRelevant;
double fmeasure = (2 * precision * recall) / (precision + recall);
// Printing the final calculated values
System.out.format("%9.2f\t%.2f\t%.2f\t\n", precision, recall, fmeasure);
}
}
}
How do I convert above code to functional code using the Java 8 Stream API and Lambda Expressions? I need to maintain state for two variables as above.
Generally, converting imperative to a functional code will only be an improvement when you manage to get rid of mutable state that causes the processing of one element to depend on the processing of the previous one.
There are workarounds that allow you to incorporate mutable state, but you should first try to find a different representation of your problem that works without. In your example, the processing of each element depends on two values, totalRelevant and retrieved. The latter is just an ascending number and therefore can be represented as a range, e.g. IntStream.range(startValue, endValue). The second stems from your list of boolean values and is the number of true value inside the sublist (0, retrieved)(inclusive).
You could recalculate that value without needing the previous value, but reiterating the list in each step could turn out to be expensive. So instead, collect your list into a single int number representing a bitset first, i.e. [true, false, true, true, false] becomes 0b_10110. Then, you can get the number of one bits using intrinsic operations:
List<Boolean> documentRelivency = Arrays.asList(true, false, true, true, false);
int numBits=documentRelivency.size(), bitset=IntStream.range(0, numBits)
.map(i -> documentRelivency.get(i)? 1<<(numBits-i-1): 0).reduce(0, (i,j) -> i|j);
System.out.println("Precision\tRecall\tF-Measure");
IntStream.rangeClosed(1, numBits)
.mapToObj(retrieved -> {
double totalRelevant = Integer.bitCount(bitset&(-1<<(numBits-retrieved)));
return String.format("%9.2f\t%.2f\t%.2f",
totalRelevant/retrieved, 1f, 2/(1+retrieved/totalRelevant));
})
.forEach(System.out::println);
This way, you have expressed the entire operation in a functional way where the processing of one element does not depend on the previous one. It could even run in parallel, though this would offer no benefit here.
If the list size exceeds 32, you have to resort to long, or java.util.BitSet for more than 64.
But the whole operation is more an example of how to change the thinking from “this is a number I increment in each iteration” to “I’m processing a continuous range of values” and from “this is a number I increment when the element is true” to “this is the count of true values in a range of this list”.
It's unclear why you need to change your code to lambdas. Currently it's quite short and lambdas will not make it shorter or cleaner. However if you really want, you may encapsulate your shared state in the separate object:
static class Stats {
private int totalRelevant, retrieved;
public void add(boolean relevant) {
if(relevant)
totalRelevant++;
retrieved++;
}
public double getPrecision() {
return ((double)totalRelevant) / retrieved;
}
public double getRecall() {
return 1.0; // ??? was totalRelevant/totalRelevant in original code
}
public double getFMeasure() {
double precision = getPrecision();
double recall = getRecall();
return (2 * precision * recall) / (precision + recall);
}
}
And use with lambda like this:
Stats stats = new Stats();
documentRelivency.forEach(relevant -> {
stats.add(relevant);
System.out.format("%9.2f\t%.2f\t%.2f\t\n", stats.getPrecision(),
stats.getRecall(), stats.getFMeasure());
});
Lambda is here, but not Stream API. Seems that involving Stream API for such problem is not very good idea as you need to output the intermediate states of mutable container which should be mutated strictly in given order. Well, if you desperately need Stream API, replace .forEach with .stream().forEachOrdered.

how to store contetnts of a several array in a matrix in C

I am trying to store contents of different vectors in a matrix.
length of vectors are different and they are all strings. lets say:
A=["MXAA', "MXBB", "MXCC"]
B=["JJJ", "LKLKLKL"]
so the new matrix should look like the following:
C= [MXAA, MXBB, MXCC;JJJ, LKLKLKL, 0]
is the a way to do that in C?
thanks
You would need to create an array of pointers to pointer to the element type (which in your case is a pointer to char).
The problem you need to consider is that every array is different size; so I suggest you store the size of the arrays, or you will quickly end up running over the bounds of an array. This sounds a bit like a custom type.
typedef {
int n;
char **strArr;
} stringArray;
stringArray *str2d;
str2d = (stringArray*) malloc(2*sizeof(stringArray));
str2d[0].n=3;
str2d[0].strArr = (char**)malloc(3*sizeof(char*));
str2d[0].strArr[0] = "MXAA";
str2d[0].strArr[1] = "MXBB";
str2d[0].strArr[2] = "MXCC";
str2d[1].n = 2;
str2d[1].strArr = (char**)malloc(2*sizeof(char*));
str2d[1].strArr[0] = "JJJ";
str2d[1].strArr[1] = "LKLKLKL";
If you want to access an element you use similar addressing - but check that you stay within bounds!
I deliberately did this in very explicit steps, hoping this makes the principle clear. There are better ways to do this but they are more obscure (or not "standard C")

Resources