I have just had a brain block, I have a Deck object and want to get every 5 card combination from it in a iterative manner. Could someone show me how to do this, I would imagine it would be:
for(int i =0; i <52; i++){
for(int j = i + 1 ; j < 52; j++){
for(int k = j + 1; k < 52; k++{
for(int l = k + 1; l < 52; l++){
for(int m = l + 1; m < 52; m++){
}
}
}
}
}
Is this correct?
Thanks
Yes, that works fine. If you want to enumerate all n-card combinations, this doesn't work.
For that, you'd need recursion. Put card 0 in slot 0. Recursively enumerate all n-1 card hands (excluding 0) in the remaining n-1 slots. Repeat, with card 1 in slot 0. Pretty easy.
EDIT: some code:
private static final int NUM_CARDS = 52;
public static void main(String[] args) {
enumerateAllHands(Integer.parseInt(args[0]));
}
private static void enumerateAllHands(int n) {
if (n > NUM_CARDS) {
throw new IllegalArgumentException();
}
int[] cards = new int[n];
BitSet cardsUsed = new BitSet();
enumerate(cards, 0, cardsUsed);
}
private static void enumerate(int[] cards, int from, BitSet cardsUsed) {
if (from == cards.length) {
emit(cards);
} else {
for (int i = 0; i < NUM_CARDS; i++) {
if (!cardsUsed.get(i)) {
cards[from] = i;
cardsUsed.set(i);
enumerate(cards, from + 1, cardsUsed);
cardsUsed.clear(i);
}
}
}
}
private static void emit(int[] cards) {
System.out.println(Arrays.toString(cards));
}
Related
I'm doing my homework for Data Structures and I'm having trouble with 2D Array. Here's what I have to do:
"Suppose you are designing a multiplayer game that has n≥1000 players,
numbered 1 to n, interacting in an enchanted forest. The winner of this
game is the first player who can meet all the other players at least
once (ties are allowed). Assuming that there is a method meet(i, j),
which is called each time a player i meets a player j (with i ̸= j),
describe a way to keep track of the pairs of meeting players and who is the winner."
I can't compile because of this error:
Multiplayer.java:51: error: constant expression required
for this line:
case meet: sb.append("1");
I'm a beginner so I really appreciate any help. Thank you in advance!
/* Suppose you are designing a multiplayer game that has n≥1000
players, numbered 1 to n, interacting in an enchanted forest. The winner
of this game is the first player who can meet all the other players at
least once (ties are allowed). Assuming that there is a method meet(i,
j), which is called each time a player i meets a player j (with i ̸=
j), describe a way to keep track of the pairs of meeting players and
who is the winner. */
public class Multiplayer {
int n; // number of players
int map[][] = new int[n][n]; // create a 2D array
int meet = 1;
int notMeet = 0;
int[] count; // an array to keep the count, player wins when it reaches n
public Multiplayer() {
clearMap();
} // initiate a new game
public void clearMap() { // clear the 2d array
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
map[i][j] = notMeet; // clearing the map
count[i] = 0; // turn every value of count[] into 0
if (i == j)
map[i][j] = map[j][i] = meet; // when i == j give the tile the value of 1
}
}
}
public void meet(int i, int j) {
// when player i meets player j, add 1 to the count[] of each player
count[i] = count[i] + 1;
count[j] = count[j] + 1;
}
public int isWin() {
for (int i = 0; i < n; i++) {
if (count[i] == n)
return i; // player at the index i wins
}
return -1; // no player won yet
}
public String toString() {
// display the map in string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
switch (map[i][j]) {
case meet:
sb.append("1"); // if player i and j meets, put 1 in the map //this line causes error
default:
sb.append("0"); // if they haven't met, put the 0 as default
}
if (j < n - 1)
sb.append("|");
}
if (i < n - 1)
sb.append("\n-----\n");
}
return sb.toString();
}
}
class MultiplayerTest {
public static void main(String[] args) {
Multiplayer newGame = new Multiplayer();
newGame.n = 5; // test for a small number of players
// test for player 1 to meet all other players
for (int i = 2; i <= 5; i++) {
newGame.meet(1, i);
}
// print test to see if player 1 wins the game
System.out.println(newGame.toString());
System.out.println(newGame.isWin());
}
}
You can't use variables as the labels in a switch statement.
If you want to have a constant value in your program, the usual method is to create a static final member:
public static final int MEET = 1;
However, in this case if you only have two values then you are better using a boolean array and just checking for true and false. There is no need for a switch statement.
boolean map[][] = new boolean[n][n];
...
if (map[i][j]) {
...
In this case, it is better to rename the array met, so you code reads like this:
if (met[i][j]) {
...
You need to initialize your count array, like
public void initializeArray(int n) {
this.n = n;
count = new int[n];
for (int i = 0; i < n; i++) count[i] = 0;
}
and then, instead of
newGame.n = 5;
you will need to do:
initializeArray(5);
I can't see where you actually create the array count.
Your code:
boolean met[][] = new boolean[n][n]; //edited
int[] count; // an array to keep the count, player wins when it reaches n
creates the array met (... = new boolean[n][n]), but there is no such statement for the array count. Hence, references to count[i] fail.
So I fixed the code like you guys suggested. Thank you all so much! This code below still has an error, but it's a lot better than my original one. Anyone knows about ArraysIndexOutOfBound error?
import java.util.Arrays;
public class Multiplayer {
int n; //number of players
boolean met[][] = new boolean [n][n];
int[] count; //an array to keep the count, player wins when it reaches n
public Multiplayer() {clearMap(); } //initiate a new game
public void clearMap() {
for (int i = 0; i < n; i ++) {
for (int j = 0; j < n; j++) {
met [i][j] = false; //clearing the map
count [i] = 0; //turn every value of count[] into 0
if (i == j)
met[i][j] = met[j][i] = true;
}
}
}
public int[] meet(int i, int j){
//when player i meets player j, add 1 to the count[] of each player
if (i != j) {
count [i] = count[i] + 1;
count [j] = count [j] + 1;
met [i][j] = met[j][i] = true;
}
//System.out.println(Arrays.toString(count));
return count;
}
public void initializeArray(int n) {
this.n = n;
count = new int[n];
for (int i = 0; i < n; i++) count[i] = 0;
}
public int isWin () {
for (int i = 0; i < n ; i++){
if (count[i] == n-1) //if player i meets all the other players
return i; //player at the index i wins
}
System.out.println(Arrays.toString(count));
return -1;
}
public String toString() {
//display the map
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j <n; j++) {
if (met [i][j]) {sb.append("true");} //this line causes error ArrayIndexOutofBound
else {sb.append("false");}
if (j<n-1) sb.append ("|");
}
if (i<n-1) sb.append("\n-----\n");
}
return sb.toString();
}
}
class MultiplayerTest {
public static void main (String[] args) {
Multiplayer newGame = new Multiplayer ();
newGame.initializeArray(5); //test for a small number of players
//test for player 1 to meet all other players
for (int k = 0; k < 5; k++) {newGame.meet (1,k); }
//print test to see if player 1 wins the game
System.out.println(newGame.isWin());
//System.out.println(newGame.toString()); I tried printing the 2D array output into String but encountered an error and don't know how to fix it, but the other methods are fine.
}
}
In the below snippet:
switch (map[i][j]) {
case meet:
sb.append("1"); // if player i and j meets, put 1 in the map //this line causes error
default:
sb.append("0"); // if they haven't met, put the 0 as default
}
Please note that there is no break; statement and hence, as per fall through logic, it will append 0 anyway.
If you just have one case, you should rather use if, e.g.:
if(map[i][j] == meet) {
sb.append("1");
}else {
sb.append("0");
}
update
Regarding the NullPointerException, you are getting that exception because count array is not initialised and you are trying to access the element.
Change the declaration to the following:
int[] count = new int[n];
The 'constant expression required' suggests that the labels in switch case requires a constant. And as suggested by other answers, its better to use if and use boolean 2d array.
ArraysIndexOutOfBound error is actually due to because you need to create an array using the new operator in the constructor method and then pass the reference to
map asmap = new boolean[n][n];
I've tried here:
public class Multiplayer {
int n; //number of players
boolean[][] map; //not initializing here but in constructor
int[] count; //an array to keep the count, player wins when it reaches n
public Multiplayer(int num){
n=num;
map = new boolean[n][n];
count = new int[n];
//No need to use clearMap as all instance variables are assigned the default value of 0 or false or null;
for(int i=0;i<n;i++){ //self-meeting
count[i]=1;
map[i][i]=true;
}
}
public void meet(int i,int j){
if(i==j) return;
//player number 1 is at index number 0
//Hence player i is at index number i-1
i--;j--;
count[i]+=1;
count[j]+=1;
map[i][j]=map[j][i]=true;
}
public int isWin(){
for(int i =0;i<n;i++)
if(count[i]==n)
return i; // player at the index i wins
return -1; // no player won yet
}
public String toString(){
String s = "";
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(map[i][j]) s+="1";
else s+="0";
if(j<n-1) s+="|";
}
s+="\n";
for(int k=0;k<n && i<n-1;k++)
s+="--";
s+="\n";
}
return s;
}
}
public class MultiplayerTest {
public static void main(String[] args) {
int numberOfPlayers = 5;
Multiplayer newGame = new Multiplayer(numberOfPlayers);
// test for player 1 to meet all other players
for (int i = 2; i <=5; i++) {
newGame.meet(1, i);
}
// print test to see if player 1 wins the game
System.out.println(newGame.toString());
System.out.println(newGame.isWin());
}
}
I got το code an array sort for exam preparing. I am already done, the only prob is that my minimum variable is not resetting it self. And I can't put it "null"
Maybe you got an idea... In the beginning I put min = c[0][0]; But if this is the smallest number. It won't work. :/
public class Sort {
public static void main(String[] args) {
int[] a = {3,2,-1,-2,-5,4};
specialSort(a);
}
static void specialSort(int[] a) {
try {
int[] b = new int[a.length];
int[][] c = new int[a.length][2];
for (int k = 0; k<a.length; k++) {
for (int l = 0; l<2; l++) {
if (l == 0) {
c[k][l] = a[k];
} else {
c[k][l] = 0;
}
}
}
int min, minindex;
for (int j=0; j<c.length; j++) {
for (int i=0; i<c.length; i++) {
if (c[i][1] == 0) {
min = c[i][0];
if (min > c[i][0]) {
min=c[i][0];
minindex = i;
}
}
}
b[j] = min;
c[minindex][1] = 1;
}
for(int i=0; i<c.length; ++i) {
//for(int j=0; j<2; j++) {
System.out.print(b[i]+" ");
System.out.println();
}
} catch (IllegalArgumentException e) {
System.out.println("dulli");
}
}
}
If I understand correctly what you're saying and what your problem is, why don't you try setting min initially to
Integer.MAX_VALUE
or
Long.MAX_VALUE
depending on the type of your data, so that you will replace it somehow with one of the numbers from your input, because for sure some number from your input will be smaller than the largest number java can represent? I think it should work if you do it this way
I need to create a function that outputs all possible binary combinations (2^8 == 256 different sequences of 8 bits.). I'm really stumped on this. I have to do it with nested loops, and am not sure how to go about it. Below is what I tried so far. I was told that I could write this program using 8 nested loops, each one going from 0 to 1; Also, I could try to do this with bit manipulation operators.
Although what I have below is obviously wrong, I tried my best to show that I at least tried this. I also need to put new line's after each closing bracket, to separate the output.
The output should look like this:
00000000
00000001
00000010
00000011
00000100
...
11111110
11111111
public static void outputBinary(){
int[][][][][][][][] num = new int[2][2][2][2][2][2][2][2];
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.print(num[i][j][k][l][m][n][o][p]);
} }}}}}}}
}
Thanks for looking.
No need for the array. Here is a slight modification to your code that will output all the permutations.
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.println("" + i + j + k + l + m + n + o + p);
}
}
}
}
}
}
}
}
Do you have to use nested loops? Because this is trivially easy when you simply take advantage of the fact that the binary representation of all the numbers from 0 through 255 cover every permutation.
for (int i=0; i<256; i++) {
System.out.println(Integer.toBinaryString(i));
}
Just print the for variables (i...p) without accessing this obscure empty array.
Well, if it's OK to use some built-in classes, you can do this in the following way:
for (int i=0; i<256; i++){
System.out.println(Integer.toBinaryString(i));
}
And the second way (I believe you should use it, because looking by looking at it you can understand what's under the hood instead of "some magic", it uses bit mask):
for (int i=0;i<256;i++){
int mask = 256;
while (mask > 0){
if ((mask & i) == 0){
System.out.print("0");
} else {
System.out.print("1");
}
mask = mask >> 1;
}
System.out.println();
}
Here's my version. It uses recursion to convert base 2 to base 10 through repeated division:
public static void printBin()
{
for (int i = 0; i < 256; i++) {
int binary = decToBin(i, "");
// pad to give length of 8
System.out.println(String.format("%08d", binary));
}
}
public static int decToBin(int dec, String bin)
{
int quot = dec / 2;
int remainder = dec % 2;
if (quot == 0)
return Integer.parseInt("" + remainder + bin);
return decToBin(quot, "" + remainder + bin);
}
Heres another way of generating all the values using bit operations
public static void main(String[] args) {
int numBits = 8;
int val = 0;
int[] values = new int[]{0,1};
values[0] = 0;
values[1] = 1;
for (int i = 1; i < numBits; i++) {
int[] moreValues = new int[values.length * 2];
int start = (int)Math.pow(2, i);
for (int j = 0; j < values.length; j++) {
moreValues[j * 2] = values[j] << 1;
moreValues[j * 2 + 1] = values[j] << 1 | 1;
}
values = moreValues;
}
//print the values
for (int value: values) {
System.out.println(Integer.toBinaryString(value));
}
}
And another way, using bit operations and recursion
private static void generateNumbers(int number, int numBits, int currentBit) {
if (numBits == currentBit) {
Integer.toBinaryString(number);
return;
}
currentBit++;
generateNumbers(number << 1, numBits, currentBit);
generateNumbers(number << 1 | 1, numBits, currentBit);
}
public static void generateNumbers(int numBits) {
generateNumbers(0, 8, 1);
generateNumbers(1, 8, 1);
}
public static void main(String[] args) {
generateNumbers(8);
}
package org.cross.topology;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//System.out.println("sushil");
int digits=3;//Provide number of digits for which you want combinations of 0 and 1
int noof0and1=(int) Math.pow(2,digits)/*(2^digits)*/,combinations=(int) Math.pow(2,digits),secondloopcounter=0,temp=0;
String current_char="0";
int startindex=0,lastindex;
ArrayList<String> al=new ArrayList<String>(combinations);
for(int k=0;k<combinations;k++)
{
al.add("");
}
for(int i=1;i<=digits;i++)
{
noof0and1=noof0and1/2;
while(temp!=combinations)
{
temp=temp+noof0and1;
secondloopcounter++;
}
lastindex=noof0and1;
startindex=0;
for(int s=0;s<secondloopcounter;s++)
{
for(int j=startindex;j<lastindex;j++)
{
String temps=al.get(j)+current_char;
al.remove(j);
al.add(j, temps);
}
if(current_char.equals("0"))
{
current_char="1";
}
else
{
current_char="0";
}
startindex=lastindex;
lastindex=lastindex+noof0and1;
}
temp=0;
secondloopcounter=0;
}
for(int l=0;l<al.size();l++)
{
System.out.println(al.get(l));
}
}
}
Below is the solution using Recursion as an approach in java
public class NumberOfBinaryPatterns {
static int[] bitArray = new int[]{0,1};
public static void main(String args[])
{
System.out.println("Below are the patterns\n");
int numberOfBits=4; // It can be any value based on the requirement, In this case we can put this as 8
drawBinaryPattern(numberOfBits,"");
}
private static void drawBinaryPattern(int n,String seed)
{
if(n==0){
System.out.println(seed);
return;
}
for(int j=0;j<bitArray.length;j++)
{
String temp = seed+bitArray[j];
drawBinaryPattern(n-1,temp);
}
}
}
Do in php , very easy
Just convert every count of combinations in binary and add as many 0 as required to complete it in a byte representation.
for($c=1;$c<=pow(2,8);$c++)
{
$bin_str=base_convert($c,10,2); //converting combination number into binary string
$len_str=strlen($bin_str); // Length of string obtained
for($i=1;$i<=8-$len_str;$i++)
$bin_str="0".$bin_str; // adding as many 0 as required to complete in byte format
echo "<br>".$bin_str; //Displaying binary values in byte structure
}
currently recursion is fresh & difficult topic for me, however I need to use it in one of my algorithms.
Here is the challenge:
I need a method where I specify number of recursions (number of nested FOR loops) and number of iterations for each FOR loop. The result should show me, something simmilar to counter, however each column of counter is limited to specific number.
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
public void recursion(ArrayList<Integer> specs){
//number of nested loops will be equal to: specs.size();
//each item in specs, specifies the For loop max count e.g:
//First outside loop will be: for(int i=0; i< specs.get(0); i++)
//Second loop inside will be: for(int i=0; i< specs.get(1); i++)
//...
}
The the results will be similar to outputs of this manual, nested loop:
int[] i;
i = new int[7];
for( i[6]=0; i[6]<5; i[6]++){
for( i[5]=0; i[5]<7; i[5]++){
for(i[4] =0; i[4]<9; i[4]++){
for(i[3] =0; i[3]<2; i[3]++){
for(i[2] =0; i[2]<8; i[2]++){
for(i[1] =0; i[1]<9; i[1]++){
//...
System.out.println(i[1]+" "+i[2]+" "+i[3]+" "+i[4]+" "+i[5]+" "+i[6]);
}
}
}
}
}
}
I already, killed 3 days on this, and still no results, was searching it in internet, however the examples are too different. Therefore, posting the programming question in internet first time in my life. Thank you in advance, you are free to change the code efficiency, I just need the same results.
// ...
recursion (specs, specs.size () - 1);
// ...
public void recursion(ArrayList<Integer> specs, int startWith){
for (int i = 0; i < specs.get(startWith); i++) {
// ...
if (startWith - 1 >= 0)
recursion (specs, startWith - 1);
}
}
Your function also need to now the index of the specs array to use for iteration, and also the previous numbers that should be printed:
public void recursion(ArrayList<Integer> specs, int index, String output) {
if( index >= specs.size() ) {
System.out.println(output);
return;
}
for (int i = 0; i < specs.get(index); i++ )
recursion( specs, index+1, Integer.toString(i) + " " + output );
}
The you should call it like this:
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5);
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
recursion( specs, 0, "" );
Does this snippet give the output you want? (It is compileable and executeable)
import java.util.ArrayList;
import java.util.List;
public class SO {
static ArrayList<Integer> specs = new ArrayList<Integer>();
static int[] i;
public static void main(String[] args) throws Exception {
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
i = new int[specs.size()];
printMe(0, specs, i);
}
static void printMe(int depth, List<Integer> _specs, int[] i) {
if (_specs.isEmpty()) {
System.out.println(printI(i));
return;
} else {
for (int j = 0; j < _specs.get(0); j++) {
i[depth] = j + 1; // + 1 since you seems to want to go from 1 and not 0
printMe(depth + 1, _specs.subList(1, _specs.size()), i);
}
}
}
static String printI(int[] i) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i.length; j++) {
sb.append(i[j]);
if (j < i.length - 1) {
sb.append(" ");
}
}
return sb.toString();
}
}
You can try this :
public static void loops(ArrayList<Integer> specs, int idx, StringBuilder res){
if(idx==specs.size()-1){
for (int i = 0; i < specs.get(idx); i++) {
System.out.println(i+" "+res);
}
}
else{
for(int i=0;i<specs.get(idx);i++){
res.insert(0,i+" ");
loops(specs,idx+1,res);
res.delete(0, 2);
}
}
}
And call with :
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
loops(specs,0, new StringBuilder());
I think I have done the selection sort but I am not sure. Is this really an implementation of selection sort?
static void selectionSort()
{
int min = Integer.MIN_VALUE;
int n = 0;
for(int I=0; I<arraySize; I++)
{
min = dataArray[I];
for(int j=I; j<n; j++)
{
if(dataArray[min]<dataArray[j])
{
min = j;
if(dataArray[min] < dataArray[I])
{
int temp = dataArray[I];
dataArray[I] = dataArray[min];
dataArray[min] = temp;
}
}
}
}
}
I'm not sure I understand how your algorithm works at all. Specifically, you do
min = dataArray[i];
and then later
dataArray[min]<dataArray[j]
i.e. you treat min both as a value in the array, and an index.
Selection sort works as follows:
Find the minimum value in the list
Swap it with the value in the first position
Repeat the steps above for the remainder of the list
(source)
The changes required for your code to accurately implement selection sort would be the following:
Change the inner loop to just find the index of the smallest element. Call it minIndex for instance.
Do the swapping after the inner loop. i.e., swap element at index I with minIndex.
Oh, and as DonCallisto points out in the comments, you may want to do n = dataArray.length instead of n = 0 :-)
public class SelectionSort {
/**
* #Author Chandrasekhara Kota
*/
public static void main(String[] args) {
int arr[]={9,1,8,5,7,-1,6,0,2,2718};
int sortedArr[]=selectionSort(arr);
for (int i = 0; i <sortedArr.length; i++)
{
System.out.println(sortedArr[i]);
}
}
private static int[] selectionSort(int[] arr) {
int minIndex, tmp;
int n = arr.length;
for (int i = 0; i < n - 1; i++)
{
minIndex = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
return arr;
}
}
Here is a selection sort implementation in java -
public class SelectionSort {
static int intArray[] = { 10, 5, 100, 1, 10000 };
public static void doSort() {
for (int outer = 0; outer < intArray.length; outer++) {
int minPosition=outer;
for(int inner=outer;inner<intArray.length;inner++){
if(intArray[inner]<intArray[minPosition]){
minPosition=inner;
}
}
int temp=intArray[minPosition];
intArray[minPosition]=intArray[outer];
intArray[outer]=temp;
}
}
public static void printArray() {
for (int i = 0; i < intArray.length; i++) {
System.out.print(" " + intArray[i]);
}
}
public static void main(String args[]) {
System.out.print("Array Before Sorting->");
printArray();
doSort();
System.out.print("\nArray After Sorting ->");
printArray();
}
}
The above code is picked from - http://www.javabrahman.com/algorithms-in-java/selection-sort-in-java/. This link has detailed explanation on the working of the above code just in case you need the same.