Converting C++ code to JAVA - java

#include <iostream>
using namespace std;
int fun(int *k);
int main() {
int i = 10, j = 10, sum1,sum2;
sum1 = (i / 2) + fun(&i);
sum2 = fun(&j) + (j / 2);
cout<< sum1<< " "<<sum2<<endl;
}
int fun(int *k) {
*k += 4;
return 3 * (*k) - 1;
}
I have to convert my code to Java Code I already converted but i couldn't find my mistake i cannot point variables to each other..
public class System{
public static void main(String[] args) {
int i = 10;
int j = 10;
int sum1 = (i / 2) + fun(k.value=i);
int sum2 = fun(k.value=j) + (j / 2);
System.out.println("%d%d",sum1,sum2 );
}
public static int fun(int k) {
intobj k;
int k= new k();
k.value += 4;
return 3 * (k.value) - 1;
}
}
This is my java code when i look at the int sum1 = (i / 2) + fun(k.value=i);
int sum2 = fun(k.value=j) + (j / 2); part isn't true about point to true values. How can i solve that pointers problem. Thank you.

The problem is that you're using ints instead of intobjs where you want to pass things around by reference (& in c++).
In your main function, you should try declaring i and j as intobjs and your parameter for fun, k should also be an intobj.
Code:
public class System{
public static void main(String[] args) {
intobj i = new intobj();
i.value = 10;
intobj j = new intobj();
j.value = 10;
int sum1 = (i.value / 2) + fun(i);
int sum2 = fun(j) + (j.value / 2);
System.out.println("%d%d",sum1,sum2 );
}
public static int fun(intobj k) {
k.value += 4;
return 3 * (k.value) - 1;
}
}

Related

How to designate a main class in Java

I am adapting a program which compiles OK; but when I try to run it I get an error window that says "no main classes found". I searched on your site for that type of problem (for NetBeans)and then tried a R click on my project in the Project window. Lagrange/properties/run and the class shown was the one in my program. I clicked run in that window and got the same error message.
The program is pasted below:
package lagrange;
class MyMath {
double xi[] = { 0, 0.5, 1, 1.5, 2 };
double fi[] = { 1, 0.938470, 0.765198, 0.511828, 0.223891 };
double x = 0.9;
double f = aitken(x, xi, fi);
// Method to carry out the Aitken recursions.
public double aitken(double x, double xi[], double fi[]) {
int n = xi.length - 1;
double ft[] = (double[]) fi.clone();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n - i; ++j) {
ft[j] = (x - xi[j]) / (xi[i + j + 1] - xi[j]) * ft[j + 1]
+ (x - xi[i + j + 1]) / (xi[j] - xi[i + j + 1]) * ft[j];
}
}
return ft[0];
}
}
public class Lagrange {
public void main(String[] args) {
// TODO code application logic here
System.out.println("Interpolated value: " + f);
}
}
It is public static void main - main method has to be static. And in your current code, you are declaring the main method in an inner class which is not static. This is not allowed and it will fail as
static methods can only be declared in a static or top level type.
One solution that can work for you is provided below with these changes -
main method shifted to MyMath class.
main method being static does not have access to non-static members and hence an instance of MyMath is created and used to print the result.
package lagrange;
class MyMath {
double xi[] = { 0, 0.5, 1, 1.5, 2 };
double fi[] = { 1, 0.938470, 0.765198, 0.511828, 0.223891 };
double x = 0.9;
double f = aitken(x, xi, fi);
// Method to carry out the Aitken recursions.
public double aitken(double x, double xi[], double fi[]) {
int n = xi.length - 1;
double ft[] = (double[]) fi.clone();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n - i; ++j) {
ft[j] = (x - xi[j]) / (xi[i + j + 1] - xi[j]) * ft[j + 1]
+ (x - xi[i + j + 1]) / (xi[j] - xi[i + j + 1]) * ft[j];
}
}
return ft[0];
}
public static void main(String[] args) {
System.out.println("Interpolated value: " + new MyMath().f);
}
}

Generating vampire numbers in free range

