Bad interaction between a script and its tester - java

So I have this script I've written:
public class Primes {
public static void main(String[] args) {
}
//Part 4: Question 1
public static int Binary2int(String b){
int size = b.length();
double count, sum=0;
boolean binary = true;
for (int i=0; i<b.length() ; i++){
int digit = b.charAt(i)-'0';
if (digit>1){
binary = false;
i=b.length();
}
count = digit*Math.pow(2, size-i-1);
sum+=count;
}
if (!binary){
System.out.println("Error - "+b+" is not a binary number.");
}
int sum1 = (int)sum;
return sum1;
}
//Part 4: Question 2
public static boolean isBinaryString(String b){
boolean binary = true;
for (int i=0; i<b.length() ; i++){
int digit = b.charAt(i)-'0';
if (digit>1){
binary = false;
i=b.length();
}
}
return binary;
}
//Part 4: Question 3
public static String int2Binary(int n){
int count=0;
if (n<=0){
count = 1;
}
for (int i=n; i>0 ;){
i=i/2;
count++;
}
int arr[] = new int [count];
for (int i=n, t=0; i>0 ;t++){
arr[arr.length-1-t] = i%2;
i = i/2;
}
if (n<=0){
arr[0] = 0;
}
String s = Arrays.toString(arr);
return s;
}
}
4.1 is meant to take a string (which stands for a binary number) and then return an integer(which stands for the integer the binary number in the input represents).
4.2 takes a binary number in the form of a string and then returns a Boolean variable (true if it’s a binary number and false if it isn’t).
4.3 is doing the opposite of 4.1, it takes an integer in the form of an integer and returns the binary number that represents it in the form of a string.
Oh and It all works fine when I'm testing it.
Now the problem is that the one checking it will be using the following (type of)script:
/**
* This class represents a tester - to be used by students to check Ex3: <br>
* 1. call all the public functions, check compilation. <br>
* 2. test some of function of their results. <br> <br>
* note: for debug change the printFlag to true.
*/
public class BynaryTest {
/**
* if set to true - will print a trace of all the checks.
*/
public static boolean printFlag = true;//false;
/**
* number of errors the test program found
*/
public static int error = 0;
/**
* this main function runs the test of the EX3Tester class
*/
public static void main(String[] a) {
System.out.println("******* Testing Ex3 - print mode = " + printFlag + " ********");
checkEx34();
System.out.println();
System.out.println("******* U have got " + error + " errors ********");
}
public static void checkEx34() {
if (printFlag) {
System.out.println("**** Cheking Ex21 ****");
}
int[] nums = {0, 1, 12345};
for (int i = 0; i < nums.length; i = i + 1) {
String s = Primes.int2Binary(nums[i]);
int num2 = Primes.Binary2int(s);
if (nums[i] != num2) {
error++;
System.out.println("** Error in EX34:" + num2 + "!=" + nums[i] + " **");
} else {
if (printFlag) {
System.out.println("num[" + i + "]=" + nums[i] + " binary: " + s + " .. ok");
}
}
}
}
}
The interaction between the two scripts does happen and nothing crashes, but then, for some reason, the only outcome I get from using it is:
** Error in EX34:21!=0 **
Error - [1] is not a binary number.
** Error in EX34:21!=1 **
Error - [1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1] is not a binary number.
** Error in EX34:21!=12345 **
******* U have got 3 errors ********
I've tried to fix it myself or finding out what causes that sort of unwanted outcome but I couldn't come up with anything :(

Have you tested it? The mistake is quite obvious if you do.
For example for 9 your Int2Binary method returns the following binary representation: [1, 0, 0, 1] as String.
Then in your Binary2Int you check if you only have 0s and 1s like so:
int digit = b.charAt(i)-'0'; // b is [1, 0, 0, 1]
if (digit>1){
binary = false;
//... more code ...
}
See the mistake now?

In your method intToBinary, you have the following line:
String s = Arrays.toString(arr);
I think you are expecting this to take an array and concat all the values in it into a single string. Given this example:
int[] array = {1, 0, 0};
System.out.println(Arrays.toString(array));
You expect the output to be:
100
When in fact it is:
[1,0,0]

Related

Forming a pattern of bits from a integer

I need help to design java code for generating bit array for any given integer in following manner:
23 should produce output as 1101011 (min length array)
explaination :
positions are given as 1 -2 4 -8 16 -32 ....
So 1101011 can be evaluated as:
1*1 + 1*-2 + 0*4+ 1*-8 + 0*16 +1*-32 + 1*64 = 23
This is the so-called negabinary representation of numbers (described first by Vittorio Grünwald in 1885). They can be encoded in a fashion very similar to the usual binary representation, just working with -2 instead of 2 as base (Java code inspired by C# code on https://en.wikipedia.org/wiki/Negative_base ):
class EncodeNegaBinary {
public static void main(String[] args) {
int n=0,input=0;
String result="";
final String[] BITS = { "0","1" };
if (args.length != 1) {
System.err.println("Please enter an integer to be converted");
return;
} else {
input = n = Integer.parseInt(args[0]);
}
while (n != 0) {
int r = n%-2;
n /= -2;
if (r == -1) {
r=1;
n++;
}
result = BITS[r] + result;
}
System.out.printf( "%d -> %s\n", input, result);
}
}
Since it is not usual int to binary conversion, at each step we need to consider two cases as at each position there can be only two choices 0 or 1. This is done recursively in the below program:
public class ModifiedIntToBinaryConversion{
public static int calcBinaryString(int reqSum, int currSum, int add, String bs) {
if (reqSum == currSum) { // base condtion 1
System.out.println("The string is \n" + bs);
return currSum;
}
if (add + currSum > reqSum) { // base condtion 2
return 0;
}
int newAdd = add * -2;
// System.out.println("new add is "+ newAdd +" currSum is "+ currSum);
int s1 = calcBinaryString(reqSum, currSum + add, newAdd, bs + "1");
if (s1 == reqSum)
return s1;
int s2 = calcBinaryString(reqSum, currSum, newAdd, bs + "0");
return s2;
}
public static void calcBinaryString(int sum) {
int s1 = calcBinaryString(sum, 0, 1, "");
if(s1 != sum) {
System.out.println("The binary equivalent couldn't be found");
}
}
public static void main(String[] args) {
calcBinaryString(23);
}
}
Now base condition 1 is clear as I am just checking whether required sum and calculated sum are equal.
For base condition 2, I will accept it's result of debugging and a bit of thought as I was getting Stackoverflow errors. Once the calculated sum becomes greater than the required sum and then we take the next -ve number so that it become less than req. sum. But then the next +ve number will be greater than the -ve number we just considered and thus the chances are very less that the calculated sum will ever be equal to req. sum.

Why does my method return the wrong value?

Even though my method operationsNeeded prints the correct value for my return-int "count1", the very next line it returns something else to my main method. I did not include the rest of my code, if needed I'd gladly provide it.
For example if operationsNeeded is executed 4 times, count1 is on 4 which is printed out as well. But for reasons unknown to me the System.out.println("check: " +count1); Statement is executed 4 times like this:
check: 4
check: 4
check: 3
check: 2
I would expect my program to execute this only once and then continue to the return statement.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
int count =0;
while (count<testcases){
int numberOfColleagues = sc.nextInt();
sc.nextLine();
String startPieces = sc.nextLine();
int[] listOfcolleagues = listOfColleagues(numberOfColleagues, startPieces);
int count2 = operationsNeeded(listOfcolleagues, 1);
count++;
System.out.println(count2);
}
}
public static int operationsNeeded (int[] listOfColleagues, int count1){
//remove duplicates first
ArrayList<Integer> relevantList=removeDuplicatesAndSort(listOfColleagues);
System.out.println("relevantlist" + relevantList);
//check for smallestdelta & index
int [] deltaAndIndex = smallestDeltaHigherIndex(relevantList);
int delta = deltaAndIndex[0];
int index = deltaAndIndex[1];
if (delta==1){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+1);
}
}
}
if (delta>1 && delta<5){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+2);
}
}
}
if (delta>4){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+5);
}
}
}
System.out.println(count1);
int[] updatedList = new int[relevantList.size()];
for (int i=0; i<relevantList.size();i++){
updatedList[i]=relevantList.get(i);
}
if (!isAllTheSame(relevantList)) {
count1 +=1;
operationsNeeded(updatedList,count1);
}
System.out.println("check: " + count1);
return count1;
}
Your method is recursive. The "check: " line is printed on each level of that recursion, with the value that it currently has on that level. It first prints the "inner-most" value (4), than that of the level above (also 4), and finally hte value in the top-level, which is 2 after being incremented in the if above. And the value it returns is always the value from to top-level.
If you want to print it only once, you could print it on the inner-most level only, using else. However, that will still return the value from the top-level iteration; instead, keep track of the value returned from the recirsive call and update count1 accordingly.
if (! isAllTheSame(relevantList)) {
// we have to go deeper!
count1 = operationsNeeded(updatedList, count1 + 1);
} else {
// phew, finally done
System.out.println("check: " + count1);
}

