Translate Java code to PHP code (13 lines) - java

simonn helped me to code an ordered integer partition function here. He posted two functions: one function simply gives back the count of partitions, the second function gives the partitions as a list.
I've already managed to translate the first function from Java to PHP:
Java version
PHP version
Unfortunately, I can't manage to translate the second function. Can anyone help me and translate this small function for me?
public class Partitions2
{
private static void showPartitions(int sizeSet, int numPartitions)
{
showPartitions("", 0, sizeSet, numPartitions);
}
private static void showPartitions(String prefix, int start, int finish,
int numLeft)
{
if (numLeft == 0 && start == finish) {
System.out.println(prefix);
} else {
prefix += "|";
for (int i = start + 1; i <= finish; i++) {
prefix += i + ",";
showPartitions(prefix, i, finish, numLeft - 1);
}
}
}
public static void main(String[] args)
{
showPartitions(5, 3);
}
}
It would be great if the solution would be one single function instead of a class with several functions.
Thank you very much in advance! And thanks again to simonn for this great answer!

You probably don't need the main method, that just seems to be a test rig showing how to invoke the other method.
The problem mapping this code directly to PHP is that you can't overload method names in PHP. Instead you should concentrate on translating the second version of the showPartitions function. If you need a 2-argument version you can use default values for the prefix and start parameters (you'll have to change the parameter order to do this because in PHP optional parameters must come last).
Here's my (untested) attempt at translating the most important function:
function showPartitions($prefix, $start, $finish, $numLeft)
{
if ($numLeft == 0 && $start == $finish) {
echo $prefix."\n";
} else {
$prefix .= "|";
for ($i = $start + 1; $i <= $finish; $i++) {
$prefix .= $i.",";
showPartitions($prefix, $i, $finish, $numLeft - 1);
}
}
}

Related

Kotlin loop with irregular steps

I have been trying to translate a Java for expression into Kotlin which produces this sequence:
1,2,4,8,16,32,64
This is the Java code:
for(int i = 1; i < 100; i = i + i) {
System.out.printf("%d,", i);
}
The only way I have found to translate this into Kotlin is:
var i = 1
while (i < 100) {
print("$i,")
i += i
}
I have tried to use step expressions, but this does not seem to work. Is there any way to express this type of sequence more elegantly in Kotlin?
I know you can have code like this one using Kotlin + Java 9:
Stream.iterate(1, { it <= 100 }) { it!! + it }.forEach { print("$it,") }
But this relies on Java libraries and I would prefer Kotlin native libraries.
You can use the generateSequence function to create an infinite sequence, then use takeWhile to limit it at a specific value and then use forEach instead of a for-in construct to handle each iteration:
generateSequence(1) { it + it }.takeWhile { it < 100 }.forEach { print("$it,") }

Trouble with recursive method java

