How to find all possible numbers with a Recursion method - java

i want to write a Recursion method that prints all possible arrangements for these
numbers , the integers 1 to 9
arranged randomly in a grid of three rows and three column.for example :
6 2 1
5 4 7
3 9 8
sorry i don't have any code , because it's very hard to me.
public class Test {
public static void main (String[] args){
String x = "123456789";
System.out.println(test(x,0));
}
public static String test(String x , int y){
if(x.length()==1)return "";
return x.charAt(y)+test(x.substring(y),y);
}

There are many ways to implement something like this, this is one example. I will use int[] instead of String for convenience sake:
public static void main(String[] args) {
nextPermutation(new int[9], 0, new boolean[9]);
}
public static void nextPermutation(int[] perm, int index, boolean[] alreadyUsed) {
if(index == perm.length) {
//the permutation is complete
//you can store it or print it
} else {
for(int i = 0 ; i < alreadyUsed.length ; i++) {
if(alreadyUsed[i]) continue;
perm[index] = i+1;
boolean[] newAlreadyUsed = Arrays.copyOf(alreadyUsed, alreadyUsed.length);
newAlreadyUsed[i] = true;
nextPermutation(Arrays.copyOf(perm, perm.length), index+1, Arrays.copyOf(newAlreadyUsed, newAlreadyUsed.length));
}
}
}
This will generate all possible combinations of 1-9. The idea of the algorithm is that you keep track of which digits you already used, run through a loop and select all available digits.
Note that it's important to pass copies of perm and alreadyUsed, otherwise you will just pass the same array and overwrite previous permutations.

pass values ​​to an array, randomize and create a loop to generate the matrix.
loop: make a generic loop starting to generate matrix with i0 , j0 like position i1 , j1 of matrixand add the values of array
int j = 0;
for( int i = 0; i <= YOURARRAY.length(); i++)
{
System.out.println( i POSITIONOFARRAY );
j+1
}

Related

I couldn't create a method to count the number of occurrences

I've created a method to count the number of occurrences in an array, but I can't compile and run it.
Compiler gives the error:
The method occurence(int[]) in the type countOfOccurence is not applicable for the arguments (int)
public class countOfOccurence {
public static void main(String[] args) {
int[] number = {15,16,14};
System.out.print(occurence(number[15]));
}
public static int occurence(int[] number) {
int count = 0;
for(int i = 0 ; i < number.length; i++) {
for(int k = 0 ; i < number.length; i++) {
if(number[k] == number[i]) {
count++;
}
}
}
return count;
}
}
Your occurrence method is expecting an array, but you are just passing an int to it (the 15th element from your array, which will also cause a runtime error as there are only 3 elements in your array).
But I also think your logic is off here, your current method (given that it would compile) will count all occurrences of all duplicate numbers in your array, not just the number you would want.
First off all, your occurrence method would need 2 arguments, the actual array and the number you want to count the occurrences of. You don't need an inner loop, just keep your outer loop and check inside whether the array element equals your desired number.
public static void main(String[] args) {
int[] number = {15,16,14};
System.out.print(occurence(number, 15));
}
public static int occurence(int[] numberArray, int number) {
int count = 0;
for(int i = 0 ; i < numberArray.length; i++) {
if(numberArray[i] == number) {
count++;
}
}
return count;
}
Of course there are better / cleaner ways to count occurrences of elements in an array, for example using the Streams api, if you would want to optimize.
occurence(int[] number) function accepts the integer array parameter. And, you are calling the function with occurence(number[15]). By number[15], it means 15th-index position from number array, which is also not valid in your code.
For your scenario to work, occurence function should be changed to accept two parameters like public static int occurence(int[] numbers, int number). And, call it by occurence(number, 15).

Method doesn't work

For my assignment, I have to use methods to find the number of patterns in an array. The pattern is counted when the sum of adjacent numbers in an array is more than 7.
I have to use 2 methods, 1 being insertNumbers to create an array and another being computePattern to count the patterns.
However, the pattern printed out doesn't match the array printed out. Here is the code.
As this is an assignment, I would rather not get answers but answers on which part of my code is wrong, and how do I fix it.
EDIT: Here is a sample output.
Sample output #1: Array: 2 7 2 3 1 5 7 4 3 6
Number of patterns: 3
public static int[] insertNumbers()
{
//Declaring the array.
int randomArray[] = new int[10];
//Setting random numbers into the array.
for (int k = 0;k < randomArray.length;k++)
{
int i = (int)((Math.random()*9)+1);
randomArray[k] = i;
}
//Returning array into other methods.
return randomArray;
}
public static int computePattern()
{
int a = 0;
int b = 1;
int pattern = 0;
int[] randomArray = insertNumbers();
//Computing the number of patterns.
for (;a<=8 && b<=9;)
{
if (randomArray[a] + randomArray[b]>7)
{
pattern++;
}
a+=2;
b+=2;
}
return pattern;
}
public static void main(String[] args)
{
int pattern = computePattern();
int[] randomArray = insertNumbers();
//Printing out the contents of the array.
System.out.print("Array : " );
for(int i = 0; i < 10; i++)
{
System.out.print(+randomArray[i] +" ");
}
System.out.println(" ");
//Printing out the number of patterns.
System.out.println("Number of patterns: "+pattern);
}
You are computing pattern for a different array, and in main you are printing different array (you are calling insertNumbers twice basically). See here:
int pattern = computePattern(); // First time computePatter generates one array
int[] randomArray = insertNumbers(); // Another array is generated here
Also, doesn't seem your pattern counting is correct. Hint: does it compare elements with indexes 1 and 2?
Remove this line from your main function
int[] randomArray = insertNumbers();
You are calling the function insertNumbers again after computing the pattern.
You should do the compute pattern part this way
{
int a;
int pattern = 0;
int[] randomArray = insertNumbers();
//Computing the number of patterns.
for (a=1;a<9;a++)
{
if (randomArray[a] + randomArray[a-1]>7)
{
pattern++;
}
}
return pattern;
}
And you definitely calling insertNumbers Twice. You should call it once in main and send that array to computePattern.
int[] randomArray = insertNumbers();
int pattern = computePattern(randomArray);

Testing a random number generator

I am having trouble printing out the first two columns of the results in a table but as I am new to programming I am having issues and wondering where the issue is in my code. The brief states I must create:
A parameterless static int method, randInt(), that will return a random integer in the range 0..9 inclusive. This method will include a call to Math.random().
A static void method named randTest that takes a single integer argument, n. This should perform the following actions:
Declare an int array of 10 elements named counts. This will be used to record how often each possible value is returned by randInt.
Call randInt n times, each time incrementing the count of the element of counts corresponding to the value returned.
Print the results to the console in a clear tabular form. The output should look like the following:
This is my code:
import java.util.Arrays;
public class RandNumGenerator {
public static int RandInt(){
double n = Math.random()*10;
return (int) n;
}
public static void randTest(int n){
int [] counts = new int [10];
for(int i=0;i<n;i++){
counts[i] = RandInt();
System.out.println(counts[i]);
}
}
public static void main(String[] args) {
int sampleSize = 1000;
System.out.println ("Sample Size: " + sampleSize);
String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
System.out.println(Arrays.toString(intArray));
randTest(10);
}
}
public static void randTest(int n){
Question for you to think about: What is the parameter here? Hint: It's not 10... What do you actually want to DO n times?
counts[i] = RandInt();
You really want to create 10 random numbers and store them into the array? Nope. You want to create "sampleSize" numbers and increase the array on the correct position. What would the correct position be?
counts[ correctPosition ] = counts[ correctPosition ] + 1;
...would be more correct, if you can figure out the correctPosition.
Also I would move the output from the main method to randTest() where you have everything together.

Count how many times an element occurs in an array - Java

I recently made a very simple practice program in Python, that takes user input and rolls dice. The code is:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(actually this is part of a larger program, so I had to cut'n'paste bits, and I might have missed something out).
And so I decided to translate that to Java. Notice the algorithm here: get random number, print it, append it to an array, then count the amount of each number in the array at the end, and print out that value. Problem is, I don't know how to do the equivalent of someArray.count(someIndex) in Java syntax. So my Java program looks like this so far:
import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
So can someone help me with the array counting code? I understand that this might not be a defined method, since Python is higher level after all, so I could make my own array counting method, but I was wondering if Java, like Python, has a predefined one.
EDIT: I managed something like this:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
EDIT: Just out of interest, assuming I use Command prompt to run my Java program and Python.exe (command prompt console for Python), which one will be faster (in other words, for the same code, which language has better performance?)?
You could use a HashMap to store the result.
If the new number is not in your map you add it with "1" as initial value.
If it exists your put "+1" to the current map value.
To display the values you just have to iterate on you entries in a for each loop.
The solution is to transform your array to a List and then use the Collections.frequency method:
List<Integer> resultList = Arrays.asList(results);
int freq = Collections.frequency(resultList, 4);
Also you could use ArrayList from the very beginning saving you the transformation:
List<Integer> result = new ArrayList<Integer>();
// add results
int freq = Collections.frequency(result, 4);
See the Collections documentation here
EDIT: If performance is an issue (as suggested in the comments) then maybe you want to use each index of the array as a counter, as follows:
Random flip = new Random(SIDES);
int[] counters = new int[SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
counters[result] = counters[result]+1;
}
Notice that you no longer need to count at the end since you've already got all the counters in the array and there is no overhead of calculating the hash.
There are a couple libraries that will do this for you:
Google Guava's MultiSet
Apache Common's Bag
But for something so simple, you may consider an extra library a bit excessive.
You can also do this yourself with an int[]. Assuming your dice is using whole numbers, have the number rolled refer to the index into the array, and then increment the value at that index. When you need to retrieve the value for a given number, look up its value by the index.
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
There's a frequency method in collections
int occurrences = Collections.frequency(listObject, searchItem);
Java doc for collections
As far as I am aware, there is no defined method to return the frequency of a particular element in an array. If you were to write a custom method, it would simply be a matter of iterating through the array, checking each value, and if the value matches the element you're after, incrementing a counter.
So something like:
// in this example, we assume myArray is an array of ints
private int count( int[] myArray, int targetValue) {
int counter = 0;
for (int i = 0 ; i < myArray.length; i++ ) {
if (myArray[i] == targetValue) {
counter++;
}
}
return counter;
}
Of course, if you want to find the frequency of all the unique values in your array, this has the potential of being extremely inefficient.
Also, why are you using a 7-sided die? The Random nextInt() will return a number from 0 up to but not including the max. So your die will return values from 0 through 6. For a six-sided die, you'd want a new Random(6); and then increment your roll by one to get a value from one through six: flip.nextInt() +1;.
class FindOccurrence {
public static void main (String[]args) {
int myArray[] = {5, 8, 5, 12, 19, 5, 6, 7, 100, 5, 45, 6, 5, 5, 5};
int numToFind = 5;
int numberOfOccurrence = 0;
for (int i=0; i < myArray.length; i++) {
if (numToFind == myArray[i]) {
numberOfOccurrence++;
}
}
System.out.println("Our number: " + numToFind);
System.out.println("Number of times it appears: " + numberOfOccurrence);
}
}

recursion resulting in extra unwanted data

I'm writing a module to handle dice rolling. Given x die of y sides, I'm trying to come up with a list of all potential roll combinations.
This code assumes 3 die, each with 3 sides labeled 1, 2, and 3. (I realize I'm using "magic numbers" but this is just an attempt to simplify and get the base code working.)
int[] set = { 1, 1, 1 };
list = diceroll.recurse(0,0, list, set);
...
public ArrayList<Integer> recurse(int index, int i, ArrayList<Integer> list, int[] set){
if(index < 3){
// System.out.print("\n(looping on "+index+")\n");
for(int k=1;k<=3;k++){
// System.out.print("setting i"+index+" to "+k+" ");
set[index] = k;
dump(set);
recurse(index+1, i, list, set);
}
}
return list;
}
(dump() is a simple method to just display the contents of list[]. The variable i is not used at the moment.)
What I'm attempting to do is increment a list[index] by one, stepping through the entire length of the list and incrementing as I go.
This is my "best attempt" code. Here is the output:
Bold output is what I'm looking for. I can't figure out how to get rid of the rest. (This is assuming three dice, each with 3 sides. Using recursion so I can scale it up to any x dice with y sides.)
[1][1][1] [1][1][1]
[1][1][1] [1][1][2] [1][1][3] [1][2][3]
[1][2][1] [1][2][2] [1][2][3] [1][3][3]
[1][3][1] [1][3][2] [1][3][3] [2][3][3] [2][1][3]
[2][1][1] [2][1][2] [2][1][3] [2][2][3]
[2][2][1] [2][2][2] [2][2][3] [2][3][3]
[2][3][1] [2][3][2] [2][3][3] [3][3][3] [3][1][3]
[3][1][1] [3][1][2] [3][1][3] [3][2][3]
[3][2][1] [3][2][2] [3][2][3] [3][3][3]
[3][3][1] [3][3][2] [3][3][3]
I apologize for the formatting, best I could come up with.
Any help would be greatly appreciated. (This method was actually stemmed to use the data for something quite trivial, but has turned into a personal challenge. :)
edit: If there is another approach to solving this problem I'd be all ears, but I'd also like to solve my current problem and successfully use recursion for something useful.
edit2:
Running code including the "easy fix." Beware unused variables and weird hacks, I haven't cleaned it up yet.
package code.testing;
import java.util.ArrayList;
public class CodeTesting {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
int[] set = { 1, 1, 1 };
list = recurse(0,0, list, set);
}
public static ArrayList<Integer> recurse(int index, int i, ArrayList<Integer> list, int[] set){
if(index < 3){
// System.out.print("\n(looping on "+index+")\n");
for(int k=1;k<=3;k++){
// System.out.print("setting i"+index+" to "+k+" ");
set[index] = k;
if (index==2){
dump(set);
}
recurse(index+1, i, list, set);
}
}
return list;
}
static void dump(int[] arr) {
for (int s : arr) {
System.out.format("[%s]", s);
}
System.out.println();
}
}
I'm sorry I had to rewrite the code, but it's pretty much the same algorithm as yours with some corrections:
public class DiceRolls {
static void recurse(int diceNumber, int[] values, final int MAX) {
if (diceNumber == values.length) {
System.out.println(java.util.Arrays.toString(values));
} else {
for (int v = 1; v <= MAX; v++) {
values[diceNumber] = v;
recurse(diceNumber + 1, values, MAX);
}
}
}
public static void main(String[] args) {
recurse(0, new int[3], 4);
}
}
This is a standard tuplet recursive generator. If you want to add all the int[] into a List, then make sure to add(values.clone()) so they are independent int[] objects.
But what's with the extra output?
The problem is that you were dumping prematurely, before you're done throwing all the dices. In pseudocode, this is what you're doing:
if we're not done yet
trying all possibilities for this dice
dump result so far // premature dumping!
recurse for next dice
An easy fix to your code is to do the following:
if we're not done yet
trying all possibilities for this dice
recurse for next dice
else, we're done, so
dump result // timely!
So back to the Java implementation, the fix is merely moving dump(set); to an else case for the if (index < 3) statement.
Call dump() only when index == 2.
Incidentally, i and list seem unused. And the verb is "recur". :)
Here is a non-recursive alternative. Change the two constants to calculate all combinations for different dices and different numbers of dice.
package utils;
public class Dice {
private static int FACES = 3;
private static int NUMBER_OF_DICE = 3;
public static void main(String[] args) {
int start = createPair(1);
int end = createPair(FACES);
for (int i = start; i <= end; i++) {
String combination = Integer.toString(i, FACES+1);
if (combination.indexOf('0') < 0)
System.out.println(combination);
}
}
private static int createPair(int number) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < NUMBER_OF_DICE; i++) {
sb.append(number);
}
return Integer.parseInt(sb.toString(), FACES+1);
}
}

Categories