Reputation: 865
I have an array of [0,1,2,3,4,5,6,7,8,9]. I'm currently using the Javascript language.
Then I would like to reduce it to a new array that has the number 7, per se, at the index of 4 while the rest of the numbers in the array are sorted from lowest to greatest after that index.
One of the challenging aspects of this task is to get the numbers below 7 to order themselves before the index 4.
It has to be at the index of 4. It can't be at a different index. The target number to place at the index of 4 can be any number within the array I wrote above.
Example:
The array to return when I want to have the number 7 at index 4:
[3,4,5,6,7,8,9,0,1,2]
The array to return when I want to have the number 9 at index 4:
[5,6,7,8,9,0,1,2,3,4]
My best attempt so far:
let state = 7;
[0,1,2,3,4,5,6,7,8,9].reduce((acc,cur)=>{
let lastInd = state+5;
let firstInd = state-4 <0 ? 10+(state-4): state-4;
return acc
},[])
There is the option of hardcoding this to get the answer (this is the hard-coded solution):
let state = 7
let order = [
[0,1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,9,0],
[2,3,4,5,6,7,8,9,0,1],
[3,4,5,6,7,8,9,0,1,2],
[4,5,6,7,8,9,0,1,2,3],
[5,6,7,8,9,0,1,2,3,4],
[6,7,8,9,0,1,2,3,4,5],
[7,8,9,0,1,2,3,4,5,6],
[8,9,0,1,2,3,4,5,6,7],
[9,0,1,2,3,4,5,6,7,8]
];
let stateArray = order.find((e)=>{
return e.indexOf(state) === 4;
});
I just thought this would be a nice time killer and an entertaining and challenging problem to try to solve. I'm in no hurry to get this question solved because I implemented the hard-coded code for my project, but I've been wondering what would be the answer to this and I thought someone might want to solve this.
A solution in the language of Java or JS would be optimal for me. I haven't learned any other languages, but if it can be 'translated' to JS easily, I wouldn't mind.
Upvotes: 1
Views: 45
Reputation: 1987
This can be done using slice and concat:
const a=[0,1,2,3,4,5,6,7,8,9]
const f=(x)=>
{
const b=a.slice(x-4)
const c=a.slice(0,x-4)
return( b.concat(c))}
So if you call f(7)
you get:
[3,4,5,6,7,8,9,0,1,2]
Upvotes: 1