Computer Science, asked by BrainlyProgrammer, 9 hours ago


What will be the output?

a= [2,[3,[2,2,4],4,5],[6,[4,4],8]]
print(a[1][1][1])
print(a[2][1])
#Good Luck! All the best!!

Language: Ruby​

Answers

Answered by TheMoonlìghtPhoenix
12

Explanation:

For this, we need to understand nested arrays -

Nested arrays are those which can be contained one inside another simultaneously.

For example, a sample question :-

arr = [1,2,3],[4,5]

puts arr[0][2]

This gives us the output :-

1st set ie [1,2,3]

And, the third element of that set :-

0th term - 1

1st term - 2

2nd term - 3

So, the output would be 3.

Coming to the original question :-

  • Number of brackets in the given array = 5.
  • Number of brackets in [1][1][1] = 3 pairs.

Now, we can see that :-

[1] of 1st puts gives us array [3,[2,2,4],4,5]

Tip :- There are 5 nested arrays. It always starts from zero.

Now, in that array:-

[1] of that array gives us [2,2,4] (remember the tip)

And final step is :-

[1], the third time, gives us 2 as the output as 1st 2 is counted as zero and second one as 2, then third would have been 4 [2] .

print(a[2][1])

Here, again we need to look for 0th, then 1st and the 2nd element.

Here, the element is 2[6,[4,4],8]] (count straight, this is the 3rd element)

Again, here the elements are :-

0th - 6

1st - [4,4]

2nd - 8

We won't count the 2 as it's outside the nested portion.

We needed [1]

So, the output will be 2[4,4].


anindyaadhikari13: Perfect answer!
TheMoonlìghtPhoenix: Thank you! :D
Similar questions