I'm trying to implement Array.repeat, so
[3].repeat(4) // yields
=> [3, 3, 3, 3]
... and is driving me crazy.
Tried with this:
Array::repeat = (num)->
array = new Array
for n in [0..num]
array.concat(this)
array
But [3].repeat(x) always returns []. Where I'm screwing it up? Or is there a better approach do this?
Final result:
Array::repeat = (num)->
array = new Array
return array if num < 1
for n in [1..num]
array = array.concat(this)
array
['a'].repeat(5)
=> ['a', 'a', 'a', 'a', 'a']
array.concat returns a new array and does not modify the existing one.
You need to write
array = array.concat(dup)
Alternatively, you can use push(), which does modify the original array:
array.push.apply(array, dup)
This is rather simple:
function repeat(array, n){
var out = [];
for(var i = 0; i < n; i++) {
out = out.concat(array);
}
return out;
}
Or prototyping:
Array.prototype.repeat = function(n){
var out = [];
for(var i = 0; i < n; i++) {
out = out.concat(this);
}
return out;
}
That's native JS, not sure how you'd do that in CoffeeScript.
I think this is how function should look like:
Array.prototype.repeat = function(count) {
if(count==null||1*count!=count) //check for cerrect count
return this.valueOf();
var length = this.length; //Length
var return = this.valueOf(); //0 repats equals in the same array
for(var i=0; i<count; i++) { //Repeating the count
for(var j=0; j<length; j++) {
return.push(this[j]);
}
}
}
Related
When i loop through the array using the splice method, the page just freezes. It looks like i caused an infinite loop. lib.randomInt() works, so that is not the problem.
function() {
return function(string) {
var arr = string.split("")
arr.sort();
for(var i = 0; arr.length;i++){
arr.splice((i+1),0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
}
})()("example");
This is from a different file that is placed above the main file in html
var lib = {
factorial: function(num){
function _factorial(num){
if(num === 1){
return 1;
} else {
return num*_factorial(num-1);
}
}
console.log(num+"! = " + _factorial(num));
},
randomInt: function(int,offset){
if(offset == undefined || null || NaN){
offset = 0;
}
return Math.floor(Math.random()*int)+offset;
},
display: function(m, fn){
fn(m);
}
};
You've got to loop in reverse when modifying the array itself to avoid corrupting the loop like this...
for (var i=arr.length-1; i>=0; i--){}
I guess that you wanted to insert a random value after every array element, so that the string "example" would become something like "e5x9a2m4p7l1e3"
There are two issues:
Your for loop has no end condition that will become false. You need to state i < arr.length instead of just arr.length which is always truthy for non-empty arrays.
You add array elements in every iteration, but then also visit them in the next iteration, and from there on you will only be visiting the new inserted values and never get to the next original element that keeps being 1 index away from i. You need to increment i once more. For that you can use ++i instead if i+1 as the splice argument.
So your loop should be:
for(var i = 0; i < arr.length; i++) {
arr.splice(++i,0,lib.randomInt(9));
}
const lib = { randomInt: n => Math.floor(Math.random()*n) };
(function() {
return function(string) {
var arr = string.split("")
arr.sort();
for(var i = 0; i < arr.length; i++) {
arr.splice(++i,0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
console.log(pseudocryptarr);
}
})()("example");
Or to save an addition:
for(var i = 1; i <= arr.length; i+=2) {
arr.splice(i,0,lib.randomInt(9));
}
const lib = { randomInt: n => Math.floor(Math.random()*n) };
(function() {
return function(string) {
var arr = string.split("")
arr.sort();
for(var i = 1; i <= arr.length; i+=2) {
arr.splice(i,0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
console.log(pseudocryptarr);
}
})()("example");
I fixed it. I wanted after each character for there to be a number. Using the pre-looped array length and doubling it while iterating twice, means that the splice adds the number after the new number element and then the character.
Edit: My typo was the problem. I didnt even have to use len, just iterate by 2.
for(var i = 0;i < arr.length;i+=2){
arr.splice((i+1),0,lib.randomInt(9));
}
(function() {
return function(string) {
var arr = string.split("")
arr.sort();
var len = arr.length
for(var i = 0;i < len*2;i+=2){
arr.splice((i+1),0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
console.log(pseudocryptarr);
}
})()("example");
Edit: user4723924 method is better:
(function() {
return function(string) {
var arr = string.split("")
arr.sort();
for(var i = arr.length;i >= 0;i--){
arr.splice((i+1),0,lib.randomInt(9));
}
var pseudocryptarr = arr.join("");
console.log(pseudocryptarr);
}
})()("example");
I have a function that is meant to do this:
accum("abcd"); // "A-Bb-Ccc-Dddd"
accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
We can see the first "for" loop repeats each substring by it's current (index + 1). It pushes it to the array and the output would be [ 'a', 'bb', 'ccc', 'dddd' ]
It is then obvious that I need to iterate over this array and capitalise each string which I have done by the second for loop below.
The problem is when I return the array it is returning like this: [ 'A', 'B', 'C', 'D' ]
It is returning the first substring of each string but it isn't returning the rest of them.
function accum(s) {
var splitstring = s.split("")
var newarray = []
for(var i = 0; i < splitstring.length; i++) {
newarray.push(splitstring[i].repeat(i + 1))
}
for (var i = 0; i < newarray.length; i++) {
newarray[i] = newarray[i].charAt(0).toUpperCase()
}
return newarray
}
accum("abcd")
That's because you're overwriting the string with only the first character. you need to concatenate the rest of the string.
for (var i = 0; i < newarray.length; i++) {
newarray[i] = newarray[i].charAt(0).toUpperCase() + newarray[i].slice(1);
}
Here's a shorter version of your code:
function accum(s) {
return s.split("").map((ss, i) => ss.toUpperCase() + ss.repeat(i)).join("-");
}
console.log(accum("abcd"));
It also adds the separator that you seem to want. If you actually wanted the array, then remove .join("-").
No need to use second for loop. Just use map() on the returned array.
function accum(s) {
var splitstring = s.split("");
var newarray = [];
for(var i= 0; i < splitstring.length; i++) {
newarray.push(splitstring[i].repeat(i + 1))
}
return newarray.map(j=>j[0].toUpperCase()+ j.slice(1)).join('-');
}
console.log(accum("abcd"));
I just don't understand why does this function return an empty array instead of newArr = [1, 2, 3, etc.] depending on the length of the array.
function randomFunction(num) {
var newArr = [];
for(var i = 1; i < num.length; i++) {
newArr.push(i);
}
return newArr;
};
If num is supposed to be the length of the new array, and the last number of the range of values, you have to use it directly, instead of using length (which is meant to be used for an array):
function randomFunction(num) {
var newArr = [];
for(var i = 1; i <= num; i++) {
newArr.push(i);
}
return newArr;
};
var array = randomFunction(5);
console.log(array);
Also, you might want use <= instead of <, in case you want to start the value by 1 and go through n, and not n - 1.
function randomFunction(num) {
var newArr = [];
for(var i = 1; i < num /* number has no length */; i++) {
newArr.push(i);
}
return newArr;
};
Es6 alternative for fun:
return new Array(num).fill().map((r, i) => i)
randomFunction(8) ; for example
A number doesn't have length at all. It's already a value.
You do not need length attribute at all. just
for(var i = 1; i < num; i++) {
newArr.push(i);
}
function randomFunction(num) {
var newArr = [];
for (var i = 1; i < num; i++) {
newArr.push(i);
}
return newArr;
};
console.log(randomFunction(8))
num is already a number. You don't need use .lenght property
function randomFunction(num) {
var newArr = [];
for(var i = 1; i <= num; i++) {
newArr.push(i);
}
return newArr;
};
randomFunction(5); // [ 1, 2, 3, 4, 5 ]
I need code that takes an array, counts the number of elements in it and returns a set of arrays, each displaying a different combination of elements. However, the starting element should be the same for each array. Better to explain with a few examples:
var OriginalArray = ['a','b','c']
should return
results: [['a','b','c'], ['a','c','b']]
or for example:
var originalArray = ['a','b','c','d']
should return
[['a','b','c','d'], ['a','b','d', 'c'], ['acbd', 'acdb', 'adbc', 'adcb']]
Again note how the starting element, in this case 'a' should always be the starting element.
You can use Heap's algorithm for permutations and modify it a bit to add to result only if first element is equal to first element of original array.
var arr = ['a', 'b', 'c', 'd']
function generate(data) {
var r = [];
var first = data[0];
function swap(x, y) {
var tmp = data[x];
data[x] = data[y];
data[y] = tmp;
}
function permute(n) {
if (n == 1 && data[0] == first) r.push([].concat(data));
else {
for (var i = 0; i < n; i++) {
permute(n - 1);
swap(n % 2 ? 0 : i, n - 1);
}
}
}
permute(data.length);
return r;
}
console.log(generate(arr))
You have to do a .slice(1) to feed the rest of the array to a permutations function. Then you can use .map() to stick the first item to the front of each array in the result of permutations function.
If you will do this job on large sets and frequently then the performance of the permutations function is important. The following uses a dynamical programming approach and to my knowledge it's the fastest.
function perm(a){
var r = [[a[0]]],
t = [],
s = [];
if (a.length <= 1) return a;
for (var i = 1, la = a.length; i < la; i++){
for (var j = 0, lr = r.length; j < lr; j++){
r[j].push(a[i]);
t.push(r[j]);
for(var k = 1, lrj = r[j].length; k < lrj; k++){
for (var l = 0; l < lrj; l++) s[l] = r[j][(k+l)%lrj];
t[t.length] = s;
s = [];
}
}
r = t;
t = [];
}
return r;
}
var arr = ['a','b','c','d'],
result = perm(arr.slice(1)).map(e => [arr[0]].concat(e));
console.log(JSON.stringify(result));
Hey i have a simple question i cant find an answer,
i´m trying to generate some raw-data for a chart
lets say i have an array like :
[1,0,0,1,2,0]
is there a way to make an array out of it that has nested arrays that represent the count of duplicate entrys ?
[[0,3],[1,2],[2,1]]
here is some code that does the trick, but saves the count as objects
var array = [1,0,0,1,2,0];
var length = array.length;
var objectCounter = {};
for (i = 0; i < length; i++) {
var currentMemboerOfArrayKey = JSON.stringify(array[i]);
var currentMemboerOfArrayValue = array[i];
if (objectCounter[currentMemboerOfArrayKey] === undefined){
objectCounter[currentMemboerOfArrayKey] = 1;
}else{
objectCounter[currentMemboerOfArrayKey]++;
}
}
but objectCounter returns them like
{0:3,1:2,2:1}
but i need it as an array i specified above ?
for any help, thanks in advance
Try
var array = [1, 0, 0, 1, 2, 0];
function counter(array) {
var counter = [],
map = {}, length = array.length;
$.each(array, function (i, val) {
var arr = map[val];
if (!arr) {
map[val] = arr = [val, 0];
counter.push(arr);
}
arr[1] += 1;
})
return counter;
}
console.log(JSON.stringify(counter(array)))
Demo: Fiddle
You can turn your object into an array easily:
var obj = {0:3,1:2,2:1};
var arr = [];
for (var key in obj) {
// optional check against Object.prototype changes
if (obj.hasOwnProperty(key)) {
arr.push([+key, obj[key]]);
}
}
Note: The object keys are strings, so i converted them back to numbers when placed in the array.
Functional way of doing this, with Array.reduce and Array.map
var data = [1,0,0,1,2,0];
var result = data.reduce(function(counts, current) {
counts[current] = current in counts ? counts[current] + 1: 1;
return counts;
}, {});
result = Object.keys(result).map(function(current){
return [parseInt(current), result[current]];
});
console.log(result);
Output
[ [ 0, 3 ], [ 1, 2 ], [ 2, 1 ] ]
Try:
var data = [1,0,0,1,2,0];
var len = data.length;
var ndata = [];
for(var i=0;i<len;i++){
var count = 0;
for(var j=i+1;j<len;j++){
if(data[i] == data[i]){
count ++;
}
}
var a = [];
a.push(data[i]);
a.push(count);
ndata.push(a);
}
console.log(ndata)
DEMO here.
First you need to map the array to an associative object
var arr = [1,0,0,1,2,0];
var obj = {};
for (var i = 0; i < arr.length; i++) {
if (obj[arr[i]] == undefined) {
obj[arr[i]] = 0;
}
obj[arr[i]] += 1;
}
Then you can easily turn that object into a 2d matrix like so:
arr = [];
for (var k in obj) {
arr.push([k, obj[k]]);
}
alert(JSON.stringify(arr));
Your existing object can be turned into an array with a simple for..in loop. Also your existing code that produces that object can be simplified. Encapsulate both parts in a function and you get something like this:
function countArrayValues(array) {
var counter = {},
result = [];
for (var i = 0, len = array.length; i < len; i++)
if (array[i] in counter)
counter[array[i]]++;
else
counter[array[i]] = 1;
for (i in counter)
result.push([+i, counter[i]]);
return result;
}
console.log( countArrayValues([1,0,0,1,2,0]) );
Demo: http://jsfiddle.net/hxRz2/