How to add two slices/arrays in one map variable

var name_age map[string]int

name := []string{"david", "avid", "stitches", "killeta", "sskrill"}
age := []int{20, 30, 18, 40, 34}

How do you insert slices name and age into name_age map?

I have tried;

for _, i := range names {
	for _, x := range x {
		name_age = map[string]int{i: x}
	}
}

And also tried

for i := 0; i < len(name); i++ {
	for x := 0; x < len(age); x++ {
		mn = map[string]int{name[i]: age[x]}
	}
}

the output in both loops is map[sskrill:34]

When I use

var name_age_x = make(map[string]int)

for i := 0; i < len(name); i++ {
	for x := 0; x < len(age); x++ {
		name_age_x[name[i]] = age[x]
	}
}

The output is map[avid:34 david:34 killeta:34 sskrill:34 stitches:34] ////Age 34 is repeated in all names… /// Even when I use the range loop the result is the same

How do I get this working properly???

NB::: The order of Items should not be altered/sorted so that the age matches with the names.

Assuming both slices have the same length, you can range over one of them and use the index to access both.

name_age := make(map[string]int)

for idx := range names {
  name_age[name[idx]] = age[idx]
}

Please do it practically,

var name_age map[string]int

name := []string{"david", "avid", "stitches", "killeta", "sskrill"}
age := []int{20, 30, 18, 40, 34}

There are the slices, the length is the same in both slices.

Thanks, I have already done it.

Something like this? Using @NobbZ code:

name := []string{"david", "avid", "stitches", "killeta", "sskrill"}
age := []int{20, 30, 18, 40, 34}

name_age := make(map[string]int)

for idx := range name {
 	name_age[name[idx]] = age[idx]
}

fmt.Println(name_age)

https://play.golang.org/p/InYrc39ko2I

So what is the issue with that code?

Thanks a bunch. I have Struggled with this thing for more than 3 hours.

It is working as expected. Thanks

How about making this order all longer chunks get on top and the small ones on bottom as in

https://play.golang.org/p/iwXl2n-gIob

It is working as expected. Thanks

How about making this order all longer chunks get on top and the small ones on bottom as in

https://play.golang.org/p/iwXl2n-gIob

A more simpler easier to read and understand way of chunking slices would be highly appreciated

func chunker(items []string, n int) [][]string {
	if n < 0 {
		return nil
	}

	chunks := make([][]string, n)
	for i := range chunks {
		m := (len(items) + (n - 1)) / n
		chunks[i] = items[:m:m]
		items = items[m:]
		n--
	}
	return chunks
}

Slice Chunk Allocation

We have u unallocated items (len(items)) to allocate over n unallocated chunks. ‘u’ and ‘n’ are integers.

For two integer values x and y, the integer quotient q = x / y and remainder r = x % y satisfy the following relationships:

`x = q*y + r`  and  `|r| < |y|`

with x / y truncated towards zero (“truncated division”).

The Go Programming Language Specification: Arithmetic operators

We allocate u / n (integer division) items plus the u % n (integer division) remainder items to unallocated chunks. We allocate the u % n remainder items to the first u % n unallocated chunks.

The first u % n (may be zero) unallocated chunks will contain u / n + 1 items and the other chunks will contain u / n items for a total of u items in n chunks.

For u unallocated items (len(items)) and n unallocated chunks, m items, rounded up, are allocated to a chunk:

`m := (u + (n - 1)) / n`

then, for the next iteration,

`u = u - m`  // items = items[m:]
`n = n - 1`  // n--

We know that all the items will be allocated since, for the last chunk iteration (n == 1),

`m := (u + (1 - 1)) / 1`

Simplifying,

`m := u

Go Slices and Arrays

The Go Blog: Go Slices: usage and internals

The Go Blog: Arrays, slices (and strings): The mechanics of ‘append’

The Go Programming Language Specification,

The Go Programming Language, Alan A. A. Donovan and Brian W. Kernighan

1 Like

Thanks a bunch… I wish you had added comments so that i can understand what is really going on. I have been fearing things to do with arrays and slices.
I guess my head just cant wrap around how they work but with time i’ll finally understand.
Thanks for the answer and I would really appreciate if you led m into th way of undestanding how arrays work and do they work the same in all languages.

func chunker(items []string, n int) [][]string {
chunks := make([][]string, n)
for i := 0; i < len(chunks); i++ {
m := (len(items) + (n - 1)) / n
chunks[i] = items[:m]
items = items[m:]
n–
}
return chunks
}

This looks more intresting since it doesn’t have an if condition inside it

Thanks buddy…

So what does this mean

chunks[i] = items[:m:m]

I understand i is the incremented value.
What does items[:m:m]

: stands for start of array, m end of array and second m stands for?
When I decrement n using value 14 i get

n := 14
chunks := make([][]string, n)
for i := range chunks {
	m := (260 + (n - 1)) / n
	n--
	fmt.Printf("CHUNK %2d = %d\n", i, m)
}`

CHUNK 0 = 19
CHUNK 1 = 20
CHUNK 2 = 22
CHUNK 3 = 24
CHUNK 4 = 26
CHUNK 5 = 29
CHUNK 6 = 33
CHUNK 7 = 38
CHUNK 8 = 44
CHUNK 9 = 52
CHUNK 10 = 65
CHUNK 11 = 87
CHUNK 12 = 130
CHUNK 13 = 260

What are values on the right side “m” used for?

Why do this items = items[m:]?

if you learn to use a step debugger and it would have been painfully apparent in about 3 seconds why your code was wrong and what it was doing and how to fix it.

Follow the link that I provided earlier to The Go Programming Language Specification.

The Go Programming Language Specification

In particular, for slices:

Slice types

Index expressions

Slice expressions

chunks[i] = items[:m:m]

Assigns the value of the subslice items[:m:m] to the variable chunks[i].

items[:m:m]

is a full slice expression.

m := (len(items) + (n - 1)) / n

m is the number of unallocated items to be allocated to chunk[i].

items = items[m:]

items[m:] is a simple slice expression. The items variable represents the unallocated items. Once we have allocated m items, update items. This updates the value of len(items).

You didn’t copy my code correctly. What are you trying to accomplish?

If you insert a debug print statement in my code you will get sensible results.

Thanks… This now makes me understand it completely… was wondering what’s the purpose of declaring items = items[m:]. Now I get that it is used to update the value of len(items)

Thanks. Had no idea about a step debugger. I am self learning in programming so dont have a guide on how things work around.

Started with java but when I got into db CRUDs gave up, researched online other programming languages tried out a few and fell in love with Golang because of its simplicity and its ease in db connection and set up and its somehow oop nature. Though receivers and & are new and abit complicated to get used to.

knowing your tools is the biggest part of the job. step debuggers are the best way of debugging, they show the the state of everything and you can see in “slow motion” one step at a time as things change.

Thanks guys for all the solutions and assistace, I have really learnt a lot from u.
Now i want to insert the chunks in a html page but it is not working
I already posted the issue here.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.