given int X,find Y such that (X+Y) is pallindrome in binary format.works fine with values upto 12345 not working with values 123456 and above

public class aevi{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
long num=s.nextLong();
long i=0,j;
while(i<num)
{
long p=1,sum=0,reversesum=0;
j=num+i;
while(j>0)
{
System.out.print(j%2+" ");
sum+=(j%2)*p;
p=p*10;
j=j/2;
}
long r=sum;
System.out.print(r+" ");
while(sum!=0)
{
reversesum=(reversesum*10)+(sum%10);
sum=sum/10;
}
System.out.println(reversesum);
if(reversesum==r)
{System.out.println(i);
break;}
i++;
}
}
}
whats wrong with this code.The program is about " given a number X.find minimium positive integer Y required to make binary representation of
(X+Y) palindrome.for eg:X=6 Y=1".It works fine with values upto 12345 but it is not working with values 123456 and above.
To tell the truth, it is hard to read your code and find problem. I think it is too complicated with such simple problem. I offer you another solution.
E.g. you entered x=6, this is 110 in binary format. Your goal is to find another minimal value y that x+y=<binary palindrome>. For 110, maximum palindrome id 111 which is 7. So, all you need is just find a minimal 0 <= y <= (7-6) where x+y=<binary palindrome>.
Here is the code example. It is pretty easy and simple.
public static long toBinaryPalindrome(long num) {
for (long i = 0, total = allBits(Long.toBinaryString(num).length()) - num; i <= total; i++)
if (isBinaryPalindrome(num + i))
return i;
return -1;
}
private static boolean isBinaryPalindrome(long num) {
String str = Long.toBinaryString(num);
return str.equals(new StringBuilder(str).reverse().toString());
}
private static long allBits(int len) {
long res = 0;
for (int i = 0; i < len; i++)
res |= 1 << i;
return res;
}

