all possible subsets in java in different sequences [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a set =(1, 2, 3), and I need to get all possible subsets of set with different sequences (with repeating elements).The out put look:
1
2
3
1,2
1,3
2,1
2,3
3,1
3,2
1,2,3
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1
please can someone help me with that? thxx

If you want subsets, then Google Guava has a method for you:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Sets.html#powerSet(java.util.Set)
But in your example you have some duplicate sets (remember, sets are unordered). So you might want to get all the possible permutations of each subset as well:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Collections2.html#permutations(java.util.Collection)

The problem can be solved by finding all combinations using bitwise operations.
The idea is: Generate all the subsets of a given array (set), this set is known as a power set .For each of the subset(Combination), find its permutation too.
Refer the following tutorials, to learn, how can you find all combinations using Bit Wise Operations. http://www.codechef.com/wiki/tutorial-bitwise-operations
void PERMUTE()
{
/*PERMUTATION FUNCTION THAT PERMUTES THE SUBSET ARRAY*/
}
public static void main(String[] args)
{
// TODO code application logic here
int Set[]={1,2,3};
int n=Set.length;
for (int i = 0; i <= (1 << n); ++i)
{
System.out.print("[");
int subsetSz=0;
int A[]=new int[100];
for (int j = 0; j < n; ++j)
{
if ((i & 1 << j)!=0)
{
System.out.print(Set[j]+",");
A[subsetSz++]=Set[j];
}
}
System.out.println("]");
/*Permute the subset*/
if(subsetSz>1)
{
PERMUTE(A);
}
}
}

Related

find smallest and largest element in array and print location of element [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What is the easiest way to find the largest and smallest element in an array and print its index location without using an algorithm. Is there a way to do it using a loop or if statement as i am new to java and it is as far as my knowledge goes for now.
This is my code for the array:
import java.io.*;
public class Tut2ArraysQ4
{
public static void main(String [] args) throws IOException
{
BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
int []item=new int[5];
for (int i = 0; i < item.length; i++)
{
System.out.println("Enter a number: ");
int num=Integer.parseInt(kbd.readLine());
System.out.println("Index " + i + " Contains Number " + num);
}
}//end class
}//end main
i am grateful for your help
You declare two variables equal to the element in the first position of your array, and two equal to the first position.
int min = array[0];
int max = array[0];
int posMin = 0;
int posMax = 0;
Make a for to iteration over all position of the array:
for(all the position of the array)
// if current position bigger than max
// max = element of the array in the current position
// posMin = current position
// if current position smaller than min
// min = element of the array in the current position
// posMax = current position
Another approach is sorting the array, the smallest element will be in the first position and the biggest on the last position of the array. However, this solution takes typically N lg N while the first one I post performance in N. If you are using radix sort it will take k N, but:
Sometimes k is presented as a constant, which would make radix sort
better (for sufficiently large n) than the best comparison-based
sorting algorithms, which are all O(n·log(n)). However, in general k
cannot be considered a constant.
read more about
I'm sorry, but unfortunately, There is no way to do what you're trying to do without using an Algorithm.
Even if you pick 2 numbers and prey that you're right, you'll be using an algorithm.

Generate Random Letters in Java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
hey guys this is my problem..
I want to generate random letters in an specific length of a word, but the Starting Letter should corresponds to value of the variable I declare.
Example:
A3 should generate AER
A5 should generate AJIEH
B2 should generate BJ
Working with the variable names will be tedious (although it is possible I suppose through reflection). You could, however, try something like this:
public static String genString(char first, int len) {
String s = "";
for (int i = 1 ; i < len ; i++)
s += (char)(Math.random() * ('Z' - 'A' + 1) + 'A');
return first + s;
}
For example:
System.out.println(genString('A', 4));
Output (one of many possible):
AVGH

How does recursion work? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Please explain how recursion works, in the simplest way you can.
As been pointed out, recursion is when a function calls itself. Here illustrated using factorial, where factorial(5) mathematically evalutates to values 5 * 4 * 3 * 2 * 1.
public int factorial(int x) {
if (x == 1) return 1;
else return x * factorial (x - 1);
}
// Try routine
factorial(3);
Which evaluates as
factorial(1) = 1 = 1
factorial(2) = 2 * factoral(1) = 2 * 1
factorial(3) = 3 * (2 * factorial(2) * (factorial(1)) = 3 * 2 * 1
...
Usually, it's a function that calculates one result itself, and calls itself to get the rest of the results.
For example, to get all positive numbers less or equal to 3, the function says, "One result is 3, and the rest of the results are all positive numbers less or equal to 2. Let's call myself with 2 and add that result to the one I calculated."
Of course, recursive functions need to be careful to have an "end condition" or they will never return a result. In the case of this example, the end condition would be when the function is called with 0, it should just return 0.
Here's a simple example of recursive method: -
public int recur(int count) {
if (count < 10) {
return count + recur(count++);
}
return count;
}
System.out.println(recur(0)); // Invoke first time
Recursion is a method which calls itself from within itself.
Example:
public void recur(int x)
recur(10);
end
Recursion is when a function calls itself:
int factorial(int integer)
{
if (integer == 1)
return 1;
else
return (integer*(factorial(integer-1)));
}

Calculating the first and last k digits in n^n [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to print the first k digits and the last k digits in
n^n (n to the power of n, where n is an integer)
For example :
Input Output
n k First k digits Last k digits
4 2 --> 25 56
9 3 --> 387 489
I sense that it requires some clever mathematics, however I am unable to think of anything as such. Please suggest a way to approach the problem.
The last k digits are easy, you just need to calculate it modulo 10^k. To do this, after every multiplication, just apply the modulo, ie. intermediate_result %= 10^k.
Of course, you will need to calculate 10^k using some other method, because ^ does not mean power of in C or Java.
To find the first k digits, see first n digits of an exponentiation.
Thanks everyone for their help. My final code is
#include <stdio.h>
#include <math.h>
long int lastKdigits(long long n,int k)
{
long long i,res=1,div=pow(10,k);
for(i=1;i<=n;i++)
{
res=(res*n)%div;
}
return res;
}
long int firstKdigits(long long n,int k)
{
long double x, y;
x = n*log10(n);
y = floor(pow(10,x-floor(x) +k-1));
return ((int)y);
}
int main()
{
long long n;
int k;
scanf("%lld %d",&n,&k);
printf("%ld\t",firstKdigits(n,k));
printf("%ld\n",lastKdigits(n,k));
}
return 0;
}
For last k digits it's pretty easy you just need to calculate n^n (mod 10^k) but I don't know any solution for the other k diggits!

Sorting a char array in java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How would I sort a char array in Java? I know I can use java.util.Arrays.sort(), but if I manually want to sort it? Using bubble sort or something?
Notice the string is "cab", the sorted result should be "abc". I don't know how to sort this, i know how to sort integers, but i don't know how to sort char arrays.
Here's my code:
String s1 = "cab";
char[] arr;
arr = s1.toCharArray();
//Could use
//java.util.Arrays.sort(arr);
//But want to do it manually using something like bubble sort
s1 = new String(arr);
characters can be directly compared as the comparison operators are overloaded. w>q i.e
arr[1]>arr[0]
is valid and gives true. So just treat them like integers in the bubble sort algorithm.
Using bubble sort or something?
Yes, a bubble sort would work. Or you could use any one of the other well-known sort algorithms; e.g. as listed in this Wikipedia page ... or any good textbook on data structures and algorithms.
(But no, I'm not going to code this for you.)
I have no idea weather this solution is the best way, and to be honest I don't think it is.
But I'v made a little piece of code which sorts an array in the following steps:
Make a for loop that goes from 0 to array.size() * array.size().
Make a index variable (int) which is 0 out side the loop
in the loop add a try catch and catch OutOfBoundsException, in the catch set index to 0.
In the try you get 'index' of your array,
char c = array[index]
And compare to index +1
c.compareTo(array[index +1])
If that's a positive number >0 you switch the two items' positions array[index] and array[index + 1]
If it doesn't make sense to you I can provide a code sample, but not before 2 hours from now, approximately..
This is what I meant:
public static ArrayList<mContact> SortByName(ArrayList<mContact> arr)
{
int i = 0;
for (int o = 0; o < arr.size() * arr.size(); o++)
{
try
{
int c = arr.get(i).getName().compareTo(arr.get(i + 1).getName());
if (c > 0)
{
mContact con = new mContact(arr.get(i).getName());
arr.get(i).setName(arr.get(i+1).getName());
arr.get(i+1).setName(con.getName());
}
i++;
}
catch (IndexOutOfBoundsException ex)
{
i = 0;
}
}
return arr;
}
That sorts the List by the contacts Name in ascending order.
The compareTo Method returns a integer that represents the diffrence of the two strings. and 0 if they are the same!
You can compare ASCII values of each of the characters or convert each of the to int using parseInt and compare their values.

Categories