I am writing program which generates Vampire numbers https://en.wikipedia.org/wiki/Vampire_number.
I have main function with numberOfDigits argument, which must be even. If numberOfDigits is equal 4, then we are searching Vampire Numbers in range 1000 to 9999 - four digits. If numberOfDigits is equal 6, then we are searching Vampire Numbers from 100000 to 999999 - which is six digits.
In following file, when I want to search Vampire numbers in range of 10 digits, Java heap space is screaming. Note that I have default settings for memory. But for, numberOfDigits == 4, 6 or 8, code is working correctly. (compared output to https://oeis.org/A014575/b014575.txt , https://oeis.org/A014575 ). So I want to ask,
What I can do to optimize this code? I have thought about using String with digits inside, instead of long/BigInteger. I want to "omit" that heap problem. Saving big numbers to file would be too slow, am I right?
My mate wrote (bigNum.cpp) http://pastebin.com/0HHdE848 - class in C++, to operate on big numbers. Maybe with help from community I could implement that in my a.java? More important - would it be useful for my problem?
edit: My goal is to generate free range of Vampire Numbers, like 4,6,8 - a.java it can do it, even more (if I can bypass heap space problem). And that is when my questions to help comes.
a.java (permutation code from johk95, https://stackoverflow.com/a/20906510 )
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* #author re
*/
public class a {
/**
*
* #param numberOfDigits {int}
* #return ArrayList of Integer
*/
public ArrayList<Integer> vdf(int numberOfDigits) {
if ((numberOfDigits % 2) == 1) {
//or throw Exception of unrecognised format/variable?
System.out.println("cant operate on odd argument");
return new ArrayList<>();
}
long maxRange = 9;
for (int i = 1; i < numberOfDigits; i++) {
maxRange *= 10;
maxRange += 9;
}//numberOfDigits==4 then maxRange==9999, nOD==5 then maxRange==99999,..
long minRange = 1;
for (int i = 1; i < numberOfDigits; i++) {
minRange *= 10;
}//nOD==4 then minRange==1000, nOD==5 then minRange==10000, ..
ArrayList<Integer> ret = new ArrayList<>();
for (long i = minRange; i < maxRange; i++) {
long a = i;
long[] b = new long[numberOfDigits];
for (int j = numberOfDigits-1; j >= 0 ; j--) {
long c = a % 10;
a = a / 10;
b[j] = c;
}
int x = 0;
int y = 0;
ArrayList<long[]> list = permutations(b);
b = null; //dont need now
for(long[] s : list) {
for (int j = 0; j < numberOfDigits/2; j++) {
x += s[(numberOfDigits/2)-j-1] * Math.pow(10, j);
y += s[numberOfDigits-j-1] * Math.pow(10, j);
}
StringBuilder builder = new StringBuilder();
for (long t : s) {
builder.append(t);
}
String v = builder.toString();
if ((v.charAt((v.length()/2)-1) != '0'||
v.charAt(v.length()-1) != '0') &&
x * y == i) {
ret.add(x);
ret.add(y);
System.out.println(x*y+" "+x+" "+y);
break;
}
x = y = 0;
}
}
System.out.printf("%d vampire numbers found\n", ret.size()/2);
return ret;
}
/**
*
*#return vdf(4)
*/
public ArrayList<Integer> vdf() {
return vdf(4);//without trailing zeros
}
/* permutation code copied from
* johk95
* https://stackoverflow.com/a/20906510
*/
private static ArrayList<long[]> permutations(long[] lol) {
ArrayList<long[]> ret = new ArrayList<>();
permutation(lol, 0, ret);
return ret;
}
private static void permutation(long[] arr, int pos, ArrayList<long[]> list){
if(arr.length - pos == 1)
list.add(arr.clone());
else
for(int i = pos; i < arr.length; i++){
swap(arr, pos, i);
permutation(arr, pos+1, list);
swap(arr, pos, i);
}
}
private static void swap(long[] arr, int pos1, int pos2){
long h = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = h;
}
public static void main(String[] args) {
a a = new a();
try{
a.vdf(10); //TRY IT WITH 4, 6 or 8. <<<<
}catch (java.lang.OutOfMemoryError e){
System.err.println(e.getMessage());
}
}
}
EDIT: http://ideone.com/3rHhep - working code above with numberOfDigits == 4.
package testing;
import java.util.Arrays;
public class Testing
{
final static int START = 11, END = 1000;
public static void main(String[] args)
{
char[] kChar, checkChar;
String kStr, checkStr;
int k;
for(int i=START; i<END; i++) {
for(int i1=i; i1<100; i1++) {
k = i * i1;
kStr = Integer.toString(k);
checkStr = Integer.toString(i) + Integer.toString(i1);
//if(kStr.length() != 4) break;
kChar = kStr.toCharArray();
checkChar = checkStr.toCharArray();
Arrays.sort(kChar);
Arrays.sort(checkChar);
if(Arrays.equals(kChar, checkChar)) {
System.out.println(i + " * " + i1 + " = " + k);
}
}
}
}
}
This will generate vampire numbers, just modify the start and end integers.

Create several integers with a formula?

Is there a way to do what the title suggests? What I'm trying to do is create a table of experience values required to level up like so:
int level1 = 50;
int level2 = level1 + (level1 * 0.1);
int level3 = level2 + (level2 * 0.1);
But I want to get to around 100 levels... Is there a way to quickly define x number of usable int values?
Assuming you're continuing that formula...
int[] array = new int[100];
array[0] = 50;
for (int i = 1; i < 100; i++) {
array[i] = (int) (array[i - 1] * 1.1);
}
Use this approach:
public class Level
{
public Level()
{
int[] levels = new int[100]; // 100 Levels
initializeLevels(levels);
printLevels(levels);
}
private void initializeLevels(int[] levels)
{
levels[0] = 50;
for (int i = 1; i < 100; i++)
{
levels[i] = (int) (levels[i - 1] * 1.1f);
}
}
private void printLevels(int[] levels)
{
for (int i = 0; i < 100; i++)
{
System.out.println("Level " + (i + 1) + " = " + levels[i]);
}
}
public static void main(String[] args)
{
new Level();
}
}

JAVA: Is there a shorter way of printing out Fibonacci numbers?

Basically, I would like to know if there is a shorter way of printing out the Fibonacci numbers from 0 - 100.
What I have done is probably very basic, but here is the code:
public static void main(String[] args) {
int number[] = new int[100];
number[0] = 0;
number[1] = 1;
int sum1 = number[0] + number[0];
int sum2 = sum1 + number[1];
int sum3 = sum1 + sum2;
int sum4 = sum2 + sum3;
int sum5 = sum3 + sum4;
int sum6 = sum4 + sum5;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
System.out.println(sum4);
System.out.println(sum5);
System.out.println(sum6);
}
And I would be doing this up until 100. But I'm sure there is a quicker way of doing this. How?
You can use a loop. This example uses BigInteger as the number quickly become too large for long.
BigInteger a = BigInteger.ZERO, b = BigInteger.ONE;
System.out.println(1);
for (int i = 0; i < 100000; i++) {
BigInteger c = a.add(b);
System.out.println(c);
a = b;
b = c;
}
prints after a couple of seconds finally
420269270299515438 ... many, many digits deleted ... 9669707537501
Note: you don't need to memorize all the previous values, just the last two.
Standard way to do this is by recursion:
Have a look at this simple snippet, which returns the fibonacci number at position a:
public static long fib(int a){
if (a==1||a==2) return 1;
else return fib(a-1)+fib(a-2);
}
google search ftw!... wasn't even a minute searching
int[] fibonacci = new int[25+1];
fibonacci[1] = 1;
fibonacci[2] = 1;
for ( int i = 3; i < fibonacci.length; i++ )
{
fibonacci[i] = fibonacci[i-2] + fibonacci[i-1];
}
Print number < 100 with n=11
public int getFib(int n){
if(n==0) return 0;
else if(n==1) return 1;
else{
int temp=getFib(n-1)+getFib(n-2);
return temp;
}
}
Just in case you don't want to use the recursive way..
Here is the iterative...
public class Fib2 {
public static int fib(int n, int a, int b)
{
if (n==0)
{
System.out.print("1x +");
return a;
}
else
{
System.out.print("2x +");
return fib(n-1,b,a+b);
}
}
public static void main(String arg[])
{
System.out.println(fib(0,1,1));
}
}
Well, 100 isn't one of the Fibonacci numbers, however if we include 144, then this is a nice succinct example:
class F
{
public static void main( final String[] a )
{
int a = 1, b = 1;
for ( ; b < 145; a = b + (b = a) )
System.out.println( b );
}
}
If you have to do this without arrays here is the way to do it. Just change 20 to 100. This is the way I had to do it for an assignment and it is simple to understand for those still learning.
public static void main(String[] args)
{
int number1 = 1;
int number2 = 1;
int count;
int fib;
System.out.print(number1 + " " + number2 + " ");
for(count = 3; count <= 20; count++)
{
fib = number1 + number2;
number1 = number2;
number2 = fib;
System.out.print(fib + " ");
}
}

Rabin-Karp Hashcode is too big

How to deal with a big hashcode value in rolling hash Rabin-Karp algorithm ? I use modular arithmetic to avoid negative number, however there is a problem when the hashcode exceeds my modulo number (N = 83559671). I set my base number to be prime (the number to calculate hashcode) as well as the modulo number (really big), but it doesn't work with long string. Can anyone see the problem?
Here is my code.
public static void main(String [] args){
int P = 13; // base
long M = 83559671;
long iHash = 0;
String word = "abcbadccaaaabbbb";
int WINDOW = 9;
for(int i = 0; i < WINDOW; i++){
iHash = int_mod(int_mod(iHash*P, M) + word[i], M);
}
for(int i = WINDOW; i < word.length; i++){
iHash = int_mod(iHash - word[i-WINDOW] * get_pow(P, WINDOW-1, M), M);
iHash = int_mod(iHash * P, M);
iHash = int_mod(iHash + word[i], M);
}
}
public static long get_pow(int p, int t, long M){
long a = 1;
for(int i = 0 ; i < t; i++){
a = int_mod(a * p, M);
}
return a;
}
public static long int_mod(long a, long b){
return (a % b+ b) % b;
}
The problem is when I have any string's length longer than 8 then the hashcode of the string exceeds the modulo number 83559671, and that leads to a wrong answer when I make a comparison. Any shorter strings work properly.
You don't need to do the modulus at all. Here's a demo:
public class Foo {
private static int hash(String s) {
int hash = 0;
for (int i = 0; i < s.length(); i++) {
hash *= 31;
hash += s.charAt(i);
}
return hash;
}
public static void main(String[] args) {
String s1 = "abcdefghij";
String s2 = s1.substring(1) + "k";
int pow = 1;
for (int i = 0; i < s1.length(); i++) {
pow *= 31;
}
System.out.printf("hash(%s) = %d%n", s1, hash(s1));
System.out.printf("hash(%s) = %d%n31 * hash(%s) - (31^%d * %s) + %s = %s%n",
s2,
hash(s2),
s1,
s1.length(),
s1.charAt(0),
s2.charAt(s2.length() - 1),
31 * hash(s1) - (pow * s1.charAt(0)) + s2.charAt(s2.length() - 1));
}
}
This (correctly) prints out:
hash(abcdefghij) = -634317659
hash(bcdefghijk) = 21611845
31 * hash(abcdefghij) - (31^10 * a) + k = 21611845
Why don't you treat your string as a polynomial? Suppose you have a string S of length n. Now take a look at the following function: F(x) = S[0]*x^(n-1) + S[1]*x^(n-2) + ... + S[i]*x^(n-i-1) + ... + S[n - 2]*x + S[n-1]. What happens if you try to compute F(P), where P is a base from your code snippet? Well, you'd get exactly the Rabin-Karp hash of string S. But since F(x) is a polynomial, we can use Horner's rule to compute the F(P). The resulting value might be very big, hence we use modular arithmetic:
static final long M = 83559671;
static final int Base = 13;
static long hash(String s, int from, int to) {
int iHash = 0;
for(int i = from; i < to; i++) {
iHash *= Base;
iHash += s.charAt(i);
iHash %= M;
}
return iHash;
}
You can use this function to obtain the hash of a string to be found in a text. And for initial window in the text. Then you can shift window and recalculate hash:
static void find(String pattern, String text) {
if(text.length() < pattern.length()) return;
int len = pattern.length();
long ph = hash(pattern, 0, len);
long h = hash(text, 0, len);
long basePower = mpow(Base, len);
if(h == ph) System.out.println("match at 0");
for(int i = len; i < text.length(); i++) {
h *= Base;
h += text.charAt(i);
h -= basePower * text.charAt(i - len);
h = mod(h);
if(h == ph) System.out.println("match at " + (i - len + 1));
}
}
static long mod(long a) {
a %= M;
if(a < 0) {
a += M;
}
return a;
}
static long mpow(long x, int k) {
long result = 1;
for(; k > 0; k >>= 1) {
if(k % 2 == 1) {
result = mod(result * x);
}
x = mod(x * x);
}
return result;
}
public static void main(String[] args) {
find("abracadabra", "abracadabracadabra");
}
For more information on this approach I recommend to refer to CLRS.

Categories

Resources