PANIC=runtime error: index out of range - arrays

I have the following code, but i can't figure out why the error:PANIC=runtime error: index out of range is happening
type Board struct {
Tboard [9]string
Player1 Player
Player2 Player
}
func makeBoard() *Board {
b := &Board{Tboard: [9]string{}}
for x := 0; x < len(b.Tboard); x++ {
b.Tboard[x] = E // E = "[ ]"
fmt.Println(b.Tboard[x])
}
fmt.Println(len(b.Tboard)) // => 9
fmt.Print("Error: ")
fmt.Println(b) // => Error: %!v(PANIC=runtime error: index out of range)
fmt.Println(b.Tboard) // => [[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]]
return b
}

Related

Initialize the size of global array

I need to put the output of arr in global array because I need to use the array in main function. How can I initialize the array in global and I don't know the size of it ? any idea please?
globarr[]; // how to set the size here?
int *suma(int *output, int *arr)
{
*output = 0;
for (int i = 0; i < 100; i++) {
arr[i] = i;
*output += arr[i];
}
return arr;
}
void prose(){
int *by;
int output;
int arr[100];
by = suma(&output, arr);
for (ont i=0; i<output; i++) {
globarr[i] = n[i];
}
}
void main()
{
prose();
// here I need to use the values of globarr
}
I need to put the output of arr in global array
The only reason you might need to do that would be that some external authority you are bound to obey placed such an arbitrary, unnatural requirement.
It is possible to write conforming C code for any task, using only the C standard library, that does not rely on any global variables other than those few provided by the standard library itself.
because I need to use the array in main function. How can I initialize the array in global and I don't know the size of it ?
You cannot. The size of an array declared at file scope must be an integer constant expression, which means, among other things, that it must be computable at compile time.
any idea please?
You have two main alternatives:
Choose an upper bound on the size your program will support, and declare an array large enough for that. Make the program abort if otherwise it would try to use more elements of the array than are available.
Use a dynamically allocated space instead of a (declared) array.
Use function parameters and return values not global variables
long long suma(int **arr, size_t size)
{
long long output = 0;
*arr = malloc(size * sizeof(**arr));
if(*arr)
{
for (size_t i = 0; i < size; i++)
{
(*arr)[i] = i;
output += (*arr)[i];
}
}
return output;
}
#define SIZE 100
void main(void)
{
int *array;
long long output = suma(&array, SIZE);
printf("Sum of elements = %lld\n", output);
/* you can use the array */
if(array)
{
for(size_t i = 0; i < SIZE; i++)
{
printf("[%3zu]=%d%s", i, array[i], ((i + 1) % 10) ? ",\t" : "\n");
}
}
free(array);
}
https://godbolt.org/z/EPdxfPzoq
Output:
Sum of elements = 4950
[ 0]=0, [ 1]=1, [ 2]=2, [ 3]=3, [ 4]=4, [ 5]=5, [ 6]=6, [ 7]=7, [ 8]=8, [ 9]=9
[ 10]=10, [ 11]=11, [ 12]=12, [ 13]=13, [ 14]=14, [ 15]=15, [ 16]=16, [ 17]=17, [ 18]=18, [ 19]=19
[ 20]=20, [ 21]=21, [ 22]=22, [ 23]=23, [ 24]=24, [ 25]=25, [ 26]=26, [ 27]=27, [ 28]=28, [ 29]=29
[ 30]=30, [ 31]=31, [ 32]=32, [ 33]=33, [ 34]=34, [ 35]=35, [ 36]=36, [ 37]=37, [ 38]=38, [ 39]=39
[ 40]=40, [ 41]=41, [ 42]=42, [ 43]=43, [ 44]=44, [ 45]=45, [ 46]=46, [ 47]=47, [ 48]=48, [ 49]=49
[ 50]=50, [ 51]=51, [ 52]=52, [ 53]=53, [ 54]=54, [ 55]=55, [ 56]=56, [ 57]=57, [ 58]=58, [ 59]=59
[ 60]=60, [ 61]=61, [ 62]=62, [ 63]=63, [ 64]=64, [ 65]=65, [ 66]=66, [ 67]=67, [ 68]=68, [ 69]=69
[ 70]=70, [ 71]=71, [ 72]=72, [ 73]=73, [ 74]=74, [ 75]=75, [ 76]=76, [ 77]=77, [ 78]=78, [ 79]=79
[ 80]=80, [ 81]=81, [ 82]=82, [ 83]=83, [ 84]=84, [ 85]=85, [ 86]=86, [ 87]=87, [ 88]=88, [ 89]=89
[ 90]=90, [ 91]=91, [ 92]=92, [ 93]=93, [ 94]=94, [ 95]=95, [ 96]=96, [ 97]=97, [ 98]=98, [ 99]=99

