java - Permutations of 4 integers in an array? -


i have write code takes input of 4 integers between 1 , 9 scanner object , combines them in way equal 24. although solution not elegant have managed compile number of if statements using variables, b, c, d , hoping store numbers entered user in array , swap values of a, b, c, d generate each possible combination of numbers

for example 1 paring might (a+b*c) - d = 24. i'd want switch values of a, b, c, d possible combinations , life of me can't figure out how this. have

public static void dagame(int a, int b, int c, int d) {     int[] basearray = {a, b, c, d};     int [] keyarray = basearray.clone();      if(a > 9 || b > 9 || c > 9 || d > 9 || == 0 || b == 0 || c == 0 || d == 0){         system.out.println("you entered number greater 9 or enterered 0:");         main(null);         system.exit(0);     }      for(int = 0; < 2; i++){         for(int j = 0; j < basearray.length; j++){             if(i == 1){             basearray = keyarray.clone();             int temp = basearray[0];             basearray[0] = basearray[3];             basearray[3] = temp;             j = basearray.length - 1;             }             else if (i == 2){             basearray = keyarray.clone();             int temp = basearray[1];             basearray[1] = basearray[0];             basearray[0] = temp;             temp = basearray[2];             basearray[2] = basearray[3];             basearray[3] = temp;             j = basearray.length - 1;             }else{             int temp = basearray[j];             basearray[j] = basearray[basearray.length - (1+j)];             basearray[basearray.length - (1+j)] = temp; 

this misses lot of possible combinations

here 1 way it. use permutation method on both arithmetic operations , numbers.

once have inputs the users turn them string:

void perm(std::string str, std::vector<std::string> &vec){    perm("", str, vec); }  void perm(std::string prefix, std::string str, std::vector<std::string &vec){    int n = str.length();    if( n == 0 ) vec.push_back(str);    for(int = 0; < n; i++){       perm(pre+ str[i], str.substr(0,i) + str.substr(i+1,n), vec);    } } 

now have permutation method lets have string:1234 input can permutate string 2134 3214 1243 ... etc

you can same thing arithmetic operations i.e +-*/

or can combine operation:

std::vector<std::string> vec; perm("1234" + "*-/+", vec); 

now have vector permuations of numbers , operations. can prune list accept number operation number operations. can done regex:

 `\d[*|+|-|/]\d[*|+|-|/]\d[*|+|-|/]\d[*|+|-|/]`  disregard last operation. 

now have permutations strings. create logic turn ints

note:
there wasted space here method should work.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -