Print Consecutive numbers by comparing two parameters - java

input 3,5 output should be 3,4,5
input 5,3 output should be 5,4,3
And the code
public static void test(int a, int b) {
if(a>b) {
for (int i = a; i >= b; i--) {
System.out.print(i + "\t");
}
}else if(a<b) {
for (int i = a; i <= b; i++) {
System.out.print(i + "\t");
}
}
}
It works but looks a little messy. Is it possible to do without if else thing? Only one loop.

One solution which handle also boundary values correctly could be
public static void test(int start, int end) {
int current = start;
int stepWidth = current <= end ? +1 : -1;
while (current != (end + stepWidth)) {
System.out.print(current + "\t");
current += stepWidth;
}
System.out.println("");
}
edit Another one using a for loop.
public static void test(int start, int end) {
int stepWidth = start <= end ? 1 : -1;
for (int current = start; current != end + stepWidth; current += stepWidth) {
System.out.print(current + "\t");
}
System.out.println("");
}
executions
test(3, 5);
test(5, 3);
test(Integer.MAX_VALUE - 3, Integer.MAX_VALUE);
test(Integer.MIN_VALUE, Integer.MIN_VALUE + 3);
output
3 4 5
5 4 3
2147483644 2147483645 2147483646 2147483647
-2147483648 -2147483647 -2147483646 -2147483645

How about this version?
public static void test(int a, int b) {
int d = b > a ? 1 : -1;
for (int i = a; i != b; i+=d) {
System.out.print(i + "\t");
}
System.out.println(b);
}

This my solution, feedback appreciated.
public static void test(int a, int b) {
int middle = (a < b) ? (b - 1) : (a - 1);
System.out.println(a + "," + middle + ","+b);
}
Above will work only when a != b.

Related

Pre-Increment (++i ) and i + 1 in Reccursions. Why do they have different action ? StackOverFlow Mistake

In the Recursion when I write res += countNatNum(++len, sum + i, k, d); I have a StackOverFlow mistake. But when I change pre-increment on len + 1 res res += countNatNum(len + 1, sum + i, k, d); everything is OK. I don't understand why does it happen because I check the condition with if (len == 3) ?
public static int countNatNum(int len, int sum, int k, int d){
int base = 9;
if (d > base * k) return 0;
else if (len == k){
if (sum == d){
return 1;
}
else return 0;
}
int res = 0;
int c = (len == 0 ? 1 : 0);
for (int i = c; i <= base; i++){
res += countNatNum(len + 1, sum + i, k, d);
}
return res;
}
}
The Program should count the number of natural numbers where sum of digits == another natural number. The program works correct but i don't understand why does pre-increment works in such strange way.
If you use "++" the updated value is stored again. ""len +1" on the other hand does not increment "len".

Modular Exponentiation overflow

public class Solution {
public int pow(int A,int B,int d)
{
if(A<0){ A=A+d;}
if (B==0)
{
if(A==0){return 0;}
return 1;
}
else if(B%2==0)
{
int y=pow(A,B/2,d);
return (y*y)%d;
}
else
{
return (A%d*pow(A,B-1,d))%d;
}
}
}
My code overflows for,
A : 71045970
B : 41535484
d : 64735492
my code gives o/p: -17412928
expected o/p : 20805472
Where it goes wrong?
can someone modify my code?
Please try this
public int Mod(int a, int b, int c) {
if(b==0){
if(a==0) return 0;
else
return 1;
}
else if(b%2==0){
long y=Mod(a,b/2,c);
return (int)(((long)(y*y))%(long)c);
}else{
int k=a%c;
if(k<0){
k+=c;
}
return (int)(((long)((long)k * (long)Mod(a,b-1,c)))%(long)c);
}
}
BigInteger as a modPow method that does this for you trivially.
Not giving your expected result but giving a different result:
public int pow(int a, int b, int mod) {
if (a < 0) {
a = a + mod;
}
if (b == 0) {
if (a == 0) {
return 0;
}
return 1;
} else if (b % 2 == 0) {
int y = pow(a, b / 2, mod);
return (y * y) % mod;
} else {
return (a % mod * pow(a, b - 1, mod)) % mod;
}
}
public int bigPow(int a, int b, int mod) {
return BigInteger.valueOf(a).modPow(BigInteger.valueOf(a), BigInteger.valueOf(mod)).intValue();
}
private void test(int a, int b, int mod) {
System.out.println("Old - modPow(" + a + "," + b + "," + mod + ") = " + pow(a, b, mod));
System.out.println("New - modPow(" + a + "," + b + "," + mod + ") = " + bigPow(a, b, mod));
}
public void test() {
test(71045970, 41535484, 64735492);
}
prints
Old - modPow(71045970,41535484,64735492) = -17412928
New - modPow(71045970,41535484,64735492) = 44382800
In case you actually aren't looking for modPow (which now looks likely) here's a rough attemt at duplicating youyr aalgorithm using BigInteger.
public BigInteger bigPow(BigInteger a, BigInteger b, BigInteger mod) {
if (a.compareTo(BigInteger.ZERO) < 0) {
a = a.add(mod);
}
if (b.compareTo(BigInteger.ZERO) == 0) {
if (a.compareTo(BigInteger.ZERO) == 0) {
return BigInteger.ZERO;
}
return BigInteger.ONE;
} else if (!b.testBit(0)) {
BigInteger y = bigPow(a, b.shiftRight(1), mod);
return y.multiply(y).mod(mod);
} else {
return a.mod(mod).multiply(bigPow(a, b.subtract(BigInteger.ONE), mod));
}
}
Now gives the expected answer.
Old - modPow(71045970,41535484,64735492) = -17412928
New - modPow(71045970,41535484,64735492) = 20805472

