Swift sum numbers in array adding from specific element - arrays

Let's say I have some numbers in an array like below
let numberArray = [1, 3, 4, 6, 9, 14, 16]
I know how to sum them all up by using reduce method but how can I start adding numbers from specific element. For example:
//Sum all up by reduce
let sumAll = numberArray.reduce(0, +)
//sumAll = 53
//I want to start counting from the fourth element in the array which is 6
//so the total should be 45. [6 + 9 + 14 + 16]
What method should I use to achieve this?
Thanks in advance.

You can either use dropFirst(_:) or use a range as the index.
If it's not a fixed number, you could first use firstIndex(of:) to determine the index where you want to start.
numberArray.dropFirst(3).reduce(0, +)
numberArray[3...].reduce(0, +)

Run reduce on the desired subarray:
let numberArray = [1, 3, 4, 6, 9, 14, 16]
let sum = numberArray[3...].reduce(0, +)

Related

Determine indices of N number of non-zero minimum values in array

I have an array of x size and need to determine the indices of n of the smallest values. I found this link (I have need the N minimum (index) values in a numpy array) discussing how to get multiple minimum values but it doesn't work as well when my array has zeros in it.
For example:
x = [10, 12, 11, 9, 0, 1, 15, 4, 10]
n = 3
I need to find the indices of the 3 lowest non-zero values so the result would be
non_zero_min_ind = [5, 7, 3]
They don't need to be be in any order. I am trying to do this in python 3. Any help would be greatly appreciated.
Using numpy:
import numpy as np
y = np.argsort(x)
y[np.array(x)[y]!=0][:n]
array([5, 7, 3])

How to sum only the first two values of an array?

inputArray = [3, 6, -2, -5, 7, 3]
I'm trying to solve the following problem:
a) sum only 3 & 6 (that will be the first two values)
b) sum the result of 3 and 6 with -2.
c) I want to sum the first 2, multiply them with the third, skip the fourth and sum the last 2.
Thanks, I want to learn how to do it.
Challenge: https://app.codesignal.com/arcade/intro/level-2/xzKiBHjhoinnpdh6m
inputArray[0 ..< 2].reduce(0, +)
If you do a loop, you can track the progress over each iteration. For example:
var currentSum = 0
let inputArray = [3, 6, -2, -5, 7, 3]
for item in inputArray {
currentSum += item
print(currentSum)
}

Repetition of array elements in MATLAB

I have a MATLAB array and want to make a repetition based on the number of array elements. Below is the example that I want.
a = [2, 4, 6, 8]
If I want 7 elements, the result is
aa = [2, 4, 6, 8, 2, 4, 6]
Or if I want 5 elements,
aa = [2, 4, 6, 8, 2]
Is there any MATLAB function which makes these kind of result?
You can use "modular indexing":
a = [2, 4, 6, 8]; % data vector
n = 7; % desired number of elements
aa = a(mod(0:n-1, numel(a))+1);
One simple option will be to use a temporary variable for that:
a = [2 4 6 8];
k = 7;
tmp = repmat(a,1,ceil(k/numel(a)));
aa = tmp(1:k)
First, you repeat the vector using the smallest integer that makes the result larger than k, and then you remove the excess elements.
If you do that many times you can write a small helper function to do that:
function out = semi_repmat(arr,k)
tmp = repmat(arr,1,ceil(k/numel(arr)));
out = tmp(1:k);
end

How can I find the highest elements of an Array in Swift?