basically I have a brute force password guesser(I realize it's not very efficient) I have a process I want to make into a recursive method that i can pass a length integer and it will run with that amount of characters.
here is the code:
public static void generatePassword(int length)
{
// should be a recusive function learn how to do that
// 1 interval
for(int i =32;i<127;i++)// ascii table length
{
System.out.println((char)i);
}
// 2 interval
for(int z =32;z<127;z++)// ascii table length
{
for(int q =32;q<127;q++)// ascii table length
{
System.out.println((char)z+""+(char)q);
}
}
// 3 interval
for(int w =32;w<127;w++)// ascii table length
{
for(int o =32;o<127;o++)// ascii table length
{
for(int g =32;g<127;g++)// ascii table length
{
System.out.println((char)w+""+(char)o+""+(char)g);
}
}
}
}
the intervals return a string with that length example: 3rd interval will return every possible string combination with a length of 3. if anyone can help me automate this process and explain(i would like to learn rather then copy and paste) that would be great ! :)
A recursive method is a method that calls itself, it has a base-condition (also called stop condition) which prevents it from going into an infinite loop.
Lets take the first interval as an example:
for(int i = 32; i < 127; i++) { // ascii table length
System.out.println((char)i);
}
we can create a recursive method that'll do the same thing:
private void interval1(int i) {
if (i < 32 || i >= 127) return;
System.out.println((char)i);
interval1(i + 1);
}
in order to use it for our use-case, we should call this method with i=32: interval(32)
Hope this helps!
The function
Note that this will be EXTREMELY INEFFICIENT. This shouldn't ever be done in practice, since the number of String objects created is MIND-BOGGLINGLY HUGE (see bottom of answer)
public void recursivePrint(String prefix, int levels) {
if (levels <= 1) {
for (int i = 33; i < 127; ++i) {
System.out.println(prefix+(char)i);
}
} else {
for (int i = 33; i < 127; ++i) {
recursivePrint(prefix+(char)i, levels-1);
}
}
}
Then you call it with:
recursivePrint("", 5); // for printing all possible combinations of strings of length 5
The way it works
Each call to a function has it's own memory, and is stored seperately. When you first call the function, there is a String called prefix with a value of "", and an int called 'levels' which has a value of 5. Then, that function calls recursivePrint() with new values, so new memory is allocated, and the first call will wait until this new call has finished.
This new call has a String called prefix with a value of (char)34+"", and a levels with a value of 4. Note that these are completely separate instances of these variables to the first function call because remember: each function call has it's own memory (the first call is waiting for this one to finish). Now this second call makes another call to the recursivePrint() function, making more memory, and waiting until this new call finishes.
When we get to levels == 1, there is a prefix built up from previous calls, and all that remains is to use that prefix and print all the different combinations of that prefix with the last character changing.
Recursive methods are highly inefficient in general, and in this case especially.
Why you should never use it
This method is not just inefficient, though; it's infeasible for anything useful. Let's do a calculation: how many different possibilities are there for a string with 5 characters? Well there's 127-33=94 different characters you want to choose, then that means that you have 94 choices for each character. Then the total number of possibilities is 94^5 = 7.34*10^9 [that's not including the 5+ bytes to store each one] (to put that in perspective 4GB of RAM is around 4*10^9 bytes)
Here is your method implemented using recursion:
public static void generatePassword(int length, String s) {
if (length == 0) {
System.out.println(s);
return;
}
for (int i = 32; i < 127; i++) {
String tmp = s+((char) i);
generatePassword(length - 1, tmp);
}
}
All you have to do is to pass length and initial String (ie "") to it.
At if statement there is checked, if recursion should be stopped (when length of generated password is equals to expected).
At for-loop there is new character added to actual String and the method is invoked with shorter length and a new String as an argument.
Hope it helps.

Change the value of a variable each time another variable changes

I am currently making a text adventure game in Java, but I have come across a problem:
I need the value of a String variable to change each time the value of a particular int variable changes.
I want the program to perform this task (then continue where it left off) each time the value of an int variable changes:
if (enemyposition == 1) {
enemyp = "in front of you";
}
else if (enemyposition == 2) {
enemyp = "behind you";
}
else if (enemyposition == 3) {
enemyp = "to your left";
}
else if (enemyposition == 4) {
enemyp = "to your right";
}
else {
enemyp = "WOAH";
}
Thanks! :D
You could make the code much shorter using an array.
String[] message = {"WOAH", // 0
"in front of you", // 1
"behind you", // 2
"to your left", // 3
"to your right"}; // 4
enemyp = (enemyposition > 0 && enemyposition < 5) ? message[enemyposition] :
message[0];
The question you're asking sounds like it might be answerable by creating a class to hold the enemyposition integer. Add a "setter" method to your class to set the integer. You can write your setter method so that when the integer is set, it also sets up a string. Then write a "getter" method to retrieve the string. That's one common way of making sure two variables change together.
public class EnemyPosition {
private int enemyposition;
private String enemyp;
public void setPosition(int n) {
enemyposition = n;
enemyp = [adapt your code to set this based on the position]
}
public String getEnemyp() {
return enemyp;
}
}
I'm sure there are a lot of details missing, but you get the idea. Then instead of int enemyposition in the rest of your code, use EnemyPosition enemyposition = new EnemyPosition(), and use the setPosition method instead of assigning to it.
That's not the only solution (an array or Map that maps integers to strings may be good enough), but it's one OOP way to do things.

How to use RAW folder for multiple audio files