Does my pseudocode make sense? [duplicate]

This question already has an answer here:
Can you quickly tell me if this pseudocode makes sense or not?
(1 answer)
Closed 9 years ago.
I believe my code is now foolproof. I will write up the pseudocode now. But I do have one question. Why does DRJava ask that I return something outside of my if statements? As you can see I wrote for ex: "return 1;" just because it asked. It will never return that value however. Can someone explain this to me?
public class assignment1question2test {
public static void main(String[] args) {
int[] a = new int[1];
int l = 0;
int r = a.length-1;
for(int i=0; i<=r; i++) {
a[i] = 1;
}
a[0] = 10;
for (int i=0; i<=r; i++) {
System.out.println(a[i]);
}
System.out.print(recursiveSearch(a,l,r));
}
public static int recursiveSearch (int[] a, int l, int r) {
int third1 = (r-l)/3 + l;
int third2 = third1*2 - l + 1;
if (r-l == 0) {
return l;
}
System.out.println("i will be checking compare from " + l + " to " + third1 + " and " + (third1 + 1) + " to " + third2);
int compareResult = compare(a,l,third1,third1 + 1, third2);
if(r-l == 1) {
if (compareResult == 1) {
return l;
}
else {
return r;
}
}
if (compareResult == 0) {
return recursiveSearch(a,third2 + 1, r);
}
if (compareResult == 1) {
return recursiveSearch(a,l,third1);
}
if (compareResult == -1) {
return recursiveSearch(a,third1 + 1, third2);
}
return 1;
}
public static int compare(int[] a, int i, int j, int k, int l) {
int count1 = 0;
int count2 = 0;
for(int g=i; g<=j; g++) {
count1 = count1 + a[g];
}
for(int g=k; g<=l; g++) {
count2 = count2 + a[g];
}
if (count1 == count2) {
return 0;
}
if (count1 > count2) {
return 1;
}
if (count1 < count2) {
return -1;
}
return 0;
}
}
FINAL PSEUDOCODE I THINK
Algorithm: recursiveSearch (a,l,r)
Inputs: An array a, indices l and r which delimit the part of interest.
Output: The index that has the lead coin.
int third1 ← (r - l)/3
int third2 ← third1*2 - l + 1
if (r-l = 0) then
return l
int compareResult ← compare(a,l,third1,third1 + 1,third2)
if (r-l = 1) then
if (compareResult = 1) then
return l
else
return r
if (compareResult = 0) then
return recursiveSearch(a, third2 + 1, r)
if (compareResult = "1") then
return recursiveSearch(a,l,third1)
if (compareResult = "-1") then
return recursiveSearch(a,third1 + 1,third2)
String compareResult ← compare(a,l,mid,mid,r)
Here you check the middle element twice, make it:
String compareResult ← compare(a,l,mid,mid+1,r)
Apart from that your algorithm seems fair enough to me.
You should refine you logic more, it doesn't consider the case where the number of coin is even.
Odd: take a coin out, divide the remaining into 2 equal half and do the comparison.
Even: divide the remaining into 2 equal half and do the comparison.
For recursive function, please also define the base case:
When n=1, return the coin.
When n=2, return the heavier coin.
NumberOfCoin = r-l+1
if (NumberOfCoin = 1)
return l;
if (NumberOfCoin = 2)
compare(a,l,l,r,r)
0: Think it yourself
-1: Think it yourself
1: Think it yourself
if (NumberOfCoin is odd number)
mid = Think it yourself
compare(a, l, mid-1, mid+1, r)
0: Think it yourself
-1: Think it yourself
1: Think it yourself
if (NumberOfCoin is even number)
mid = l+r/2
compare(a, l, mid, mid+1, r)
0: Think it yourself
-1: Think it yourself
1: Think it yourself