Can someone please explain how one would get the highest elements of an array in Swift 2.2?
For example lets say I have this code:
let myArray: [Int] = [2, 1, 6, 3, 5 ,7, 11]
How would i retrieve the 3 highest values of that array?
In this case I'd want the numbers 6, 7 and 11.
Any help would be greatly appreciated.
To find the 3 highest items, sort the array and take the last 3 items using suffix:
let myArray = [2, 1, 6, 3, 5 ,7, 11]
let highest3 = myArray.sort().suffix(3)
print(highest3) // [6, 7, 11]
For the 3 lowest items, use prefix:
let lowest3 = myArray.sort().prefix(3)
print(lowest3) // [1, 2, 3]
prefix and suffix have the added advantage that they do not crash if your array has fewer than 3 items. An array with 2 items for instance would just return those two items if you asked for .suffix(3).
let highestNumber = myArray.maxElement()
Shown in playground
Edit: Sorry, didn't read the full question, this method only retrieves the one highest value, here is a reconfigured version that should work
let myArray: [Int] = [2, 1, 6, 3, 5 ,7, 11, 4, 12, 5]
var myArray2 = myArray
var highestNumbers: [Int] = []
while highestNumbers.count < 3 {
highestNumbers.append(myArray2.maxElement()!)
myArray2.removeAtIndex(myArray2.indexOf(myArray2.maxElement()!)!)
print(highestNumbers)
}
Shown again in playground

Find All Numbers in Array which Sum upto Zero

Given an array, the output array consecutive elements where total sum is 0.
Eg:
For input [2, 3, -3, 4, -4, 5, 6, -6, -5, 10],
Output is [3, -3, 4, -4, 5, 6, -6, -5]
I just can't find an optimal solution.
Clarification 1: For any element in the output subarray, there should a subset in the subarray which adds with the element to zero.
Eg: For -5, either one of subsets {[-2, -3], [-1, -4], [-5], ....} should be present in output subarray.
Clarification 2: Output subarray should be all consecutive elements.
Here is a python solution that runs in O(n³):
def conSumZero(input):
take = [False] * len(input)
for i in range(len(input)):
for j in range(i+1, len(input)):
if sum(input[i:j]) == 0:
for k in range(i, j):
take[k] = True;
return numpy.where(take, input)
EDIT: Now more efficient! (Not sure if it's quite O(n²); will update once I finish calculating the complexity.)
def conSumZero(input):
take = [False] * len(input)
cs = numpy.cumsum(input)
cs.insert(0,0)
for i in range(len(input)):
for j in range(i+1, len(input)):
if cs[j] - cs[i] == 0:
for k in range(i, j):
take[k] = True;
return numpy.where(take, input)
The difference here is that I precompute the partial sums of the sequence, and use them to calculate subsequence sums - since sum(a[i:j]) = sum(a[0:j]) - sum(a[0:i]) - rather than iterating each time.
Why not just hash the incremental sum totals and update their indexes as you traverse the array, the winner being the one with largest index range. O(n) time complexity (assuming average hash table complexity).
[2, 3, -3, 4, -4, 5, 6, -6, -5, 10]
sum 0 2 5 2 6 2 7 13 7 2 12
The winner is 2, indexed 1 to 8!
To also guarantee an exact counterpart contiguous-subarray for each number in the output array, I don't yet see a way around checking/hashing all the sum subsequences in the candidate subarrays, which would raise the time complexity to O(n^2).
Based on the example, I assumed that you wanted to find only the ones where 2 values together added up to 0, if you want to include ones that add up to 0 if you add more of them together (like 5 + -2 + -3), then you would need to clarify your parameters a bit more.
The implementation is different based on language, but here is a javascript example that shows the algorithm, which you can implement in any language:
var inputArray = [2, 3, -3, 4, -4, 5, 6, -6, -5, 10];
var ouputArray = [];
for (var i=0;i<inputArray.length;i++){
var num1 = inputArray[i];
for (var x=0;x<inputArray.length;x++){
var num2 = inputArray[x];
var sumVal = num1+num2;
if (sumVal == 0){
outputArray.push(num1);
outputArray.push(num2);
}
}
}
Is this the problem you are trying to solve?
Given a sequence , find maximizing such that
If so, here is the algorithm for solving it:
let $U$ be a set of contiguous integers
for each contiguous $S\in\Bbb Z^+_{\le n}$
for each $\T in \wp\left([i,j)\right)$
if $\sum_{n\in T}a_n = 0$
if $\left|S\right| < \left|U\left$
$S \to u$
return $U$
(Will update with full latex once I get the chance.)

Resources