<commit_before>---
author: <EMAIL>
comments: true
date: 2011-10-18 12:00:00+01:00
layout: post
title: Print all possible, non-empty subsets of an array
tags: [java, programming, algorithms, bit-twiddling]
share: true
---

It’s actually a really simple task. Everything you need is a counter between 1 and 2^n-1, where n is the number of entries. For each possible value of the counter check it’s bits - 1 at position i means that i'th value of the array is present in the particular subset. No recursion, only shifts and additions.

{% highlight java %}
int[] numbers = {1,2,3,4};
int n = numbers.length;
int np = 1<<n;
for (int i=1; i<np; i++){
	int bitv = i;
	int pos = 0;
	while (bitv > 0){
		if ((bitv & 1) == 1) System.out.print(numbers[pos] + " ");
		bitv >>= 1;
		pos++;
	}
	System.out.println();
}
{% endhighlight %}
<commit_msg>Rename a post<commit_after>---
author: <EMAIL>
comments: true
date: 2011-10-18 12:00:00+01:00
layout: post
title: All subsets of an array
tags: [java, programming, algorithms, bit-twiddling]
share: true
---

It’s actually a really simple task. Everything you need is a counter between 1 and 2^n-1, where n is the number of entries. For each possible value of the counter check it’s bits - 1 at position i means that i'th value of the array is present in the particular subset. No recursion, only shifts and additions.

{% highlight java %}
int[] numbers = {1,2,3,4};
int n = numbers.length;
int np = 1<<n;
for (int i=1; i<np; i++){
	int bitv = i;
	int pos = 0;
	while (bitv > 0){
		if ((bitv & 1) == 1) System.out.print(numbers[pos] + " ");
		bitv >>= 1;
		pos++;
	}
	System.out.println();
}
{% endhighlight %}

{'fraction_non_alphanumeric': 0.1395631067961165, 'fraction_numerical': 0.04004854368932039, 'mean_word_length': 3.835777126099707, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5266581', 'n_tokens_mistral': 628, 'n_tokens_neox': 561, 'n_words': 233}