I want to create all combinations with two states(1 and 0).
If i do this with two for-loops, this works. But when I use a self-calling function it doesnt. Does anybody can tell me why, please ?
For-Loops :
public class Counter {
public Counter() {
loop(iter);
for (int i=0; i < 2; i++) {
for (int i2=0; i2 < 2; i2++) {
System.out.println(Integer.toString(i)+Integer.toString(i2));
}
}
}
public static void main(String args[]){
new Counter();
}
}
Self-Calling Function :
class Stringhelper {
public Stringhelper() {
}
public String getstring(String string,int beginning,int ending) {
if (string.length() != 0) {
String newstring="";
for (int iter=Math.abs(beginning); iter < ending && iter < string.length(); iter=iter+1) {
newstring=newstring+Character.toString(string.charAt(iter));
}
return newstring;
}
else {
return "";
}
}
}
public class Counter {
public String abil="";
public int iter=1;
public Stringhelper shelper=new Stringhelper();
public void loop(int iter) {
for (int i=0; i < 2; i++) {
abil=abil+Integer.toString(i);
if (iter==0) {
System.out.println(abil);
abil=shelper.getstring(abil,0,abil.length()-1);
}
else {
loop(iter-1);
}
}
}
public Counter() {
loop(iter);
}
public static void main(String args[]){
new Counter();
}
}
And using the self-calling Function the output is 00,01,010,011 instead of 00,01,10,11
Explaining your code here (ignore abil for now):
public void loop(int iter) {
for (int i=0; i < 2; i++) {
abil=abil+Integer.toString(i);
if (iter==0) {
System.out.println(abil);
abil=shelper.getstring(abil,0,abil.length()-1);
}
else {
loop(iter-1);
}
}
}
When iter is 0 it will print it
In the next iteration, when it is not equal to 0, another loop is created, added to the stack, where it starts again from 0, and prints abil's new stack value.
When you create a new stack it recreates all the variables in temporary storage until the code exits. In this case it keeps creating stacks and never exits. In order to exit a stack, use return.
In summary, you need to learn more about how stacks and recursion work in order to fix your problem.
public void loop(int iter) {
for (int i=0; i < 2; i++) {
if (i==1) {
abil=shelper.getstring(abil,0,iter);
}
abil=abil+Integer.toString(i);
if (iter==4) {
System.out.println(abil);
}
else {
loop(iter+1);
}
}
}
this did the trick
Related
Assuming that B[] is longer than A[], I'm trying to figure out a way to count the number of times all the elements of A[] occurs in B[].
So say a[]{A,B} & B[A,B,C,A,C,A,B,B,A,B]
It would return 3
Here's a generic method that counts occurrences of one array within the other:
public static <T> int countOccurrences(T[] hayStack, T[] needle) {
int foundCount = 0;
for (int i = 0; i <= hayStack.length - needle.length; i++) {
boolean found = true;
for (int j = 0; j < needle.length; j++) {
if (!Objects.equals(hayStack[i + j], needle[j])) {
found = false;
break;
}
}
if (found) {
foundCount++;
}
}
return foundCount;
}
And here's a test class to go with it:
public class ArrayzTest {
#Test
public void countOccurrences_whenNeedleEmpty_returnsHaystackLength(){
assertThat(Arrayz.countOccurrences(hayStack(), emptyArray()), is(hayStack().length));
}
#Test
public void countOccurrences_whenHaystackEmpty_returnsZero(){
assertThat(Arrayz.countOccurrences(emptyArray(), hayStack()), is(0));
}
#Test
public void countOccurrences_whenHaystackHasNeedles_countsOccurrences(){
assertThat(Arrayz.countOccurrences(hayStack(), needle()), is(3));
}
private Integer[] needle() {
return new Integer[]{1,2,3};
}
private Integer[] hayStack() {
return new Integer[]{1,2,3,1,2,3,1,2,3};
}
private Integer[] emptyArray() {
return new Integer[0];
}
}
I want to replace all multiples of 2 in my array with the value 0 and I felt as though this code did this but 4,6 and 8 stay the same in the output.
Am I doing something stupidly wrong?
public static void markOfMultiples(int[]listOfNumbers, int number)
{
for(int i = 0; i<listOfNumbers.length; i++)
{
if (listOfNumbers[i]%number == 0)
{
listOfNumbers[i] = 0;
}
}
}
In mycase your method was working fine,It solely depends how you are invoking your method
You should invoke your method like
public static void main(String[] args)
{
int num[]={2,4,6,11,13,8};
markOfMultiples(num,2);
}
Your method remains the same
public static void markOfMultiples(int[]listOfNumbers, int number)
{
for(int i = 0; i<listOfNumbers.length; i++)
{
if (listOfNumbers[i]%number == 0)
{
listOfNumbers[i] = 0;
}
System.out.println(listOfNumbers[i]);//added by me to track what's going on
}
and its working fine!
I am a new member here, and I am also a beginner in JAVA. The thing that seems the most abstract to me is recursion, and so I have some difficulties finishing a program that should have this output if we write 3 for example:
1
12
123
12
1
Or if we write 5 for example it should print out this:
1
12
123
1234
12345
1234
123
12
1
And I can do this program with for loop, but I have to use recursion, and here is what I have done so far:
public class Aufgabe3 {
private static void printSequenz(int n) {
if(n<1){
return;
}
printMany(n);
printSequenz(n-1);
}
private static void printMany(int n){
for(int i=1;i<=n;i++){
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
}
I would be really happy if someone would help me :).
You need to implement two recursive functions:
void printLoToHi(int n)
{
if (n < 1)
return;
printLoToHi(n-1);
printMany(n);
}
void printHiToLo(int n)
{
if (n < 1)
return;
printMany(n);
printHiToLo(n-1);
}
Then, you need to call them sequentially:
printSequenz(int n)
{
printLoToHi(n);
printHiToLo(n-1); // -1 in order to avoid printing the highest twice
}
Or in a more "symmetrical manner":
printSequenz(int n)
{
printLoToHi(n-1); // print lowest to second highest
printMany(n); // print the highest
printHiToLo(n-1); // print second highest to lowest
}
You could do it like this:
private static void printSequenz(int n) {
printSequenz(1,n, true);
}
private static void printSequenz(int current, int total, boolean goingUp) {
if(!goingUp && current<1){
return;
}
printMany(current);
if(current+1>total){
goingUp=false;
}
if(goingUp){
printSequenz(current+1,total,goingUp);
} else {
printSequenz(current-1,total,goingUp);
}
}
private static void printMany(int n) {
for (int i = 1; i <= n; i++) {
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
public class Test {
public static void main(String args[]) {
int seq = 6;
for(int i=1; i<=seq; i++) {
System.out.println("");
int low =seq-(seq-i);
printIncreasing(i,low);
}
for(int i=seq-1; i>=1; i--) {
System.out.println("");
int low = seq-i;
printDecreasing(i,low);
}
}
public static void printIncreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
public static void printDecreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
}
I have the following code which I use a lot of times in the class.
for (int i = 0; i < someList.size(); i++) {
for (int j = 0; j < someList.size(); j++) {
if (i != j) {
someList.get(i).sendMessageTo(someList.get(j))); //variable action
}
}
}
The purpose of the loop is to make each element in the List to send a message (or perform another action) to every element in the list except itself.
Is there any way I can create a helper method so I don't have to repeat the loop code.
Edit:
I need just one helper method to take care of the for loop and the if algorithm. I will supply the List and the whatever action I need to use. It should work for all.
I want to be able to state the variable action and call the helper method.
Thanks.
You could do something like (I don't know what type is in your List, I called it Element):
public interface ApplySomeAction
{
public apply(Element e1, Element e2);
}
...
public void applyActionToAllElements(ApplySomeAction action)
{
for (int i = 0; i < someList.size(); i++) {
for (int j = 0; j < someList.size(); j++) {
if (i != j) {
action.apply(someList.get(i), someList.get(j));
}
}
}
}
later call it with:
applyActionToAllElements(new ApplySomeAction() {
public apply(Element e1, Element e2)
{
e1.sendMessageTo(e2));
}
};
Could make another interface+method with just one element if you often do an action with just one of those elements.
You could maybe get rid of one of the loops by doing it this way:
for (int i = 0; i < someList.size() - 1; i++) {
someList.get(i).sendMessageTo(someList.get(i + 1))); //variable action
}
And use #NESPowerGlove's solution to abstract the method that's called.
I'd make me an Iterable
/**
* Returns all pairs of the list except those where i == j.
* #param <T>
*/
public class AllPairs<T> implements Iterable<Pair<T, T>> {
// The list.
private final List<T> list;
public AllPairs(List<T> list) {
this.list = list;
}
#Override
public Iterator<Pair<T, T>> iterator() {
return new PairIterator();
}
private class PairIterator implements Iterator<Pair<T, T>> {
// The indexes.
int i = 0;
int j = 0;
// The next to return.
Pair<T, T> next = null;
// Easier to read.
int size = list.size();
#Override
public boolean hasNext() {
while (next == null && (i < size || j < size)) {
// Step j.
j += 1;
// Wrap j.
if (j >= size && i < size) {
j = 0;
i += 1;
}
if (i < size && j < size && j != i) {
// Grab it.
next = new Pair<>(list.get(i), list.get(j));
}
}
return next != null;
}
#Override
public Pair<T, T> next() {
Pair<T, T> it = next;
next = null;
return it;
}
}
}
/**
* A simple Pair
*/
public static class Pair<P, Q> {
public final P p;
public final Q q;
public Pair(P p, Q q) {
this.p = p;
this.q = q;
}
}
public void test() {
System.out.println("Hello");
List<Integer> l = Arrays.asList(0, 1, 2, 3);
for (Pair<Integer, Integer> p : new AllPairs<>(l)) {
System.out.println("[" + p.p + "," + p.q + "]");
}
}
Then define an interaction mechanism - this would be almost trivial using Lambdas:
// Objects that can interact with each other.
public interface Interacts<T extends Interacts<T>> {
public void interact(T with);
}
public static <T extends Interacts<T>> void interactAllPairs(List<T> l) {
// Interact all pairs.
for (Pair<T, T> p : new AllPairs<>(l)) {
p.p.interact(p.q);
}
}
Then you can make your message objects interact - here's a simple example:
// Interact by sending a message.
public class Messenger implements Interacts<Messenger> {
private final int me;
public Messenger(int me) {
this.me = me;
}
#Override
public void interact(Messenger with) {
sendMessage(with);
}
public void sendMessage(Messenger to) {
System.out.println(this + "->" + to);
}
#Override
public String toString() {
return Integer.toString(me);
}
}
Testing now looks like:
public void test() {
// Meassage list.
List<Messenger> messages = new ArrayList<>();
for (int i = 0; i < 4; i++) {
messages.add(new Messenger(i));
}
interactAllPairs(messages);
}
giving your required output:
0->1
0->2
0->3
1->0
1->2
1->3
2->0
2->1
2->3
3->0
3->1
3->2
I am getting java.lang.ArrayIndexOutOfBoundsException error.
public class Trainee implements EvaluationDetails
{
private int traineeId;
private String traineeName;
private double traineeMarks[];
public Trainee(int id,String name,double Marks[])
{
traineeId=id;
traineeName=name;
traineeMarks=Marks;
}
public int getTraineeId()
{
return traineeId;
}
public String getTraineeName()
{
return traineeName;
}
public boolean validateTraineeMarks()
{
if(noOfCourses>0 && noOfCourses<8)
{
for(int i=0;i<=traineeMarks.length;i++)
{
if(traineeMarks[i]>0 && traineeMarks[i]<100)
continue;
else
return false;
}
return true;
}
else
return false;
}
public double calculateGPA()
{
int GPA;
int Cp[]=new int[7];
boolean bool=validateTraineeMarks();
if(bool==true)
{
for(int i=0;i<traineeMarks.length;i++)
{
if(traineeMarks[i]>=85 && traineeMarks[i]<=100)
Cp[i] = 5;
else if(traineeMarks[i]>=65 && traineeMarks[i]<85)
Cp[i] = 4;
else if(traineeMarks[i]>=0 && traineeMarks[i]<=65)
Cp[i] = 3;
}
GPA = //GPA calculation logic
}
else
{
System.out.println("Improper values for trainee marks");
return 0.0;
}
return GPA;
}
}
The main class is as shown below:
public class Demo {
public static void main(String[] args)
{
double marks[]={74.0,57.0,86.0,93.0,56.0,73.5,83.0};
Trainee t = new Trainee(102,"Dixon",marks);
System.out.println("Trainee Id:"+t.getTraineeId());
System.out.println("Trainee Name:"+t.getTraineeName());
System.out.println("GPA is"+t.calculateGPA());
}
}
The interface is coded as below:
public interface EvaluationDetails
{
int creditpoints[]={3,3,4,4,2,3,5};
int noOfCourses=7;
public double calculateGPA();
}
for(int i=0;i<=traineeMarks.length;i++) should be for(int i=0;i<traineeMarks.length;i++)
the problem is you are trying to access array.length + 1 elemnt
Your mistake is here:
for(int i=0;i<=traineeMarks.length;i++)
Indexes in java (and all c-like languages) start from 0 and therefore the last index of array is length-1. So, fix your loop definition as following:
for(int i=0;i<traineeMarks.length;i++)
Here is your mistake:
for(int i=0;i<=traineeMarks.length;i++)
you should go from i=0 to traineeMarks.length-1 so,
for(int i=0;i<traineeMarks.length;i++)
for(int i=0;i<=traineeMarks.length;i++)
should be
for(int i=0;i< traineeMarks.length;i++)
for(int i=0;i<=traineeMarks.length;i++) //this is wrong this cause to java.lang.ArrayIndexOutOfBoundsException
use
for(int i=0;i<traineeMarks.length;i++)