I have an array of numbers. In this array each number is repeating for "r" times.
This function is generating the array:
var n = 8;
var k = 4;
var r = 3;
var comb = n * r / k;
function getNumbers() {
var array = new Array();
for (i = 0; i < r; i++) {
for (j = 0; j < n; j++) {
array.push(j);
}
}
return array;
}
The numbers from this array I want to split them in "comb=n*r/k" uniq small arrays with the length of k;
for this I made the following function:
function InsertNumber(array) {
var finalarray = GetArrays(comb);
for (j = 0; j < array.length; j++) {
for (i = 0; i < finalarray.length; i++) {
if (ContainX(array[j], finalarray[i])) {
if (finalarray[i].length <= k) {
finalarray[i].push(array[j]);
Console.log(array[j]);
var index = array.indexOf(array[j]);
array.splice(index, 1);
InserNumber(array);
}
}
}
}
ShowTable(finalarray);
}
function GetArrays(x) {
var array = new Array();
for (i = 0; i < x; i++) {
var smallArray= new Array();
array.push(smallArray);
}
return array;
}
function ContainX(array,element) {
var result = false;
for (i = 0; i < array.length; i++) {
if (element === array[i]) {
result = true;
}
}
return result;
}
finaly I want to display all the small arays items in a table using this function:
function ShowTable(array) {
document.write("<table>")
for (i = 0; i < array.lenght; i++) {
document.write("<tr>")
for (j = 0; j < array[i].legth; j++) {
document.write("<td>" + array[i][j] + "</td>")
}
document.write("</tr>")
}
document.write("</table>")
}
I think that the step by step algorithm to get the expected result may be ok, but I am not able to see the result in browser because of the recursive function InsertNumber().
Can you help me with a better method to generate all combinations of all numbers in an array, where the the array items may repeat for r times?
I am open for any solution which can fix my issue.
Edit:
Exemple: mainArray=[0,0,1,1,2,2];
I want to split this array in:
arr1=[0,1];
arr2=[0,2];
arr3=[1,2];
this 3 arrays are containing all items of mainArray and are uniq!!!.
In this exemple: n=3, k=2, r=2, comb=n*r/k=3;
n=total unique numbers from `mainArray [0,1,2]`;
k=length of small arrays
r= number of repetition of each unique n;
comb= the number of small arrays;
**Edit2- Exemple2:**
mainArray=[0,0,1,1,2,2,3,3,4,4]
arr1=[0,1];
arr2=[0,2];
arr3=[1,3];
arr4=[2,4];
arr5=[3,4];
n=5, unique numbers in main array;
k=2, length of small array;
r=2, repetition of each number in main array;
comb=5*2/2=number of combinations which must result!.
(all the items from mainArray are spllited in small arr is such a way to not have small array with same items)
This proposal works with an array and a given length for the part array.
Distribution of values with length = 2
0 0 1 1 2 2 3 3 4 4
0 1
0 2
1 3
2 4
3 4
Distribution of values with length = 3
0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7
0 1 2
0 1 3
0 2 4
1 3 5
2 4 6
3 5 7
4 6 7
5 6 7
The key feature is to splice the used value and increase the position with length - 1 for the next item to push to the part array. If the position p is outside of the array, then the position is set to the last element of the array.
function getParts(array, length) {
var r = [],
values,
i, p;
while (array.length > length) {
values = [];
p = 0;
for (i = 0; i < length; i++) {
if (p >= array.length) {
p = array.length - 1;
}
values.push(array.splice(p, 1)[0]);
p += length - 1;
}
r.push(values);
}
r.push(array);
return r;
}
function print(o) {
document.write('<pre>' + JSON.stringify(o, 0, 4) + '</pre><hr>');
}
print(getParts([0, 0, 1, 1, 2, 2], 2));
print(getParts([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], 2));
print(getParts([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7], 3));
Related
function sumPairs(ints, s) {
let result = [];
for(let i = 0; i < ints.length; i++){
for(let j = 0; j < ints.slice(i); j++){
(ints[i] + ints[j] === s && result.length === 0) ? result.push(ints[i], ints[j]) : 0;
}
} return result;
}
sumPairs([1, 2, 3, 4, 5, 6], 10) //returns [6, 4] instead of [4,6]?
How do I fix this so that the function returns the first pair that add up to s, the second argument? I added the result.length === 0 condition in the if statement a further update would be prevented?
Just iterate over the array using for..of loop and use Set to achieve the desired result.
function sumPairs(ints, s) {
const dict = new Set();
for (let num of ints) {
if (dict.has(s - num)) return [s - num, num];
else dict.add(num);
}
}
console.log(sumPairs([1, 2, 3, 4, 5, 6], 10));
Iterations:
Iteration 1 :=> num = 1 and dict is empty
dict doesn't have 9 (because of s - num i.e 10 - 1) so add num i.e 1 to dict.
Iteration 2 :=> num = 2 and dict has 1
dict doesn't have 8 (because of s - num i.e 10 - 2) so add num i.e 2 to dict
Iteration 3 :=> num = 3 and dict has 1, 2
dict doesn't have 7 (because of s - num i.e 10 - 3) so add num i.e 3 to dict
Iteration 4 :=> num = 4 and dict has 1, 2, 3
dict doesn't have 6 (because of s - num i.e 10 - 4) so add num i.e 4 to dict
Iteration 5 :=> num = 5 and dict has 1, 2, 3, 4
dict doesn't have 5 (because of s - num i.e 10 - 5) so add num i.e 5 to dict
Iteration 6 :=> num = 6 and dict has 1, 2, 3, 4, 5
dict have 4 (because of s - num i.e 10 - 6) so return [s - num, num] i.e [4, 6]
I think you might be overcomplicating things a little. There's no need to slice() or to push(), and there's no need to keep on looping after a result has been found:
function sumPairs(ints, s) {
for (let i = 0; i < ints.length; i++) {
for (let j = i; j < ints.length; j++) {
if (ints[i] + ints[j] == s) {
return [ints[i], ints[j]];
}
}
}
}
console.log(sumPairs([1, 2, 3, 4, 5, 6], 10));
As #robby-cornelissen said there's no need to slice. And there's no need for push too as you can return the result simply.
When you do ints.slice(i) you get an array from that position.
You are comparing an int within an array in the second loop.
It didn't enter the second loop until "i === 5" which is in the ints array a [6]. Notice it didn't enter the second until you get an array of one element. Keep in mind 6 == [6] and 1<[6] and 2<[6] etc
Then it goes incrementing the value of j until you get the position of j that gets the value of ints which, summed by the value of the position i results on s.
const twoSum = (arr, target) => {
arr.sort((a, b) => a - b);
//double pointer -> increment, decrement accordingly
let leftPointer = 0;
let rightPointer = arr.length - 1;
while (leftPointer < rightPointer) {
if (arr[leftPointer] + arr[rightPointer] === target) {
return [arr[leftPointer], arr[rightPointer]];
}
if (arr[leftPointer] + arr[rightPointer] > target) {
rightPointer--;
}
if (arr[leftPointer] + arr[rightPointer] < target) {
leftPointer++;
}
}
};
console.log(twoSum([1, 2, 3, 4, 5, 6], 10));
For example, given A = [1, 2, 1, 1], the function should return 3.
Creates only three different sequences: (1, 2, 1), (1, 1, 1) and (2, 1, 1). The correct answer for this example is 3.
Given A = [1, 2, 3, 4], the function should return 4. There are four
ways: (1, 2, 3), (1, 2, 4), (1, 3, 4) and (2, 3, 4).
Given A = [2, 2, 2, 2], the function should return 1. There is only
one way: (2, 2, 2).
Given A = [2, 2, 1, 2, 2], the function should return 4. There are
four ways: (1, 2, 2), (2, 1, 2), (2, 2, 1) and (2, 2, 2).
Given A = [1, 2], the function should return 0
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..100,000]; each element of array A
is an integer within the range [1..N].
Here is my Brute Force Solution below!
I was wondering if anybody out there has a better more optimized solution?
Detected time complexity of this solution:
O(N**3*log(N)) or O(N**4)
const theatreTickets = (array) => {
let combos = []
if(array.length < 2) {
combos.length = 0
}
for(let i = 0; i <= array.length; i++) {
for(let j = i + 1; j <= array.length - 1; j++) {
for(let k = j + 1; k <= array.length - 1; k++) {
combos.push([array[i], array[j], array[k]])
}
}
}
combos = Array.from(new Set(combos.map(JSON.stringify)), JSON.parse)
return combos.length
}
console.log(theatreTickets([1, 2, 1, 1])) // Should Be 3
Thank you!
I think you need to combine, algorithm of combination and unique. It will work. Sample is given below.
Source: Efficient algorithm to get the combinations of all items in object
function combine(items, numSubItems) {
var result = [];
var indexes = new Array(numSubItems);
for (var i = 0 ; i < numSubItems; i++) {
indexes[i] = i;
}
while (indexes[0] < (items.length - numSubItems + 1)) {
var v = [];
for (var i = 0 ; i < numSubItems; i++) {
v.push(items[indexes[i]]);
}
result.push(v);
indexes[numSubItems - 1]++;
var l = numSubItems - 1; // reference always is the last position at beginning
while ( (indexes[numSubItems - 1] >= items.length) && (indexes[0] < items.length - numSubItems + 1)) {
l--; // the last position is reached
indexes[l]++;
for (var i = l +1 ; i < numSubItems; i++) {
indexes[i] = indexes[l] + (i - l);
}
}
}
return result;
}
var combinations = combine([1,2,1,1], 3);
console.log([...new Set(combinations.map(x => x.join(",")))]);
combinations = combine([1,2,3,4], 3);
console.log([...new Set(combinations.map(x => x.join(",")))]);
Change the given amount of money into minimum number of bills.
Inputs:
Amount: positive integer;
Bills: a sorted list of distinct positive integers (e.g. [1, 5, 10]).
Assumptions:
Amount does not exceed 100.
At most 4 bill values.
Must return 0 if the amount cannot be changed.
Examples:
Amount: 17, bills: [1, 5, 10], answer: 4 -> 10+5+1+1
Amount: 17, bills: [2, 4], answer: 0
Here's the code I have so far
function sort(array) {
for (var i = array.length - 1; i >= 0; i--) {
for (var j = 0; j < i; j++) {
if (array[j + 1] > array[j]) {
var z = array[j];
array[j] = array[j + 1];
array[j + 1] = z;
}
}
}
return array;
}
function change(amount, bills) {
sort(bills);
var result = [];
while (amount > 0) {
for (var i = 0; i < bills.length; i++) {
if (amount >= bills[i]) {
amount -= bills[i];
result.push(bills[i]);
i--;
}
}
}
return result.length;
}
console.log(change(17, [1, 5, 10])); // Expect: 4
console.log(change(17, [2, 4])); // Expect: 0
console.log(change(18, [2, 4])); // Expect: 5
//console.log(change(17, [3, 5])); // Expect: 5
There are 2 problems
One is that if the amount cannot be divided it doesn't return 0 but just lags out because it's an infinite loop.
Second is that in the last example, 17,[3,5] my code takes the 5 3 times and then realises that it can't do the remaining 2 and lags out, instead of doing 3 4 times and adding a 5.
Would really appreciate suggestions, or fixed code. Please keep it fairly simple I am just a starter.
If fixed your change function and added comments to explain my changes, let me know if you have any doubts
function change (amount, bills) {
//Asign sorted array of bills to possibleBills
var possibleBills = sort(bills);
var result = [];
//Asign amount to currentAmount
var currentAmount = amount;
//Sort through possibleBills
for (var i = 0; i < possibleBills.length; i++) {
//Perform action inside while loop if the current bill value can be substracted from currentAmount
while (currentAmount - possibleBills[i] >= 0) {
currentAmount -= possibleBills[i];
result.push(possibleBills[i]);
//End loop and return the length of result if currentAmount reaches 0
if (currentAmount === 0) {
return result.length;
}
}
}
//Return 0 if the amount couldn't be changed with the given bills
if (currentAmount > 0) {
return 0;
}
return result.length;
};
function change(amount, bills) {
const billsDesc = bills.sort((a, b) => b - a);
const give = {}
let remaining = amount;
for (const bill of billsDesc) {
const qty = Math.floor(remaining/bill);
give[bill] = qty;
remaining -= qty*bill;
}
give.totalQty = Object.values(give).reduce((curr, prev) => curr + prev, 0);
return remaining === 0? give.totalQty : 0;
}
console.log(`${change(17, [1, 5, 10])} should equal 4`);
console.log(`${change(17, [2, 4])} should equal 0`);
console.log(`${change(18, [2, 4])} should equal 5`);
I want to loop through an array and then add each value to each other (except itself + itself) and if the sum of the two values that were looped through equals the second argument in my function, and the pair of values hasn't been encountered before, then remember their indices and, at the end, return the full sum of all remembered indices.
In other words, the problem statement is: given an array A of integers and a second value s that is a desired sum, find all pairs of values from array A at indexes i, j such that i < j and A[i] + A[j] = s, and return the sum of all indexes of these pairs, with the following restriction:
don't reuse value pairs, i.e. if two index pairs i, j and k, l satisfying the above conditions are found and if A[i] == A[k] and A[j] == A[l] or A[i] == A[l] and A[j] == A[k], then ignore the pair with the higher index sum.
Example
For example, functionName([1, 4, 2, 3, 0, 5], 7) should return 11 because values 4, 2, 3 and 5 can be paired with each other to equal 7 and the 11 comes from adding the indices of them to get to 11 where:
4 + 3 = 7
5 + 2 = 7
4 [index: 1]
2 [index: 2]
3 [index: 3]
5 [index: 5]
1 + 2 + 3 + 5 = 11
Example #2
functionName([1, 3, 2, 4], 4) would only equal 1, because only the first two elements can be paired to equal 4, and the first element has an index of 0 and the second 1
1 + 3 = 4
1 [index: 0]
3 [index: 1]
0 + 1 = 1
This is what I have so far:
function functionName(arr, arg) {
var newArr = [];
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++) {
if((arr[i] + arr[j]) === arg ) {
newArr.push(i , j);
}
}
}
if(newArr.length === 0) {
return console.log(0);
}
return console.log(newArr.reduce(function(a,b){return a + b}));
}
functionName([1, 4, 2, 3, 0, 5], 7);
The problem I have is that it all works but I have the issue that once it finds a pair that equals the second argument, then it's not supposed to use the same value pairs again but mine does, e.g.:
if the array is [1,1,1] and the second argument is 2, the loop will go through and find the answer but it continues to search after it finds the sum and I only want it to use the pair [1, 1] once, so if it finds a pair like this at indexes [0, 1] then it should not include any other pair that contains the value 1.
I was thinking that i could remove the rest of the values that are the same if more than 2 are found using filter leaving me with only 2 of the same value if there is in an array thus not having to worry about the loop finding a 1 + 1 twice but is this the best way to go about doing it?
I'm still new to this but looking forward to your comments
PS I'm planning on doing this using pure JavaScript and no libraries
Link to a JS fiddle that might make things easier to see what I have.
https://jsfiddle.net/ToreanJoel/xmumv3qt/
This is more complicated than it initially looks. In fact, making a loop inside a loop causes the algorithm to have quadratic time complexity with regard to the size of the array. In other words, for large arrays of numbers, it will take a very long time to complete.
Another way to handle this problem is to notice that you actually have to use each unique value in the array only once (or twice, if s is even and you have two s/2 values somewhere in the array). Otherwise, you would have non-unique pairs. This works because if you need pairs of numbers x and y such that x + y = s, if you know x, then y is determined -- it must be equal s - x.
So you can actually solve the problem in linear time complexity (to be fair, it's sometimes n*log(n) if all values in A are unique, because we have to sort them once).
The steps of the algorithm are as follows:
Make a map whose keys are values in array A, and values are sorted lists of indexes these values appear at in A.
Move through all unique values in A (you collected them when you solved step 1) in ascending order. For each such value:
Assume it's the lower value of the searched pair of values.
Calculate the higher value (it's equal to s - lower)
Check if the higher value also existed in A (you're doing it in constant time thanks to the map created in step 1).
If it does, add the lowest indexes of both the lower and the higher value to the result.
Return the result.
Here's the full code:
function findSumOfUniquePairs(numbers, sum) {
// First, make a map from values to lists of indexes with this value:
var indexesByValue = {},
values = [];
numbers.forEach(function (value, index) {
var indexes = indexesByValue[value];
if (!indexes) {
indexes = indexesByValue[value] = [];
values.push(value);
}
indexes.push(index);
});
values.sort();
var result = 0;
for (var i = 0, maxI = values.length; i < maxI; ++i) {
var lowerValue = values[i],
higherValue = sum - lowerValue;
if (lowerValue > higherValue) {
// We don't have to check symmetrical situations, so let's quit early:
break;
}
var lowerValueIndexes = indexesByValue[lowerValue];
if (lowerValue === higherValue) {
if (lowerValueIndexes.length >= 2) {
result += lowerValueIndexes[0] + lowerValueIndexes[1];
}
} else {
var higherValueIndexes = indexesByValue[higherValue];
if (higherValueIndexes) {
result += lowerValueIndexes[0] + higherValueIndexes[0];
}
}
}
return result;
}
document.write(findSumOfUniquePairs([1, 4, 2, 3, 0, 5], 7) + '<br>'); // 11;
document.write(findSumOfUniquePairs([1, 3, 2, 4], 4) + '<br>'); // 1
document.write(findSumOfUniquePairs([1, 1, 1], 2) + '<br>'); // 1
document.write(findSumOfUniquePairs([1, 1, 1, 1], 2) + '<br>'); // 1
document.write(findSumOfUniquePairs([1, 2, 3, 1, 2, 3, 1], 4) + '<br>'); // 7
document.write(findSumOfUniquePairs([5, 5, 1, 1, 1], 6) + '<br>'); // 2
document.write(findSumOfUniquePairs([0, 5, 0, 5, 1, 1, 1], 6) + '<br>'); // 5
This works, but it mucks up the initial array.
function functionName(arr, arg) {
var newArr = [];
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++) {
if((arr[i] + arr[j]) === arg ) {
newArr.push(i , j);
arr[i] = null;
arr[j] = null;
}
}
}
if(newArr.length === 0) {
return console.log(0);
}
return console.log(newArr.reduce(function(a,b){return a + b}));
}
Solution with loops with restart, if a sum is found. the found summands are stored in usedNumbers and later sorted and used to get the index for summing the index.
The sorting and the last index provides the correct start position for the Array.prototype.indexOf.
Edit:
what about [1,1,1,1], 2 ... should that be 6 or 1? – Jaromanda X 21
#JaromandaX that should be 1, after the pair is found with the values then it shouldn't look for a pair with the same values again – Torean
This version takes care of the requirement.
function f(array, sum) {
var arrayCopy = array.slice(0),
usedNumbers = [],
index = 0,
indexA = 0,
indexB,
a, b;
while (indexA < arrayCopy.length) {
indexB = indexA + 1;
while (indexB < arrayCopy.length) {
a = arrayCopy[indexA];
b = arrayCopy[indexB];
if (a + b === sum) {
usedNumbers.push(a, b);
arrayCopy = arrayCopy.filter(function (i) { return a !== i && b !== i; });
indexA--; // correction to keep the index
break;
}
indexB++;
}
indexA++;
}
return usedNumbers.sort().reduce(function (r, a, i) {
index = array.indexOf(a, i === 0 || a !== usedNumbers[i - 1] ? 0 : index + 1);
return r + index;
}, 0);
}
document.write(f([1, 4, 2, 3, 0, 5], 7) + '<br>'); // 11
document.write(f([1, 1, 1], 2) + '<br>'); // 1
document.write(f([5, 5, 1, 1, 1], 6) + '<br>'); // 2
document.write(f([0, 5, 0, 5, 1, 1, 1], 6) + '<br>'); // 5
document.write(f([1, 1, 1, 1], 2) + '<br>'); // 1
The solution below is very compact. It avoids unnecessary checks and loops only through the relevant elements. You can check the working codepen here:
http://codepen.io/PiotrBerebecki/pen/RRGaBZ.
function pairwise(arr, arg) {
var sum = 0;
for (var i=0; i<arr.length-1; i++) {
for (var j=i+1; j<arr.length; j++) {
if (arr[i] <= arg && arr[j] <= arg && arr[i] + arr[j] == arg) {
sum += i+j;
arr[i] = arr[j] = NaN;
}
}
}
return sum;
}
console.log( pairwise([1, 1, 0, 2], 2) ) // should return 6
Under the hood:
Start looping from the element with index (i) = 0.
Add a second loop only for the elements which are later in the array. Their index j is always higher than i as we are adding 1 to i.
If both elements (numbers) are less than or equal to to the arg, check if their sum equals to the arg. This avoids checking the sum if either of the numbers are greater than the arg.
If the pair has been found then change their values to NaN to avoid further checks and duplication.
This solution should have a time complexity of 0(n) or linear
Much faster than two nested for-loops. This function will give you the two indices that add up to the target number. It can easily be modified to solve any other configuration of this problem.
var twoSum = function(nums, target) {
const hash = {}
for(let i = 0; i < nums.length; i++) {
hash[nums[i]] = i
}
for(let j = 0; j < nums.length; j++) {
let numToFind = target - nums[j]
if(numToFind in hash && hash[numToFind] !== j) {
return [hash[numToFind], j]
}
}
return false
};
console.log(twoSum([1,2,3,5,7], 5))
In Python:
def twoSum(self, nums: List[int], target: int) -> List[int]:
myMap = {}
for i in range(len(nums)):
myMap[nums[i]] = i
for j in range(len(nums)):
numToFind = target - nums[j]
if numToFind in myMap and myMap[numToFind] != j:
return [myMap[numToFind], j]
print(twoSum([1,2,3,5,7], 5))
In Java:
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(Integer i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for(Integer j = 0; j < nums.length; j++) {
Integer numToFind = target - nums[j];
Integer myInt = map.get(numToFind);
if(map.containsKey(numToFind) && myInt != j) {
return new int[] {myInt , j};
}
}
return new int[] {0, 0};
}
}
System.out.println(twoSum([1,2,3,5,7], 5))
I want to insert numbers to an array by the next following:
the number should be between 1-5
the first number can't be 1, the second can't be 2, etc..
chosen number can't be inserted to another index
for example:
[1,2,3,4,5]
I randomize the first number: 1 [condition 2 doesn't exists: 1 can't be in the first index, so I randomize again and got 4).
so new array:
0 - 4
1 -
2 -
3 -
4 -
I randomize a number to the second cell and got 4, but 4 was inserted to the first element [condition 3], so I randomize again and got 2, but 2 can't be the second element [condition 2], so I randomize again and got 5.
0 - 4
1 - 5
2 -
3 -
4 -
etc
I tried to init a vec by the numbers (1-5):
var array = new Array();
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
var newarr = new Array();
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$(document).ready(function() {
for (var i = 0; i < 5; i++) {
var rand;
// check condition 2
while((rand = getRandomInt(1, 5)) == (i+1));
newarr[i] = rand;
//array.splice(i, 1);
}
// print the new array
for (var i = 0; i < 5; i++) {
alert((i+1) + '->' + newarr[i]);
}
});
but I need to add condition 3 to my code,
any help appreciated!
Try this:
$(document).ready(function() {
for (var i = 0; i < 5; i++) {
var rand;
// check condition 2
while((rand = getRandomInt(1, 5)) == (i+1) || $.inArray(rand, newarr)) // Also check, if generated number is already in the array
newarr[i] = rand;
//array.splice(i, 1);
}
// print the new array
for (var i = 0; i < 5; i++) {
alert((i+1) + '->' + newarr[i]);
}
});
But beware. If you generate for example this array:
[2, 1, 4, 3]
You will end up having an endless while loop, since the only available number is 5, but it can't be inserted in that position.
var values = [1,2,3,4,5];
var output = [];
for(var i=0;i<5;i++)
{
do{
var index = Math.floor(Math.random() * values.length);
}while(values[index] == i +1);
output[i] = values[index];
values.splice(index, 1);
}
console.log(output);
Demo : http://jsfiddle.net/aJ8sH/