I´m trying to implement the EEA. I found this pattern which I use also.
extended_euclid(a,b)
1 if b = 0
2 than return (a,1,0)
3 (d',s',t') <-- extended_euclid(b, a mod b)
4 (d,s,t) <--- (d',t',s' - (a div b)t')
5 return (d,s,t)
And my code looks like this:
public static Triple extendedEuclid(BigInteger a, BigInteger b) {
if (b.equals(new BigInteger("0"))) {
return new Triple(a, new BigInteger("1"), new BigInteger("0"));
} else {
Triple i = extendedEuclid(b, a.mod(b));
return new Triple(i.getA(), i.getB(), (i.getC().divide(i.getB()).multiply(i.getC())));
}
}
I´m not quite sure if my code is correct. I looked up many pages like twenty or so but I still don´t get it. I´m mentally stuck.
Thanks.
It looks like you got the operations in the final return out of order. You also implemented the third value of Triple incorrectly. Here is my implementation. (I also used BigInteger's helper constants/methods + renamed variables for clarity.)
public class ExtendedEuclidAlgorithm {
public static void main(final String[] args) {
System.out.println("eea(240, 46) = " + apply(BigInteger.valueOf(240), BigInteger.valueOf(46)));
System.out.println("eea(65, 40) = " + apply(BigInteger.valueOf(65), BigInteger.valueOf(40)));
System.out.println("eea(1239, 735) = " + apply(BigInteger.valueOf(1239), BigInteger.valueOf(735)));
}
/*
* extended_euclid(d,s)
if s = 0
than return (d,1,0)
(d',s',t') <-- extended_euclid(s, d mod s)
return (d',t',s' - (d div s)t')
*/
public static Triple apply(final BigInteger a, final BigInteger b) {
if (b.equals(BigInteger.ZERO)) {
return new Triple(a, BigInteger.ONE, BigInteger.ZERO);
} else {
final Triple extension = apply(b, a.mod(b));
return new Triple(extension.d, extension.t, extension.s.subtract(a.divide(b).multiply(extension.t)));
}
}
private static class Triple {
public final BigInteger d;
public final BigInteger s;
public final BigInteger t;
private Triple(final BigInteger d, final BigInteger s, final BigInteger t) {
this.d = d;
this.s = s;
this.t = t;
}
#Override
public String toString() {
return "Triple{" +
"d=" + d +
", s=" + s +
", t=" + t +
'}';
}
}
}
eea(240, 46) = Triple{d=2, s=-9, t=47}
eea(65, 40) = Triple{d=5, s=-3, t=5}
eea(1239, 735) = Triple{d=21, s=-16, t=27}
I validated the response values from Wikipedia and here.
Related
Here is my code to swap two numbers using wrapper class, i am aware of the fact that java only has pass by value ,so we cannot use use something like a pointer to pass the address of variables.For this i created objects for wrapper class Integer a,b.
But this code doesn't work , the comments in the code section explain my approach , Can someone please tell me where did i go wrong.
class swp{
public static void main(String[] args) {
Integer x = new Integer(5); //x --> obj with 5 int value
Integer y = new Integer (6); //y --> obj with 6 int value
System.out.println("x = "+ x+ " " +"y = " + y);
swap(x,y);
System.out.println("x = " + x+ " " +"y = " + y);
}
//the values in x and y are copied in a and b
static void swap(Integer a,Integer b){ //a ,x--> obj with 5 int value .b,y --> obj with 6 int value
int temp = a.intValue(); // temp contains 5
a = b.intValue() ; // value at the obj ref. by a has changed to 6
b = temp; //value at the obj ref. by a has changed to 5
System.out.println("in func : "+"a = " + a+ " " +"b = " + b);
}
}
output
a = 5 b = 6
in func : a = 6 b = 5
a = 5 b = 6
I know i could do this using the following approach
void swap(class_name obj1,class_name obj2){
int temp = obj1.x;
obj1.x =obj2.x;
obj2.x = temp;
}
But i want to know what exactly is wrong with my approach.
Not using Integer directly, but you can using an Integer (or int) array. Like,
public static void main(String[] args) {
int[] arr = { 5, 6 };
System.out.println("a = " + arr[0] + " " + "b = " + arr[1]);
swap(arr);
System.out.println("a = " + arr[0] + " " + "b = " + arr[1]);
}
private static void swap(int[] arr) {
int t = arr[0];
arr[0] = arr[1];
arr[1] = t;
}
Which does output
a = 5 b = 6
a = 6 b = 5
Or create a POJO like,
class MyPair {
private int a;
private int b;
public MyPair(int a, int b) {
this.a = a;
this.b = b;
}
public String toString() {
return String.format("a = %d, b = %d", a, b);
}
public void swap() {
int t = a;
a = b;
b = t;
}
}
Then you can do
public static void main(String[] args) {
MyPair p = new MyPair(5, 6);
System.out.println(p);
p.swap();
System.out.println(p);
}
For the same result.
I was wondering if you can create a custom base with your own symbols instead of the one Java applies to you with Integer.parseInt (0-9 and A-P.)
I was thinking of something like this:
public class Base {
private String symbols;
public Base(String symbols) {
this.symbols = symbols;
}
// for example: new Base("0123456789"); would represent base 10
public static String convertBases(Base from, Base to, String toConvert) {
// Takes toConvert which is encoded in base "from" and converts it to base "to"
}
}
I am not sure how to implement this. Does anyone have the code for this?
To do this, you need to first parse the input text in the from base, then format the value in the to base, exactly like you'd need to do if using standard base "alphabet".
public static String convertBases(int fromRadix, int toRadix, String text) {
int value = Integer.parseInt(text, fromRadix);
return Integer.toString(value, toRadix);
}
So, first you implement parse and toString, then implementing convertTo is easy:
public class Base {
private final String symbols;
private final BigInteger radix;
private final Map<Character, Integer> symbolIndex;
public Base(String symbols) {
if (symbols.length() <= 1)
throw new IllegalArgumentException("Must provide at least 2 symbols: length=" + symbols.length());
this.symbols = symbols;
this.radix = BigInteger.valueOf(symbols.length());
this.symbolIndex = new HashMap<>(symbols.length() * 4 / 3 + 1);
for (int i = 0; i < symbols.length(); i++) {
Integer prevIndex = this.symbolIndex.putIfAbsent(symbols.charAt(i), i);
if (prevIndex != null)
throw new IllegalArgumentException("Duplicate symbol at index " + prevIndex +
" and " + i + ": " + symbols.charAt(i));
}
}
public BigInteger parse(String text) {
BigInteger value = BigInteger.ZERO;
for (int i = 0; i < text.length(); i++) {
Integer index = this.symbolIndex.get(text.charAt(i));
if (index == null)
throw new IllegalArgumentException("Not a valid number: " + text);
value = value.multiply(this.radix).add(BigInteger.valueOf(index));
}
return value;
}
public String toString(BigInteger value) {
if (value.signum() < 0)
throw new IllegalArgumentException("Negative value not allowed: " + value);
if (value.signum() == 0)
return this.symbols.substring(0, 1);
StringBuilder buf = new StringBuilder();
for (BigInteger v = value; v.signum() != 0; v = v.divide(this.radix))
buf.append(this.symbols.charAt(v.mod(this.radix).intValue()));
return buf.reverse().toString();
}
public String convertTo(Base newBase, String text) {
return newBase.toString(parse(text));
}
}
Test
Base base3 = new Base("012");
Base base6alpha = new Base("ABCDEF");
System.out.println(base3.convertTo(base6alpha, "0")); // 0 -> A
System.out.println(base3.convertTo(base6alpha, "2")); // 2 -> C
System.out.println(base3.convertTo(base6alpha, "10")); // 3 -> D
System.out.println(base3.convertTo(base6alpha, "200")); // 18 -> DA
Output
A
C
D
DA
Test 2
Base obscure = new Base("^JsdloYF9%");
Base base64 = new Base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
BigInteger value = new BigInteger("123456789012345678901234567890"); // Too large for int and long
String obscureValue = obscure.toString(value);
String base64Value = base64.toString(value);
System.out.println(obscureValue);
System.out.println(base64Value);
System.out.println(base64.convertTo(obscure, base64Value));
System.out.println(obscure.convertTo(base64, obscureValue));
Output
JsdloYF9%^JsdloYF9%^JsdloYF9%^
BjukP9sNz4O5OPwrS
JsdloYF9%^JsdloYF9%^JsdloYF9%^
BjukP9sNz4O5OPwrS
Let's start with a value type. It holds a string representation and a Base object. (i.e., it has a string representation and a something like a decoder). Why? because we don't want to pass around Strings which we need to look at and "guess" what base they are.
public class CustomNumber {
private final String stringRepresentation;
private final Base base;
public CustomNumber(String stringRepresentation, Base base) {
super();
this.stringRepresentation = stringRepresentation;
this.base = base;
}
public long decimalValue() {
return base.toDecimal(stringRepresentation);
}
public CustomNumber toBase(Base newBase) {
long decimalValue = this.decimalValue();
String stringRep = newBase.fromDecimal(decimalValue);
return new CustomNumber(stringRep, newBase);
}
}
Then we need to define an interface which is broad enough to handle any regular or custom-symbol base. We will later build concrete implementations on top.
public interface Base {
public long toDecimal(String stringRepresentation);
public String fromDecimal(long decimalValue);
}
We are all set. Lets do an example implementation to support the standard decimal number format before going to custom string symbols:
public class StandardBaseLong implements Base{
public long toDecimal(String stringRepresentation) {
return Long.parseLong(stringRepresentation);
}
public String fromDecimal(long decimalValue) {
return Long.toString(decimalValue);
}
}
Now finally, coming to the custom string base:
public class CustomBase implements Base{
private String digits;
public CustomBase(String digits) {
this.digits = digits;
}
public long toDecimal(String stringRepresentation) {
//Write logic to interpret that string as your base
return 0L;
}
public String fromDecimal(long decimalValue) {
//Write logic to generate string output in your base format
return null;
}
}
Now you have a framework to work with various custom and standard bases.
Of course, there could be more customisations and improved features (more convenience constructors, hashCode and equals implementations and arithmetic). But, they are beyond the scope of this answer.
I have two BigInteger variables "e" and "n" and i want to concatenate them together as "en".. how do i do this?
Do i need to convert to a string first then back to BigInteger?
My code sets the variables from another class.
public class Key {
public BigInteger getN() {
return n;
}
public void setN(BigInteger n) {
this.n = n;
}
public BigInteger getE() {
return e;
}
public void setE(BigInteger e) {
this.e = e;
}
public BigInteger getD() {
return d;
}
public void setD(BigInteger d) {
this.d = d;
}
public BigInteger e;
public BigInteger n;
public BigInteger d;
public BigInteger publickeyconcat() {
BigInteger myval = (e + n);
return myval;
}
public BigInteger privatekeyconcat(){
BigInteger myval2 = e;
return myval2;
}
}
UPDATE
Have tried the method given in the comments but when converting to use e and n rather than number1 and number2 it doesn't concat them together.
public BigInteger publickeyconcat() {
BigInteger ten=new BigInteger("10");
BigInteger myval=(e.multiply(ten.pow((int)(Math.floor(Math.log10(e.doubleValue()) + 1)))).add(n));
return myval;
}
Because of the effort shown, the power of 10 for multiplying the first number can be gotten as follows:
public static BigInteger concat(BigInteger x, BigInteger y)
{
int ndigits = y.bitLength() * 3 / 10; // Guessed number of digits using 2^10 ≈ 10^3.
BigInteger pow10 = BigInteger.TEN.pow(ndigits);
while (pow10.compareTo(y) > 0) {
pow10 = pow10.divide(BigInteger.TEN);
}
while (pow10.compareTo(y) <= 0) {
pow10 = pow10.multiply(BigInteger.TEN);
}
// Cheating: int ndigits = y.toString().length();
return x.multiply(pow10).add(y);
}
Since other answers have already focused on String Concatenation, let me give you another answer not involving String Concatenation. You can take the number of digits of first number, multiply first number with 10^(no of digits) and add the second number. A crude example would be as follows,
BigInteger ten=new BigInteger("10");
BigInteger number=new BigInteger("1234");
BigInteger number2=new BigInteger("5678");
BigInteger newBigInt=(number.multiply(ten.pow((int)(Math.floor(Math.log10(number.doubleValue()) + 1)))).add(number2));
System.out.println(newBigInt); //would print 12345678
If you just want to concatenate two BigInteger variables, you can do it this way:
public BigInteger publickeyconcat(BigInteger e, BigInteger n) {
String a = String.valueOf(e);
String b = String.valueOf(n);
String val = a + b;
BigInteger myval = new BigInteger(val);
return myval;
}
But if you want to do operations with the numbers, you can do that directly. There is no need for a conversion.
i did this in the end by converting to a string and using string buffer due to the size of BigInteger. I then left as String as i wanted to write it to a file but i could have reverted to BigInteger using the content variable.
public String publickeyconcat() {
String str = String.valueOf(e);
StringBuffer tmp = new StringBuffer(str);
tmp.append(n);
str = tmp.toString();
BigInteger content = new BigInteger(str);
return str;
}
I have an ArrayList of Objects that I'd like to sort by their value. Basically I have 9 different mathematical functions (i.e., f1(n) = log n, f2(n) = n, f3(n) = n log n, etc). I plugged the value of 1 into all 9 functions and I placed their results in an ArrayList of Objects with their label attached to them as shown in the code below. I'd like to sort the entire list of results.
ArrayList<Object>val1 = new ArrayList<Object>();
val1.add("f\u2081(1) = " + log(funcValues[0]));
val1.add("f\u2082(1) = " + funcValues[0]);
val1.add("f\u2083(1) = " + exponent(funcValues[0]));
val1.add("f\u2084(1) = " + f4(funcValues[0]));
val1.add("f\u2085(1) = " + squared(funcValues[0]));
val1.add("f\u2086(1) = " + cubed(funcValues[0]));
val1.add("f\u2087(1) = " + twoN(funcValues[0]));
val1.add("f\u2088(1) = " + factorial(funcValues[0]));
val1.add("f\u2089(1) = " + f9(funcValues[0]));
Basically, wherever you see log, funcValues, exponent, f4, squared, etc those are all functions that compute the answers to the mathematical functions. The output of this ArrayList is:
f₁(1) = 0.0 f₂(1) = 1 f₃(1) = 1.0 f₄(1) = 0.0 f₅(1) =
1 f₆(1) = 1.0 f₇(1) = 2.0 f₈(1) = 1 f₉(1) = 0.0
I'd like to sort only the numbers. I was trying to do it this way:
class ValuesSorted implements Comparator<Object> {
#Override
public int compare(Object v1, Object v2) {
if ()
return 0;
}
}
I am stuck on the if statement because I can't do something like if (v1.getValue > v2.getValue) because I am using 9 different function calls to pull each of those values.
Simply try
Collections.sort(testList);
Collections.reverse(testList);
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
You are trying to track two things, the value and a label. When you are tracking two associated things, use a Map. In this case, a sorted map, i.e. a TreeMap.
TreeMap map = new TreeMap<Double, String>();
// for each function, map.put(value, label), e.g.
map.put(log(funcValues[0]), "f\u2081(1)");
...
map.put(f4(funcValues[0]),"f\u2084(1)");
...
map.put(f9(funcValues[0]), "f\u2089(1)");
And result will be sorted by numerical value. map.values() will have the labels in sorted order.
class Pair<X,Y>{
private X first;
private Y second;
Pair(X first,Y second){
this.first=first;
this.second=second;
}
public X getX() {
return first;
}
public void setX(X first) {
this.first = first;
}
public Y getY() {
return second;
}
public void setY(Y second) {
this.second = second;
}
public Comparator<Pair<X, Y>> getComparator(){
return new Comparator<Pair<X, Y>>() {
#Override
public int compare(Pair<X, Y> o1, Pair<X, Y> o2) {
double a=(Double) o1.getY();
double b=(Double) o2.getY();
if(a==b){
return 0;
}else if(a>b){
return 1;
}else{
return -1;
}
}
};
}
}
public class Main{
public static void main(String[] arg){
List<Pair<String,Double>> val1 = new ArrayList<Pair<String,Double>>();
val1.add(new Pair<String,Double>("f\u2081(1) = ", 0.1));
val1.add(new Pair<String,Double>("f\u2082(1) = ", 0.2));
val1.add(new Pair<String,Double>("f\u2083(1) = ", 0.1));
val1.add(new Pair<String,Double>("f\u2084(1) = ", 1.1));
val1.add(new Pair<String,Double>("f\u2085(1) = ", 1.2));
val1.add(new Pair<String,Double>("f\u2086(1) = ", 2.0));
val1.add(new Pair<String,Double>("f\u2087(1) = ", 2.1));
val1.add(new Pair<String,Double>("f\u2088(1) = ", 0.3));
Collections.sort(val1,new Pair<String,Double>("",0.0).getComparator());
for (Pair<String, Double> pair : val1) {
System.out.println(pair.getX()+" "+pair.getY());
}
}
}
Any help or advice would be greatly appreciated. I'm trying to create a simple game which generates ten different, random questions. The questions can contain 2, 3 or 4 integers. So something like this: 55 2 − 4 − 101, 102/3/3, 589 − 281, 123 + 5 6 + 2.
The question will be displayed in a textview and then the user can take a guess, entering values into an edittext and then upon clicking a key on a custom keypad I have created it will check the answer, and then display the next question in the sequence of 10.
I know how to create random numbers, just struggling to work out how to create a whole question with random operators (+, -, /, *).
Big thank you to anyone who has the time to construct a reply.
A little of spare time produced a complete example for your case. Create new RandomMathQuestionGenerator.java file and it is cooked for compilation.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class RandomMathQuestionGenerator {
private static final int NUMBER_OF_QUESTIONS = 10;
private static final int MIN_QUESTION_ELEMENTS = 2;
private static final int MAX_QUESTION_ELEMENTS = 4;
private static final int MIN_QUESTION_ELEMENT_VALUE = 1;
private static final int MAX_QUESTION_ELEMENT_VALUE = 100;
private final Random randomGenerator = new Random();
public static void main(String[] args) {
RandomMathQuestionGenerator questionGenerator = new RandomMathQuestionGenerator();
List<Question> randomQuestions = questionGenerator.getGeneratedRandomQuestions();
for (Question question : randomQuestions) {
System.out.println(question);
}
}
public List<Question> getGeneratedRandomQuestions() {
List<Question> randomQuestions = new ArrayList<Question>(NUMBER_OF_QUESTIONS);
for (int i = 0; i < NUMBER_OF_QUESTIONS; i++) {
int randomQuestionElementsCapacity = getRandomQuestionElementsCapacity();
Question question = new Question(randomQuestionElementsCapacity);
for (int j = 0; j < randomQuestionElementsCapacity; j++) {
boolean isLastIteration = j + 1 == randomQuestionElementsCapacity;
QuestionElement questionElement = new QuestionElement();
questionElement.setValue(getRandomQuestionElementValue());
questionElement.setOperator(isLastIteration ? null
: Operator.values()[randomGenerator.nextInt(Operator.values().length)]);
question.addElement(questionElement);
}
randomQuestions.add(question);
}
return randomQuestions;
}
private int getRandomQuestionElementsCapacity() {
return getRandomIntegerFromRange(MIN_QUESTION_ELEMENTS, MAX_QUESTION_ELEMENTS);
}
private int getRandomQuestionElementValue() {
return getRandomIntegerFromRange(MIN_QUESTION_ELEMENT_VALUE, MAX_QUESTION_ELEMENT_VALUE);
}
private int getRandomIntegerFromRange(int min, int max) {
return randomGenerator.nextInt(max - min + 1) + min;
}
}
class Question {
private List<QuestionElement> questionElements;
public Question(int sizeOfQuestionElemets) {
questionElements = new ArrayList<QuestionElement>(sizeOfQuestionElemets);
}
public void addElement(QuestionElement questionElement) {
questionElements.add(questionElement);
}
public List<QuestionElement> getElements() {
return questionElements;
}
public int size() {
return questionElements.size();
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (QuestionElement questionElement : questionElements) {
sb.append(questionElement);
}
return sb.toString().trim();
}
}
class QuestionElement {
private int value;
private Operator operator;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
#Override
public String toString() {
return value + (operator == null ? "" : " " + operator.getDisplayValue()) + " ";
}
}
enum Operator {
PLUS("+"), MINUS("-"), MULTIPLIER("*"), DIVIDER("/");
private String displayValue;
private Operator(String displayValue) {
this.displayValue = displayValue;
}
public String getDisplayValue() {
return displayValue;
}
}
Run and preview. Hope this helps.
Thanks to:
Generating random number in
range
Retrieving random
element from array
Create an array char[] ops = { '+', '-', '/', '*' } and create a random int i in range [0,3], and chose ops[i]
You will need to take care that you do not generate a divide by zero question.
You can make it even more generic by creating an interface MathOp and creating 4 classes that implement it: Divide, Sum , ... and create an array: MathOp[] ops instead of the char[]
Using this, it will also give you much easier time to check the result later on...
Put your operators in an array (4 elements), generate a random integer from 0 to 3, and pick the operator that is at this index in the array.
Do that each time you need to have a random operator, i.e. after every number of your question except the last one.
Make an array that has one entry for each of the operators. Then generate a random number between 0 and the length of the array minus 1.
So since each operation is binary you can just worry about figuring out the base case and then building up your expressions from there.
An easy way would just to select a random number an correlate that which operation will be used.
int displayAnswer(int leftSide, int rightSide, int operation {
int answer;
string operation;
switch(operation) {
case 1:
operation = "+";
answer = leftSide + rightSide;
break;
case 2:
operation = "-";
answer = leftSide - rightSide;
break;
case 3:
operation = "*";
answer = leftSide * rightSide;
break;
case 4:
operation = "/";
answer = leftSide / rightSide:
break;
}
textView.setText(leftSide + operation + rightSide);
return answer;
}