Posts

Showing posts with the label arrays

How *(&arr + 1) - arr is working to give the array size [duplicate]

32 5 This question already has answers here : How does *(&arr + 1) - arr give the length in elements of array arr? (3 answers) Why are the values different? C++ pointer (2 answers) Closed 3 days ago . int arr[] = { 3, 5, 9, 2...

Why does an array allow a string as an index in JavaScript? [closed]

2 3 Closed . This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 8 days ago . Improve this question As we already know, one of the di...

How can I get next few elements in an array but jump back to the start when passing the last element?

6 1 Imagine I have the following simple array: const myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"]; Now I want to get the next for instance 3 elements after "el5" (index 4). As you can see there are only 2 elements left in the array. When hitting last index in the array I want to go back to the start and continue there. This should be the expected output when the start is "el5" (index 4): ["el6", "el7", "el1"] . And this is what I've tried so far. const myArr = ["el1", "el2", "el3", "el4", "el5", "el6", "el7"]; let output = []; const followingElementsCount =...

Sum all data in array of objects into new array of objects

I have an array of objects that looks like this: var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}] and I want to sum each element in the array to produce an array like this: var result = [{costOfAirtickets: 4000, costOfHotel: 3200}] I have used a map and reduce function but I was able to only sum an individual element like so: data.map(item => ite.costOfAirtickets).reduce((prev, next)=>prev + next); // 22 At the moment this produces a single value which is not what I want as per initial explanation. Is there a way to do this in Javascript or probably with lodash. Using for..in to iterate object and reduce to iterate array var data = [{costOfAirtickets: 2500, costOfHotel: 1200},{costOfAirtickets: 1500, costOfHotel: 1000}]; var result = [data.reduce((acc, n) => { for (var prop in n) { if (acc.hasOwnProperty(prop)) acc[prop] += n[prop]; else acc[prop] = n[prop]; } return acc; }, {})] console.log(result) Us...

Find duplicate in array with a memory efficient approach

A is an array of integers. All the values are between 0 to A.Length-1 it means 0 <= A[i] <= A.Length-1 I am supposed to find repeating elements; and if there are several repeating elements, then choose the one that has lower index for the repeated item. for example: a = [3, 4, 2, 5, 2, 3] then result = 2 This was an interview question. I used another array to store items and check when it is repeating. Then it gave me time-out for some test cases. The interviewer advised to only loop over the array only once, and do not create any additional data structure. No need for another data structure. You can use the input itself as a hashset. Every time you see a value, add A.Length to the item that corresponds to that index. As values might have been already incremented, you should look at the value as A[i] mod A.length. If you find an item that is already >= A.length.. you have a repetition. (Remember that the problem states that all items are in the interval [0, A.Length-1]) T...

Why is it allowed to declare an automatic array with size depending on user input? [duplicate]

This question already has an answer here: Why aren't variable-length arrays part of the C++ standard? 13 answers I'm using MinGW to compile for C++11 and I found out that this doesn't throw an error: int S; cin>>S; char array[S]; While this does ("storage size of 'array' isn't known"): char array[]; To me, the size is also unknown in the first case, as it depends on what the user input is. As far as I knew, automatic arrays are allocated at compile time in stack memory. So why wouldn't the first example fail? It's not. C++ doesn't have variable-length arrays, though some compilers allow it as an extension of the language. I don't have enough reputation to comment so I am using an answer. Please don't be cruel to me :-) You are apparently not aware of the GNU GCC extension Arrays of Variable Length. Therefore your first code co...

How to get all substrings (contiguous subsequences) of my JavaScript array?

My task is to split the given array into smaller arrays using JavaScript. For example [1, 2, 3, 4] should be split to [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [2] [2, 3] [2, 3, 4] [3] [3, 4] [4]. I am using this code: let arr = [1, 2, 3, 4]; for (let i = 1; i <= arr.length; i++) { let a = []; for (let j = 0; j < arr.length; j++) { a.push(arr[j]); if (a.length === i) { break; } } console.log(a); } And I get the following result: [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] undefined What am I missing/doing wrong? You have two issues in your code: You need to have loop to initialize with the value of i for the inner loop so that it consider the next index for new iteration of i You need to remove that break on the length which you have in inner loop. let arr = [1, 2, 3, 4]; for (let i = 0; i <= arr.length; i++) { let a = []; for (let j = i; j < arr.length; j++) { a.push(arr[j]); console.log(a); } } For the inner array, you could just start with...

Array#push causes “stack level too deep” error with large arrays

I made two arrays, each with 1 million items: a1 = 1_000_000.times.to_a a2 = a1.clone I tried to push a2 into a1: a1.push *a2 This returns SystemStackError: stack level too deep. However, when I try with concat, I don't get the error: a1.concat a2 a1.length # => 2_000_000 I also don't get the error with the splat operator: a3 = [*a1, *a2] a3.length # => 2_000_000 Why is this the case? I looked at the documentation for Array#push, and it is written in C. I suspect that it may be doing some recursion under the hood, and that's why it's causing this error for large arrays. Is this correct? Is it not a good idea to use push for large arrays? I think that this is not a recursion error, but an argument stack error. You are running up against the limit of the Ruby VM stack depth for arguments. The problem is the splat operator, which is passed as an argument to push. The splat operator is expanded into a million element argument list for push. As function arguments ...

Convert double to int array

I have a double double pi = 3.1415; I want to convert this to a int array int[] piArray = {3,1,4,1,5}; I came up with this double pi = 3.1415; String piString = Double.toString(pi).replace(".", ""); int[] piArray = new int[piString.length()]; for (int i = 0; i <= piString.length()-1; i++) piArray[i] = piString.charAt(i) - '0'; It's working but I don't like this solution because I think a lot of conversions between datatypes can lead to errors. Is my code even complete or do I need to check for something else? And how would you approach this problem? I don't know straight way but I think it is simpler: int[] piArray = String.valueOf(pi) .replaceAll("\\D", "") .chars() .map(Character::getNumericValue) .toArray(); Since you want to avoid casts, here's the arithmetic way, supposing you only have to deal with positive numbers...

Confusion about array initialization in C

In C language, if initialize an array like this: int a[5] = {1,2}; then all the elements of the array that are not initialized explicitly will be initialized implicitly with zeroes. But, if I initialize an array like this: int a[5]={a[2]=1}; printf("%d %d %d %d %d\n", a[0], a[1],a[2], a[3], a[4]); output: 1 0 1 0 0 I don't understand, why does a[0] print 1 instead of 0? Is it undefined behaviour? Note: This question was asked in an interview. TL;DR: I don't think the behavior of int a[5]={a[2]=1}; is well defined, at least in C99. The funny part is that the only bit that makes sense to me is the part you're asking about: a[0] is set to 1 because the assignment operator returns the value that was assigned. It's everything else that's unclear. If the code had been int a[5] = { [2] = 1 }, everything would've been easy: That's a designated initializer setting a[2] to 1 and everything else to 0. But with { a[2] = 1 } we have ...