How Does *(&Arr + 1) - Arr Give the Length in Elements of Array Arr

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

If a and b are Boolean NumPy arrays, the & operation returns the elementwise-and of them:

a & b

That returns a Boolean array. To reduce this to a single Boolean value, use either

(a & b).any()

or

(a & b).all()

Note: if a and b are non-Boolean arrays, consider (a - b).any() or (a - b).all() instead.



Rationale

The NumPy developers felt there was no one commonly understood way to evaluate an array in Boolean context: it could mean True if any element is True, or it could mean True if all elements are True, or True if the array has non-zero length, just to name three possibilities.

Since different users might have different needs and different assumptions, the
NumPy developers refused to guess and instead decided to raise a ValueError whenever one tries to evaluate an array in Boolean context. Applying and to two numpy arrays causes the two arrays to be evaluated in Boolean context (by calling __bool__ in Python3 or __nonzero__ in Python2).

Cartesian power (a special Cartesian product) -- choose elements from array, in repeatable style

A single loop is hard. Recursive might be the most intuitive approach. But here is an iterative version with two loops, using Python but avoiding magic functionality from itertools so it's not all that language-specific:

a = [0]*n
while(True):
for i in range(n):
a[i] += 1
if a[i] == n:
a[i] = 0
else:
break
else:
break
print("".join(map(str, reversed(a))))

Idea is the following: index your numbers from right to left (thus the reversed call in there). Increment the righternmost digit. As long as you hit the limit of n there, reset to zero but increment the digit one further left. This is essentially adding 1 using long addition with carry. Exit the inner loop when there is no more carry. Exit the outer loop when you don't explicitly exit the inner one, i.e. when you have a carry for all digits.

Test run at https://ideone.com/n0ScW8.

Actually now that I look at the code again, I see a way to use a single loop, and avoid Python's for-else construct which has no obvious counterpart in some other languages. Let's use JavaScript this time, for a change.

a = Array.from(Array(n), x=>0);
i = n - 1;
while (i >= 0) {
a[i]++;
if (a[i] == n) {
a[i] = 0;
i--;
} else {
console.log(a.join(""));
i = n - 1;
}
}

Note that both versions omit the initial 000…0 solution, so they are short one solution. Easy to add that up front. Also notice that I misread the question, so I'm assuming an array of numbers 0 through n-1 while in fact you asked for arbitrary input. But a simple indirection will turn one into the other, so I leave that as an exercise.

Loop over an array in JavaScript

TL;DR

  • Your best bets are usually

    • a for-of loop (ES2015+ only; spec | MDN) - simple and async-friendly
      for (const element of theArray) {
      // ...use `element`...
      }
    • forEach (ES5+ only; spec | MDN) (or its relatives some and such) - not async-friendly (but see details)
      theArray.forEach(element => {
      // ...use `element`...
      });
    • a simple old-fashioned for loop - async-friendly
      for (let index = 0; index < theArray.length; ++index) {
      const element = theArray[index];
      // ...use `element`...
      }
    • (rarely) for-in with safeguards - async-friendly
      for (const propertyName in theArray) {
      if (/*...is an array element property (see below)...*/) {
      const element = theArray[propertyName];
      // ...use `element`...
      }
      }
  • Some quick "don't"s:

    • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
    • Don't use map if you're not using its return value.
      (There's sadly someone out there teaching map [spec / MDN] as though it were forEach — but as I write on my blog, that's not what it's for. If you aren't using the array it creates, don't use map.)
    • Don't use forEach if the callback does asynchronous work and you want the forEach to wait until that work is done (because it won't).

But there's lots more to explore, read on...


JavaScript has powerful semantics for looping through arrays and array-like objects. I've split the answer into two parts: Options for genuine arrays, and options for things that are just array-like, such as the arguments object, other iterable objects (ES2015+), DOM collections, and so on.

Okay, let's look at our options:

For Actual Arrays

You have five options (two supported basically forever, another added by ECMAScript 5 ["ES5"], and two more added in ECMAScript 2015 ("ES2015", aka "ES6"):

  1. Use for-of (use an iterator implicitly) (ES2015+)
  2. Use forEach and related (ES5+)
  3. Use a simple for loop
  4. Use for-in correctly
  5. Use an iterator explicitly (ES2015+)

(You can see those old specs here: ES5, ES2015, but both have been superceded; the current editor's draft is always here.)

Details:

1. Use for-of (use an iterator implicitly) (ES2015+)

ES2015 added iterators and iterables to JavaScript. Arrays are iterable (so are strings, Maps, and Sets, as well as DOM collections and lists, as you'll see later). Iterable objects provide iterators for their values. The new for-of statement loops through the values returned by an iterator:

const a = ["a", "b", "c"];
for (const element of a) { // You can use `let` instead of `const` if you like
console.log(element);
}
// a
// b
// c

Find minimum group of array with difference less than k

This code snippet fixes the code by update the .sort().

function minimumGroups(arr, k) {
// Write your code here
arr.sort((a, b) => a-b); // this line is updated.
let start = 0;
if(arr.length == 0) return 0;
// If arr has some value then at least can form 1 group
let count = 1;
for(let i = 0; i < arr.length; i++) {
if(arr[i] - arr[start] > k) {
count++;
start = i;
}
}
return count;
};

console.log(minimumGroups([ 1, 13, 6, 8, 9, 3, 5 ], 4));

Check for falsy values on array

Try this code if you want to check for falsy values

Let me tell you that falsy values don't require to be boolean!

For Example, 0 is a falsy value however typeof(0) is number ..

The reason why your code returns an empty array is the if condition, you're checking if typeof(arr[i]) !== Boolean && arr[i]

this condition will always be false since typeof returns a string and Boolean is considered as an Object/ Constructor (which isn't a string)

function bouncer(arr) {
let word = []
for (let i = 0; i < arr.length; i++)
if (arr[i]) {
word.push(arr[i])
}
return word;
}

console.log(bouncer([false, null, 0, NaN, undefined, ""]));

How to 'repeat' an array n times

You could do this:

var repeated = [].concat(... new Array(100).fill([1, 2, 3]));

That creates an array of a given length (100 here) and fills it with the array to be repeated ([1, 2, 3]). That array is then spread as the argument list to [].concat().

Oh wait just

var repeated = new Array(100).fill([1, 2, 3]).flat();

would be a little shorter.

How to create a zero filled JavaScript array of arbitrary length?

How about trying like this:

Array.apply(null, new Array(10)).map(Number.prototype.valueOf,0);
//Output as [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

or

new Array(10+1).join('0').split('').map(parseFloat)
//Output as [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

EDIT:-

If your array is dynamic then simply put that in a function which takes a number and replace 10 by that variable.



Related Topics



Leave a reply



Submit