Shannon Hochkins
Shannon Hochkins

Reputation: 12186

Calculate start middle and end of a number

I need a start, middle and end value of any given number, it doesn't have to be equally distributed, just needs a bit of logic. Example:

var parts = 3;

Obviously, I could devide this by 3 and get an even devised result start: 1; middle: 1; end: 1.

However if the user was to put in something like:

var parts = 8;

In my eyes, the answer would be start: 2; middle: 4; end: 2.

I need to perform a basic task depending on the length of the 'parts' variable.

Example:

I need to calculate the start, middle and end values so I can do something like this.

for (var t=0; t < start; t++){
    console.log('Start');
}
for (var t=0; t < middle; t++){
    console.log('Middle');
}
for (var t=0; t < end; t++){
    console.log('End');
}

How could I calculate this?

Upvotes: 0

Views: 318

Answers (3)

Usual Suspect
Usual Suspect

Reputation: 601

Here is the Solution:

var start,end,middle;
var parts=10;
if(parts%3==0)
{
start=end=middle=parts/3;
}
else
{
start=parseInt(parts/3);
end=parseInt(parts/3);
middle=parts-start-end;
}
console.warn(start+" "+end+" "+middle);

Here is the Fiddle: http://jsfiddle.net/j9WUZ/4/

Upvotes: 1

Shannon Hochkins
Shannon Hochkins

Reputation: 12186

To be perfectly honest, as soon as I left home, and got into my car, I remembered about the Modulo Operation. While most of your answers do work and I there was one answer that was using Modulos, I have to be selfish here and most a much more simpler and correct version.

var parts=9;
var start = end = middle = (parts - (parts % 3)) / 3;
middle += parts % 3;

But thank you all for your help!

Demo: http://jsfiddle.net/B5tap/

Upvotes: 0

Rob Kovacs
Rob Kovacs

Reputation: 1087

var parts, segment, start, middle, end;

parts = 8; // Obviously this value would be defined elsewhere

segment = Math.floor(parts / 3);

start = end = segment;
middle = parts - (segment * 2);

Upvotes: 2

Related Questions