DEMA & TEMA Ta-lib Java Implementation

I am currently working with Ta-lib Java implementations. I can run properly MA & SUM. But having problem while try to run DEMA, TEMA. The output is all zeros.
I am calling the DEMA & TEMA method of Ta-lib as follows
import com.tictactec.ta.lib.Core;
import com.tictactec.ta.lib.MInteger;
public class TALibJava {
double[] array = {207.650, 205.160, 210.870, 209.350, 207.250, 209.960, 207.650, 205.160, 188.170, 186.020};
double[] output = new double[array.length];
int period = 5;
Core core = new Core();
int lookback = 0;
MInteger begin = new MInteger();
MInteger length = new MInteger();
public void callDEMA() {
lookback = core.demaLookback(period);
core.dema(0, array.length - 1, array, 0, begin, length, output);
System.out.println("DEMA Output: ");
print();
}
public void callTEMA() {
lookback = core.temaLookback(period);
core.tema(0, array.length - 1, array, 0, begin, length, output);
System.out.println("TEMA Output: ");
print();
}
public void print() {
for(int i=0;i<array.length;i++) {
System.out.print(output[i] + "\t ");
}
System.out.println("");
}
public static void main(String args[]) {
TALibJava obj = new TALibJava();
obj.callDEMA();
obj.callTEMA();
}
}
Perhaps the input parameters are not properly set. Please suggest me what I'm doing wrong.
According to the source code of dema(), optInTimePeriod cannot be 0:
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return RetCode.BadParam ;
That's why your current code returns "BadParam" and not "Success" when you call dema().
(Same thing goes for tema())

Recursively splitting off perfect squares for display

I am attempting to create a recursive method that accepts an integer parameter and prints the first n squares
separated by commas, with the odd squares in descending order followed by the even squares in ascending order.
For example, if the input is 8, it should print the following output:
49, 25, 9, 1, 4, 16, 36, 64
My code so far is:
s and n have the same values initially, the only difference is that s changes as the code forwards while n doesn't change.
private static void genSquare(int s, int n) {
if (s >= 0 && s <= n) {
if (isOdd(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s - 2, n);
}
if (s == 0 || s == 1) {
genSquare(1, n);
}
if (isEven(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s + 2, n);
}
}
}
I have created a while loop version of it, which works perfectly. I just don't have the recursive version working.
Sample inputs would be using the same number for s and n.
Here is the code for the loop version:
private void genLoop(int s, int n) {
if (isEven(s)) {
s--;
}
while (s <= n) {
if (s == 1) {
System.out.print(1 + " ");
s++;
} else if (isOdd(s)) {
System.out.print(s * s + " ");
s -= 2;
} else if (isEven(s)) {
System.out.print(s * s + " ");
s += 2;
}
}
}
The problem is in this statement:
if(s == 0 || s== 1)
genSquare(1,n);
This causes the method to recurse infinitely. In fact, when you get to the point where s is zero or one, you have to make sure that you DON'T call genSquare recursively.
That's enough of a hint for you to figure the rest out for yourself ... and fix any other bugs.
In addition, there's a simpler way of squaring an integer ...
void calculateSquare(int n)
{
// odds descending and even ascending
int t=n;
if(n<=0)
return;
if(n%2==1)
{
// Calculate square now and print it also
System.out.println(n*n);
calculateSquare(--n);
}
else
{
calculateSquare(--n);
System.out.println(t*t);
}
}
This would do the job.
Try the following approach:
Assume your example where n is equal to 8. The square of 8 should printed last so you probably first should do a recursive call, then print the square of the current number.
Thinking about the task for n=7 the order of things given above should be reverted for odd numbers.
Yes it is good example for recursion . Try this it helps u
public class RecursionEx {
static int no = 0;
public static void main(String[] args) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number");
try
{
no = Integer.parseInt(bufferedReader.readLine());
getSquares(no,0);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void getSquares(int number,int count)
{
if(number==1)
{
System.out.print(number);
count=1;
getSquares(number+1, count);
}
else
{
if(number%2!=0&&count==0)
{
System.out.print(number*number+",");
getSquares(number-2,0);
return;
}
if(count==0)
getSquares(number-1,0);
if(number%2==0&&count==1)
{
if(number<=no)
System.out.print(","+number*number);
if(number>=no)
return;
getSquares(number+2, count);
}
}
}
}

Categories