Have a function Arr(strArr) read the array of strings stored in strArr which will contain only two elements, both of which will represent an array of positive integers. For example of strArr is ["[1, 2, 5, 6]", "[5, 2, 8, 11]"], and goal for this is to add the elements in corresponding locations from both arrays. For the example input, the program should do the following additions: [(1 + 5), (2 + 2), (5 + 8), (6 + 11)] which then equals [6, 4, 13, 17]. Return this resulting array in a string format with each element separated by a hyphen: 6-4-13-17.
If the two arrays do not have the same amount of elements, then simply append the remaining elements onto the new array.
Examples
Input: ["[5, 2, 3]", "[2, 2, 3, 10, 6]"]
Output: 7-4-6-10-6
Input: ["[1, 2, 1]", "[2, 1, 5, 2]"]
Output: 3-3-6-2
Thank you for your help.
The question seems obviously a homework exercise, and as was pointed out in comments that's not what StackOverflow is for; however, I know a lot of students who struggle to know even how to approach a problem. I think helping with that is a good thing, so I won't give a solution to the problem, but rather advice about approaching it.
The general formula that works for most problems is simple: Break the problem into smaller sub-problems, and solve each of those independently, then combine the sub-solutions. If any of those sub-problems are too complicated, repeat the process for those, and so on.
Homework problems, and a lot of real world problems, usually break down into three main sub-problems:
Transform some input into a more conveniently computable form.
Process the transformed input into some computed outputs.
Transform the computed outputs into a specified format.
Applied to your problem, you have:
How to parse a specially formatted string into an array of integers.
How to sum corresponding elements of two arrays, taking into account they may be of different lengths, to produce an array of sums.
How to transform an array of integers into a specially delimited string output.
The solution to your top-level problem will involve applying the sub-solutions in that order, but you don't have to solve them in that order. If you're having difficulty with getting started with the first one, solve one of the easier sub-solutions first to get some momentum. Psychology is actually quite important in problem solving. Believing you can solve it is half of actually solving it, so solve the easier problems first to get that factor working in your favor.
Maybe you regard the sub-problem 3 as the easiest to solve: So write a function place-holder for it (aka, a "stub function"), and make up some input data to test it. This would lead you to write something like this:
func formatOutput(from intArray: [Int]) -> String
{
// Your implementation will go here
}
let actual = formatOutput(from: [1, 2, 3, 4])
let expected = "1-2-3-4"
// If you're doing this in a playground, app, or command line tool
if actual != expected {
fatalError("FAILED: \"\(actual)\" != \"\(expected)\"")
}
else { print("Yay! Passed!") }
// If you're using XCTest
XCTAssertEqual(actual, expected)
That won't even compile yet, because formatOutput has to return something, and it doesn't yet. The key thing is that you've written your usage code first, and expressed in code what you expect. Now focus on the guts of formatOutput. If you want to take a Test Driven Development approach (TDD), maybe at first just return an empty string from formatOutput so you can be sure the code compiles and you see a failing test. Then implement it correctly if you know how, or in small steps if you're not clear on what to do. As you get the exact thing you're testing for working, you can keep adding more tests and improving formatOutput until you've verifiably got it doing everything it's supposed to do. Remember the KISS principle: "Keep It Simple, Stupid!" Don't over-think the solution, and save doing it "cleverly" for another day, which often never comes because the simple thing was sufficient.
At that point you have one of the sub-problems solved, so you move on to the next, following the same pattern. And the next, until all the parts are solved. Then put them together.
You'll note that sub-problem 2 has a bit of an extended description, especially the part specifying that the arrays may be of different lengths. Unless you already know how to solve that problem as stated, that sort of thing indicates it's a good candidate to be broken into yet simpler problems:
2a. How to sum corresponding elements of two arrays of the same length.
2b. How to modify 2a to handle arrays of different lengths.
2b can be done a few different ways:
2.b.1. Apply 2.a to sub-arrays of common length, then handle the remaining part of the longer one separately
OR
2.b.2. Enlarge the shorter array so that it is the same length as the longer one, so 2.a can be applied unmodified.
OR
2.b.3. Modify 2.a so that it can treat the shorter array as though it were the same length as the longer one, without actually copying or adding new elements.
OR
2.b.4. Modify 2.a so that it doesn't have to do anything special for different lengths at all. Hint: think more about the output and its length than the inputs.
When faced with alternatives like that, in the absence of any external constraints that would make one option preferred over the others, pick the one that seems simplest to you (or the most interesting, or the one you think you'd learn the most from). Or if you have time, and want to get the most out of the exercise, implement all of them so you can learn how they are all done, and then pick the one you like best for your final code.
func getResult(strArr: [String]) -> String {
let intArray1 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[0].utf8))) ?? []
let intArray2 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[1].utf8))) ?? []
var arrayResult = zip(intArray1,intArray2).map(+)
let commonCount = arrayResult.count
arrayResult.append(contentsOf: intArray1.dropFirst(commonCount))
arrayResult.append(contentsOf: intArray2.dropFirst(commonCount))
return arrayResult.map(String.init).joined(separator: "-")
}
let result1 = getResult(strArr : ["[5, 2, 3]", "[2, 2, 3, 10, 6]"])
let result2 = getResult(strArr : ["[1, 2, 1]", "[2, 1, 5, 2]"])
You can use this function to get your desired result.
I am learning GO. According to documentation, slices are richer than arrays.
However, I am failing to grasp hypothetical use cases for slices.
What would be use case where one would use a slice instead of array?
Thanks!
This is really pretty elementary and probably should already have been covered in whatever documentation you're reading (unless it's just the language spec), but: A Go array always has a fixed size. If you always need 10 things of type T, [10]T is fine. But what if you need a variable number of things n, where n is determined at runtime?
A Go slice—which consists of two parts, a slice header and an underlying backing array—is pretty ideal for holding information needed to access a variable-sized array. Note that just declaring a slice-header variable:
var x []T
doesn't actually allocate any array of T yet: the slice header will be initialized to hold nil (converted to the right type) as the (missing) backing array, 0 as the current size, and 0 as the capacity of this array. As a result of this, the test x == nil will say that yes, x is nil. To get an actual array, you will need either:
an actual array, or
a call to make, or
use of the built-in append or similar (e.g., copy, append hidden behind some function, etc).
Since the call to make happens at runtime, it can make an array of whatever size is needed at this point. A series of calls to append can build up an array. Note that each call to append may have to allocate a new backing array, or may be able to extend the existing array in-place, depending on what's in the capacity. That's why you need x = append(x, elem) or x = append(x, elems...) and not just append(x, elem) or append(x, elems...).
The Go blog entry on slices has a lot more to say on this. I like this page more than the sequence of pages in the Go Tour starting here, but opinions vary.
I'm looking for an elegant way of useing ndgrid and interpn in a more "general" way - basically for any given size of input and not treat each rank in a separate case.
Given an N-D source data with matching N-D mesh given in a cell-array of 1D vectors for each coordinate Mesh={[x1]; [x2]; ...; [xn]} and the query/output coordinates given in the same way (QueryMesh), how do I generate the ndgrid matrices and use them in the interpn without setting a case for each dimension?
Also, if there is a better way the define the mesh - I am more than willing to change.
Here's a pretty obvious, conceptual (and NOT WORKING) schematic of what I want to get, if it wasn't clear
Mesh={linspace(0,1,10); linspace(0,4,20); ... linsapce(0,10,15)};
QueryMesh={linspace(0,1,20); linspace(0,4,40); ... linsapce(0,10,30)};
Data=... (whatever)
NewData=InterpolateGeneric(Mesh,QueryMesh,Data);
function NewData=InterpolateGeneric(Mesh,QueryMesh,Data)
InGrid=ndgrid(Mesh{:});
OutGrid=ndgrid(QueryMesh{:});
NewData=interpn(InGrid{:},Data,OutGrid{:},'linear',0.0)
end
I think what you are looking for is how to get multiple outputs from this line:
OutGrid = ndgrid(QueryMesh{:});
Since ndgrid produces as many output arrays as input arrays it receives, you can create an empty cell array in this way:
OutGrid = cell(size(QueryMesh));
Next, prove each of the elements of OutGrid as an output argument:
[OutGrid{:}] = ndgrid(QueryMesh{:});
I want to resample an array of elements using the command idresamp(). The input arguments for idresamp function is an array x. So I should get the output as an array. However, I am getting a structure iddata. I don't know how to access the elements /result of the resampling. Can somebody please show how to access the resampled values? Thank you.
x=rand(4000,1); %create some arbitrary data
x_resamp =idresamp(x,2); %resampling factor is 2
Here x_resamp is of iddata type. So, I am unable to access the result. On clicking the variable x_resamp this is what I got
How does one access the resampled values (output). Where is the array? The next step is to calculate the power after resampling and hence I need to use the resampled values.
I am using Matlab R2018a.
If you just want to resample by a factor 2, and have access to the Signal Processing Toolbox, use resample:
y = resample(x,2,1);
If you are insistent on using idresamp, you need to know that it returns an object of type iddata, which comes with a long documentation on usage. I think this complicates things more than you are looking for. It seems you should be able to do:
x_resamp = idresamp(x,2);
y = x_resamp.OutputData;
(but I can't test this because I don't have access to this toolbox.)
you might ask "why don't you just use C?",
but I would like to try constructing an array
with specific element size using python 3, is that possible?
I know bytearray() but it's limited to one byte per element, is there a more flexible function?
also, is there any equivalent statement in python 3 to "sizeof(int)" in C?
I am not talking about sys.getsizeof(int) since it gives me the bytesize of the whole int class
x = [None]*10
This will initialize a list with size 10, but you can also take a look at arrays from the numpy module. This will also have lots of other optimization in it too.
I don't have much experience with your memory problem, but maybe this code will help? http://code.activestate.com/recipes/546530/