0
$\begingroup$

If I had an array of 7 numbers and I wanted all numbers to be equally spaced within it but needed to start at 5 and end at 35 how would I do this?

For instance if I were given:

  • Numbers in array: 7
  • Largest number in array: 35
  • Smallest number in array: 5

How do I find what number to increment the array by if I wanted to create an array of equally spaced numbers?

An example answer would be: Given the above three numbers I would say increment each array position by 5 and all 7 numbers will be equally spaced all the way to 35. The end result would look like this: [5,10,15,20,25,30,35]

Question 1: What would the formula be to repeat this any time I have array length, smallest, and largest number?

Question 2: In the above example if I were given the number 30 what is the formula to find its position in the given array? The formula should produce a result like this: If the array started at index one it would be position 6.

Any help would be great, thanks!

$\endgroup$
1
$\begingroup$

Hints:

  • How many gaps between consecutive pairs of numbers? In your example, $7-1=6$
  • What do the gaps add up to? In your example, $35-5=30$
  • What is the size of a gap? In your example, $\frac{30}{6}=5$
  • suppose there was a value before the first; what would it be? (call this the zeroth value) In your example, $5-5=0$
  • how many gaps would you need to add to the zeroth value to get your target value? In your example, $\frac{30}{5}=6$

So the $n$th value would be the zeroth value plus $n$ gaps, while value $x$ would be in the position corresponding to $x$ minus the zeroth value, all divided by the gap size

$\endgroup$
1
$\begingroup$

We have 2 numbers, $a,b$ with $a<b$. Suppose we want $c$ numbers in the array. Then the array would look like this: $(a,a+d,a+2d,....,a+(c-2)d,b)$ For some number $d$. Notice that the difference between any consecutive numbers in the array is $d$ (by construction). Using this fact, $b-(a+(c-2)d)=d.$ (last number in array minus penultimate) which we can solve for $d$ to obtain $d=(b-a)/(c-1)$ and $c \neq 1$ since we always have at least 2 numbers in the array.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.