随机参数使用System()

Randomized Parameters Using System()?

本文关键字:System 参数 随机      更新时间:2023-10-16

我正在尝试使用system()调用程序时为miniat尝试一些随机参数。我以前从来没有做过这样的事情,我不得不承认我很迷路。

例如,我可以这样做:

system("minisat -luby -rinc=1.5 <dataset here>")

如何将其随机化为-luby-no-luby,并将-rinc1.5值随机化?

system只是一个接受c风格字符串作为参数的普通函数。你可以自己构造字符串

bool luby = true;
double rinc = 1.5;
system((std::string("minisat -")+(luby?"luby":"no-luby")+" -rinc="+std::to_string(rinc)).c_str());

您需要使用变量动态构造命令。

bool luby = true;  // if you want -no-luby, set it to be false
double rinc = 1.5;  // set it to be other values
char command[1024];
std::string luby_str = (luby ? "luby" : "no-luby");
std::snprintf(command, sizeof(command), "minisat -%s -rinc=%f", luby_str.c_str(), rinc);
system(command);

就像@RemyLebeau指出的,c++风格应该更好。

std::string command;
std::ostringstream os;
os << "minisat -" << luby_str << " -rinc=" << rinc;
system(command.c_str());

在这里,您可以尝试使用像这样的随机字符串命令生成器来创建一个随机命令:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include <string>
std::string getCommand()
{
    std::string result = "minisat ";
    srand(time(0));
    int lubyflag = rand() % 2; //Not the best way to generate random nums
                               //better to use something from <random>
    if (lubyflag == 1)
    {
        result += "-luby ";
    } else 
    {
        result += "-no-luby ";
    }
    double lower_bound = 0; //Now were using <random>
    double upper_bound = 2; //Or whatever range 
    std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
    std::default_random_engine re;
    double rinc_double = unif(re);
    result += "-rinc=" + rinc_double;
    return result;
}
int main()
{
    std::string command = getCommand();
    system(command.c_str());
}

如果你想要所有的控制权,这样做:

bool flaga = false;
double valueb = 1.5;
system(std::string("ministat " + ((flaga) ? "-luby " : "-no-luby ") + 
    "rinc= " + std::to_string(valueb)).c_str());