Number of connections in a hash of arrays

I have a hash of arrays like the following:
my %HoA = (
"M" => [ "L", "E" ],
"L" => [ "I" ],
"E" => [ "B", "C" ],
"B" => [ "A" ],
"C" => [ "A" ]
);
You can visualize it in this way:
M
/ \
L E
/ / \
I B C
\ /
A
Now, I would like to know the number of connections for every node:
M 6
E 3
L 1
B 1
C 1
I 0
A 0
With the igraph package in R this is straightforward but I am struggling to do the same with a hash of arrays in Perl.
You can build graphs in Perl using the Graph module
You need a Graph::Directed object
Here's an example
use strict;
use warnings 'all';
use Graph::Directed;
my %HoA = (
"M" => [ "L", "E" ],
"L" => [ "I" ],
"E" => [ "B", "C" ],
"B" => [ "A" ],
"C" => [ "A" ]
);
# Build the graph
#
my $g = Graph::Directed->new;
while ( my ($from, $to) = each %HoA ) {
$g->add_edge($from, $_) for #$to;
}
# Build a table of successors of each vertex
#
my %succ;
for my $v ( $g->vertices ) {
my #succ = $g->all_successors($v);
$succ{$v} = \#succ;
}
# Print the vertices in descending order of successors
#
for my $v ( sort { #{$succ{$b}} <=> #{$succ{$a}} } $g->vertices ) {
printf "%s %d\n", $v, scalar #{$succ{$v}};
}
output
M 6
E 3
C 1
B 1
L 1
A 0
I 0

Format JSON Array format to another JSON Array format

Here is the my JSON Array format
[
[
"1234",
[
"Name11"
],
"4567",
[
"Name12"
],
"7890",
[
"Name13"
]
],
[
"1234",
[
"Name21"
],
"4567",
[
"Name22"
],
"7890",
[
"Name23"
]
]
]
The "1234","4567" and "7890" are my Ids and "Name11","Name12", "Name13", "Name21", "Name22" and "Name23" are the values for each corresponding Ids.
The JSON array contains two records as shown above. Now i need to convert the following JSON Format....
[
{
"1234":"Name11",
"4567":"Name12",
"7890":"Name13"
},
{
"1234":"Name21",
"4567":"Name22",
"7890":"Name23"
}
]
Please help me out, how can i construct the above mentioned JSON array format.
With pure javascript:
var src = [
[
"1234",
[
"Name11"
],
"4567",
[
"Name12"
],
"7890",
[
"Name13"
]
],
[
"1234",
[
"Name21"
],
"4567",
[
"Name22"
],
"7890",
[
"Name23"
]
]
]
var newObj = []
for(var i = 0; i< src.length; i++){
var item = {}
for(var j = 0; j<src[i].length; j++){
if(j%2 === 0){
item[src[i][j]] = ""
}else{
item[src[i][j-1]] = src[i][j][0]
}
}
newObj.push(item)
}
You can do it with the following code (see the snippet below):
var res = src.map(function(a){
var arr = [];
for(var i=0;i<a.length/2;i++) {
var item = {};
item[a[i*2]] = a[i*2+1][0];
arr.push(item);
};
return arr;
});
var src = [
[
"1234",
[
"Name11"
],
"4567",
[
"Name12"
],
"7890",
[
"Name13"
]
],
[
"1234",
[
"Name21"
],
"4567",
[
"Name22"
],
"7890",
[
"Name23"
]
]
];
var res = src.map(function(a){
var arr = [];
for(var i=0;i<a.length/2;i++) {
var item = {};
item[a[i*2]] = a[i*2+1][0];
arr.push(item);
};
return arr;
});
document.getElementById("res").textContent = JSON.stringify(res);
<div id="res"></div>

Mongodb array maching

I have the following document:
{ arr : [1,2,3] }
And I have to compare it with the following:
a : [1,2]
b : [2,3,1]
c : [2,5,3,1]
I need to make a query that return arr only when it match all the elements of the query array.
In the example, it would be "b" and "c"
I have tried with $all like the following:
find(arr:{$all:a}) (the same for b and c)
but this does not work because it match "a" too. :(
Try this:
find( {$or:[
{ $and: [ { arr: 1 }, { arr: 2 }, {arr:{$size:2}} ] },
{ $and: [ { arr: 1 }, { arr: 2 }, { arr: 3 }, {arr:{$size:3}} ] },
{ $and: [ { arr: 1 }, { arr: 2 }, { arr: 3 }, { arr: 5 }, {arr:{$size:4}} ] }
]})
or maybe with the $all operator (i haven't tryied that before but should be ok):
find( {$or:[
{ $and: [ { arr: { $all: a } }, {arr:{$size: a.length }} ] },
{ $and: [ { arr: { $all: b } }, {arr:{$size: b.length }} ] },
{ $and: [ { arr: { $all: c } }, {arr:{$size: c.length }} ] }
]})
You can use the aggregation framework and its set operations to select arrays which are subsets of the query array:
> db.foo.insert({arr:[1,2,3]})
> db.foo.insert({arr:[3,2,1]})
> db.foo.insert({arr:[3,2,1,4]})
and then
db.foo.aggregate([
{ $project: { arr:'$arr', isIn: { $setIsSubset: ['$arr', [2,5,3,1]] }}},
{ $match: { isIn: true }}
])
returns
{ "_id" : ObjectId("5345beb536cdafd3eb4a6b16"), "arr" : [ 1, 2, 3 ], "isIn" : true }
{ "_id" : ObjectId("5345bec036cdafd3eb4a6b17"), "arr" : [ 3, 2, 1 ], "isIn" : true }
Note that this requires version 2.6+

Getting array elements using array index in mongoDB

Consider following collection in mongoDB :
{a:[4,2,8,71,21]}
{a:[24,2,2,1]}
{a:[4,1]}
{a:[4,2,8,21]}
{a:[2,8,71,21]}
{a:[4,2,8]}
How can I get following results in a most easily:
Getting nth element of array
{a:4}
{a:24}
{a:4}
{a:4}
{a:2}
{a:4}
Getting elements 2 to 4
{a:[8,71,21]}
{a:[2,1]}
{a:[]}
{a:[8,21]}
{a:[71,21]}
{a:[8]}
And other similar queries.
What you are looking for is the $slice projection.
Getting a number of elements from the beginning of an array
You can pass a simple $limit with a number of values to return (eg. 1):
> db.mycoll.find({}, {_id: 0, a: { $slice: 1}})
{ "a" : [ 4 ] }
{ "a" : [ 24 ] }
{ "a" : [ 4 ] }
{ "a" : [ 4 ] }
{ "a" : [ 2 ] }
{ "a" : [ 4 ] }
Getting a range of elements
You can pass an array with parameters of ( $skip, $limit ).
Note: to match your expected output you would have to find elements 3 to 5 (skip the first 2 elements, return the next 3):
> db.mycoll.find({}, {_id: 0, a: { $slice: [2,3]}})
{ "a" : [ 8, 71, 21 ] }
{ "a" : [ 2, 1 ] }
{ "a" : [ ] }
{ "a" : [ 8, 21 ] }
{ "a" : [ 71, 21 ] }
{ "a" : [ 8 ] }
Getting the nth element of array
Pass the number of elements to $skip and a value of 1 for the limit.
For example, to find the second element you need to skip 1 entry:
> db.mycoll.find({}, {_id: 0, a: { $slice: [1,1]}})
{ "a" : [ 2 ] }
{ "a" : [ 2 ] }
{ "a" : [ 1 ] }
{ "a" : [ 2 ] }
{ "a" : [ 8 ] }
{ "a" : [ 2 ] }
Note that the $slice operator:
always returns an array
will return an empty array for documents that match the find criteria but return an empty result for the $slice selection (eg. if you ask for the 5th element of an array with only 2 elements)

Resources