Can you quickly tell me if this pseudocode makes sense or not?

I believe my code is now foolproof. I will write up the pseudocode now. But I do have one question. Why does DRJava ask that I return something outside of my if statements? As you can see I wrote for ex: "return 1;" just because it asked. It will never return that value however. Can someone explain this to me?
public class assignment1question2test {
public static void main(String[] args) {
int[] a = new int[50];
int l = 0;
int r = a.length;
for(int i=0; i<r; i++) {
a[i] = 1;
}
a[0] = 10;
for (int i=0; i<r; i++) {
System.out.println(a[i]);
}
System.out.print(recursiveSearch(a,l,r));
}
public static int recursiveSearch (int[] a, int l, int r) {
int third1 = (r-l)/3 + l;
int third2 = third1*2 - l + 1;
System.out.println("i will be checking compare from " + l + " to " + third1 + " and " + (third1 + 1) + " to " + third2);
int compareResult = compare(a,l,third1,third1 + 1, third2);
if(r-l == 1) {
if (compareResult == 1) {
return l;
}
else {
return r;
}
}
if (compareResult == 0) {
return recursiveSearch(a,third2 + 1, r);
}
if (compareResult == 1) {
return recursiveSearch(a,l,third1);
}
if (compareResult == -1) {
return recursiveSearch(a,third1 + 1, third2);
}
return 1;
}
public static int compare(int[] a, int i, int j, int k, int l) {
int count1 = 0;
int count2 = 0;
for(int g=i; g<=j; g++) {
count1 = count1 + a[g];
}
for(int g=k; g<=l; g++) {
count2 = count2 + a[g];
}
if (count1 == count2) {
return 0;
}
if (count1 > count2) {
return 1;
}
if (count1 < count2) {
return -1;
}
return 0;
}
}
UPDATED FINAL PSEUDOCODE:
Algorithm: recursiveSearch (a,l,r)
Inputs: An array a, indices l and r which delimit the part of interest.
Output: The index that has the lead coin.
int third1 ← (r - l + 1)/3
int third2 ← third1*2 - l + 1
if (r-l = 0) then
return l
int compareResult ← compare(a,l,third1,third1 + 1,third2)
if (r-l = 1) then
if (compareResult = 1) then
return l
else
return r
if (compareResult = 0) then
return recursiveSearch(a, third2 + 1, r)
if (compareResult = "1") then
return recursiveSearch(a,l,third1)
if (compareResult = "-1") then
return recursiveSearch(a,third1 + 1,third2)
You seem to be including mid in the following search regardless of which side is larger. The recursive calls should both exclude mid from their search space.
Also, for the comparison to be meaningful, the two groups being compared need to be of equal size. That will require some extra odd/even logic.

How to write an "all these numbers are different" condition in Java?