I have the following function:
strNameValue = prefs.getString("NamePosition", "");
inNameValueConversion = Integer.parseInt(strNameValue);
if (inNameValueConversion == 0) {
DisplayInformation(inNameValueConversion, R.raw.audio01);
}
if (inNameValueConversion == 1) {
DisplayInformation(inNameValueConversion, R.raw.audio02);
}
if (inNameValueConversion == 2) {
DisplayInformation(inNameValueConversion, R.raw.audio03);
}
if (inNameValueConversion == 3) {
DisplayInformation(inNameValueConversion, R.raw.audio04);
}
Because all the audio file starts with audio and only the number changes at the end I wanted to create a function which allows me to use less code like this:
public void DisplayInformation(int inNum, final int inSoundResource) {
if (inSoundResource < 2) {
strIConv = String.valueOf("0" + inSoundResource);
inConv = Integer.parseInt(strIConv);
int k = R.raw.audio+"inConv";
}
}
I get the following error: audio cannot be resolved or is not a field
How do I edit the above code so I can just use one function instead of using so many IF statement, since it will be 90+ times.
You can use getIdentifier(), so your code would look like this:
public void displayInformation(int inNum) {
String id = "audio";
// for inNum < 9, we need to add 0, so for example when you pass 0
// id will be 01, not 1
if (inNum < 9) then id += "0";
//based on your code, 0 - audio01, 1 - audio02 etc, so add 1
id += (inNum + 1);
// call getIdentifier with string containing resource name, which are in your raw folder
// and in your package
int k = getResources().getIdentifier(id, "raw", "your.package.name.here");
//k now contains an id of your resource, so do whatever you want with it
}
and your code can then be reduced to this:
strNameValue = prefs.getString("NamePosition", "");
inNameValueConversion = Integer.parseInt(strNameValue);
displayInformation(inNameValueConversion);
Remember to use your package name in the call to getIdentifier().
Docs are here: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String, java.lang.String, java.lang.String)
You could try to do it like it is mentioned in this post: https://stackoverflow.com/a/5626631/3178834
In your case, you have to create an array for all audio files as resources xml and then load it with res.getXml into java. Just follow the link from above.
Building R values that way won't work -- you'll need to use reflection instead.
For example:
import java.lang.reflect.Field;
/* ... */
int id = R.id.class.getField("video" + i).getInt(0);

Why do I get this compile error in Java?

I get the following error:
quicksort(int[],int,int)cannot be applied to(int[])
When I compile this:
import java.util.*;
public class Sort {
public static void main(String[] args){
Random rand = new Random();
int[] tab = new int[10];
for(int i = 0; i < tab.length; i++) {
tab[i] = rand.nextInt(100);
System.out.println("Before: ");
show(tab);
quicksort (tab);
System.out.println("After: ");
show(tab);
}
}
static void quicksort(int tab[], int x, int y) {
int i,j,v,temp;
i=x;
j=y;
v=tab[(x+y) / 2];
do {
while (tab[i]<v)
i++;
while (v<tab[j])
j--;
if (i<=j) {
temp=tab[i];
tab[i]=tab[j];
tab[j]=temp;
i++;
j--;
}
}
while (i<=j);
if (x<j)
quicksort(tab,x,j);
if (i<y)
quicksort(tab,i,y);
}
static void show (int tab[]) {
for (int i = 0; i <tab.length; i++) {
System.out.println(tab[i]);
}
}
}
What am I doing wrong?
Just after the line to print out "before", you have:
quicksort (tab);
The function you designed needs three arguments. You can either add the extra arguments:
quicksort (tab, 0, tab.length - 1)
Or add a new function such as:
public quicksort(int[]) {
quicksort(tab, 0, tab.length - 1);
}
the function "quicksort" that you define asks for 3 parameters, but you are only providing one.
Because your quicksort function has 3 parameters, but your call gives only one.
Edit: second :(
your code should call
quicksort (tab,0,10);
In your outer calll, so you can sort the list.
Without knowing what you're writing code in, I strongly recommend using an IDE if you haven't adopted one already. Particularly Eclipse for Java.
Eclipse would underline the offending line of code and make some suggestions to you, (in addition to offering code completion). A text editor, like JEdit does not.
Note: I've been told IntelliJ is good, but you can't beat Eclipse's price (free).
BTW: You could just use Arrays.sort() which is a built in function. You wouldn't write a function like this in real life. (only as homework)

Categories