OK, I have this problem to solve but I can’t program it in Java correctly. See the picture below, you’ll see a 6 pointed star were every point and intersection of lines is a letter.
The assignment is to position the numbers 1 to 12 in such a way that the sum of all lines of four balls is 26 and the sum of all the 6 points of the star is 26 as well.
This comes down to:
(A+C+F+H==26)
(A+D+G+K==26)
(B+C+D+E==26)
(B+F+I+L==26)
(E+G+J+L==26)
(H+I+J+K==26)
(A+B+E+H+K+L==26)
So I started programming a program that would loop through all options brute forcing a solution. The loop is working, however, it now shows solutions where one number is used more than once, which is not allowed. How can I make it in the code that it also checks whether all variables are different or not?
if ((A!= B != C != D != E != F != G != H != I != J != K != L)
I tried the above, but it doesn't work, because it says:
incomparable types: boolean and int.
How can I make a check within 1 or a small statement for whether or not all the numbers are different?
(instead of making a nested 12*12 statement which checks every variable combination)
This is my code so far:
public class code {
public static void main(String[] args){
for(int A = 1; A < 13; A++){
for(int B = 1; B < 13; B++){
for(int C = 1; C < 13; C++){
for(int D = 1; D < 13; D++){
for(int E = 1; E < 13; E++){
for(int F = 1; F < 13; F++){
for(int G = 1; G < 13; G++){
for(int H = 1; H < 13; H++){
for(int I = 1; I < 13; I++){
for(int J = 1; J < 13; J++){
for(int K = 1; K < 13; K++){
for(int L = 1; L < 13; L++){
if ((A+C+F+H==26) && (A+D+G+K==26) && (B+C+D+E==26) && (B+F+I+L==26) && (E+G+J+L==26) && (H+I+J+K==26) && (A+B+E+H+K+L==26)){
if ((A= C != D != E != F != G != H != I != J != K != L)){
System.out.println("A: " + A);
System.out.println("B: " + B);
System.out.println("C: " + C);
System.out.println("D: " + D);
System.out.println("E: " + E);
System.out.println("F: " + F);
System.out.println("G: " + G);
System.out.println("H: " + H);
System.out.println("I: " + I);
System.out.println("J: " + J);
System.out.println("K: " + K);
System.out.println("L: " + L);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
If I get it correctly, you want to check if all A to L are unique. So just put them in a set and find the size of the set:
if ((new HashSet<Integer>(
Arrays.asList(A, B, C, D, E, F, G, H, I, J, K, L)))
.size() == 12) {
//do your stuff
}
I strongly advise using recursion instead, which would vastly simplify the code. Do something like this:
function generate(set used, array list):
if list.size() == 12:
if list matches criteria:
yield list as solution
else:
for next = 1; next < 13; next++:
if next not in used:
used.add(next)
generate(used, list + next)
used.remove(next)
However, to answer you question directly: You can throw all the values into a set and check that it's size is equal to the number of items you threw in. This works because a set will count duplicates as one.
Before looking for a good solution for you, I would like to help with the error you get.
if ((A= C != D != E != F != G != H != I != J != K != L)){
This line does not makes much sense. The first thing the compiler will check is:
if (A=C)
You probably wanted to code if (A!=C), but let's consider what you really type. A=C is an attribution, so A will receive C value.
Then, the compiler will go on. After attributing C's value to A, it will check the comparison:
if (A=C != D)
This will compare A's value to D, which will result in a boolean -- let's say that the result is false.
The next comparison would be:
if (false != E)
At this point, there is a comparison between a boolean and an int, hence the error incomparable types: boolean and int..
Well, as you need to check wheter your numbers are unique, a nice solution would be the one proposed by #abhin4v.
Your nested loops will execute 12^12 = 8.91610045E12 IF-Statements, many of them invalid because of wrong combinations of numbers. You need permutations of 1,2,3,..,12 as candidates of your bruteforcing approach. The number of permutations of 12 Elements is 12!= 479 001 600, so the bruteforcing will be much faster I guess. With only generating valid permutations you don't need any check for valid combinations.
Here is some sample code, the code in nextPerm() is copied and modified from Permutation Generator :
import java.util.Arrays;
public class Graph26 {
private static final int A = 0;
private static final int B = 1;
private static final int C = 2;
private static final int D = 3;
private static final int E = 4;
private static final int F = 5;
private static final int G = 6;
private static final int H = 7;
private static final int I = 8;
private static final int J = 9;
private static final int K = 10;
private static final int L = 11;
private final static boolean rule1(final int[] n) {
return n[A] + n[C] + n[F] + n[H] == 26;
}
private final static boolean rule2(final int[] n) {
return n[A] + n[D] + n[G] + n[K] == 26;
}
private final static boolean rule3(final int[] n) {
return n[H] + n[I] + n[J] + n[K] == 26;
}
private final static boolean rule4(final int[] n) {
return n[B] + n[C] + n[D] + n[E] == 26;
}
private final static boolean rule5(final int[] n) {
return n[B] + n[F] + n[I] + n[L] == 26;
}
private final static boolean rule6(final int[] n) {
return n[E] + n[G] + n[J] + n[L] == 26;
}
private final static boolean rule7(final int[] n) {
return n[A] + n[B] + n[E] + n[H] + n[K] + n[L] == 26;
}
private final static boolean isValid(final int[] nodes) {
return rule1(nodes) && rule2(nodes) && rule3(nodes) && rule4(nodes)
&& rule5(nodes) && rule6(nodes) && rule7(nodes);
}
class Permutation {
private final int[] o;
private boolean perms = true;
public boolean hasPerms() {
return perms;
}
Permutation(final int[] obj) {
o = obj.clone();
}
private int[] nextPerm() {
int temp;
int j = o.length - 2;
while (o[j] > o[j + 1]) {
j--;
if (j < 0) {
perms = false;
break;
}
}
if (perms) {
int k = o.length - 1;
while (o[j] > o[k]) {
k--;
}
temp = o[k];
o[k] = o[j];
o[j] = temp;
int r = o.length - 1;
int s = j + 1;
while (r > s) {
temp = o[s];
o[s] = o[r];
o[r] = temp;
r--;
s++;
}
}
return o.clone();
}
}
public static void main(final String[] args) {
int[] nodes = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
final Graph26 graph = new Graph26();
final Permutation p = graph.new Permutation(nodes);
int i = 0;
while (p.hasPerms()) {
if (isValid(nodes)) {
System.out.println(Arrays.toString(nodes));
}
i++;
nodes = p.nextPerm();
}
System.out.println(i);
}
}

Categories