Given a set of letters, say from A.. F, how can one generate a combination of these letters for a specific length. i.e for length 4, generate all string containing these letters {AAAA, ABCD, ...} (duplicates included). I am not able to understand how to come out with a code that does it.This is pertaining to the Mastermind game that I am trying to simulate. Is there any algorithm to perform this generation.
regards,
darkie
There is an algorithm called Heap's Algorithm for generating permutations. This might suit your purposes. I found an example implementation here
I'm not sure what the name would be of such an algorithm, but it is a recursive one. That is, have a method that figures out one character, and simply keep calling itself until you're at the desired length of string that you want, then start filling in your array. Here's some sample C# code that should help:
public void GetPermutations()
{
string currentPrefix = ""; // Just a starting point
int currentLength = 1; // one-based
int desiredLength = 4; // one-based
string alphabet = "ABCDEF"; // Characters to build permutations from
List<string> permutations = new List<string>();
FillPermutations(currentPrefix, currentLength, alphabet, desiredLength, permutations);
}
public void FillPermutations(string currentPrefix, int currentLength, string alphabet, int desiredLength, List<string> permutations)
{
// If we're not at the desired depth yet, keep calling this function recursively
// until we attain what we want.
for (int i = 0; i < alphabet.Length; i++)
{
string currentPermutation = currentPrefix + alphabet[i].ToString();
if (currentLength < desiredLength)
{
// Increase current length by one and recurse. Current permutation becomes new prefix
int newCurrentLength = currentLength + 1;
FillPermutations(currentPermutation, newCurrentLength, alphabet, desiredLength, permutations);
}
else
{
// We're at the desired length, so add this permutation to the list
permutations.Add(currentPermutation);
}
}
}
Related
my question is related to my previous question. I should make some change in my code. I have a number of nodes between 1 to 100 in the CSV file. I create another CSV file and generate 20 random numbers between the 100 nodes and called them demand points. Each of this demand point has specific demands which are the randomly generate numbers between 1 to 10. I want to read this demand points(the indexes) and their weights. this is the first part of my question? how can I read this?
After that, I need to have a distance between each of these demand points and all nodes. I don't how can I just read the indexes of demand points and calculate the distance between them and all the nodes.
Based on the code that I provided, I need the indexes of demand points for a lot of places. My main problem is that I don't know how should I get these indexes in Cplex through the CSV file.
The demand points with their demands picture is:
first column is demandpointindex and second column in their demands
this file has 200 rows
I tried this code for reading the demand points:
tuple demands
{
int demandpoint;
int weight;
}
{demands} demand={};
execute
{
var f=new IloOplInputFile("weight.csv");
while (!f.eof)
{
var data = f.readline().split(",");
if (ar.length==2)
demand.add(Opl.intValue(ar[0]),Opl.intValue(ar[1]));
}
f.close();
}
execute
{
writeln(demand);
}
but it's not true.
int n=100;
int p=5;
tuple demands
{
int demandpointindex;
int weight;
}
{demands} demand={};
execute
{
var f=new IloOplInputFile("weight.csv");
while (!f.eof)
{
var data = f.readline().split(",");
if (ar.length==2)
demand.add(Opl.intValue(ar[0]),Opl.intValue(ar[1]));
}
f.close();
}
execute
{
writeln(demand);
}
float d[demandpointindexes][facilities];
execute {
var f = new IloOplInputFile("test1.csv");
while (!f.eof) {
var data = f.readline().split(",");
if (data.length == 3)
d[Opl.intValue(data[0])][Opl.intValue(data[1])] = Opl.floatValue(data[2]);
}
writeln(d);
}
dvar boolean x[demandpointindexe][facilities];
...
I hope I got your explanation right. Assume you have a file weight.csv like this:
1,2,
3,7,
4,9,
Here the first item in each row is the index of a demand point, the second item is its weight. Then you can parse this as before using this scripting block:
tuple demandpoint {
int index;
int weight;
}
{demandpoint} demand={};
execute {
var f = new IloOplInputFile("weight.csv");
while (!f.eof) {
var data = f.readline().split(",");
if (data.length == 3)
demand.add(Opl.intValue(data[0]), Opl.intValue(data[1]));
}
writeln(demand);
}
Next you can create a set that contains the indeces of all the demand points:
{int} demandpoints = { d.index | d in demand };
Assume file test1.csv looks like this
1,1,0,
1,2,5,
1,3,6,
1,4,7,
3,1,1,
3,2,1.5,
3,3,0,
3,4,3.5,
4,1,1,
4,2,1.5,
4,3,1.7,
4,4,0,
Here the first item is a demand point index, the second item is a facility index and the third item is the distance between first and second item. Note that there are no lines that start with 2 since there is no demand point with index 2 in weight.csv. Also note that I assume only 4 facilities here (to keep the file short). You can read the distance between demand points and facitilies as follows:
range facilities = 1..4;
float d[demandpoints][facilities];
execute {
var f = new IloOplInputFile("test1.csv");
while (!f.eof) {
var data = f.readline().split(",");
if (data.length == 4)
d[Opl.intValue(data[0])][Opl.intValue(data[1])] = Opl.floatValue(data[2]);
}
writeln(d);
}
The full script (including a dummy objective and constraints so that it can be run) looks:
tuple demandpoint {
int index;
int weight;
}
{demandpoint} demand={};
execute {
var f = new IloOplInputFile("weight.csv");
while (!f.eof) {
var data = f.readline().split(",");
if (data.length == 3)
demand.add(Opl.intValue(data[0]), Opl.intValue(data[1]));
}
writeln(demand);
}
// Create a set that contains all the indeces of demand points
// as read from weight.csv
{int} demandpoints = { d.index | d in demand };
range facilities = 1..4;
float d[demandpoints][facilities];
execute {
var f = new IloOplInputFile("test1.csv");
while (!f.eof) {
var data = f.readline().split(",");
if (data.length == 4)
d[Opl.intValue(data[0])][Opl.intValue(data[1])] = Opl.floatValue(data[2]);
}
writeln(d);
}
minimize 0;
subject to {}
It prints
{<1 2> <3 7> <4 9>}
[[0 5 6 7]
[1 1.5 0 3.5]
[1 1.5 1.7 0]]
Be careful about how many commas you have in your csv! The code posted above assumes that each line ends with a comma. That is, each line has as many commas as it has fields. If the last field is not terminated by a comma then you have to adapt the parser.
If you have in test1.csv the distance between all the nodes then it makes sense to first read the data into an array float distance[facilities][facilities]; and then define the array d based on that as
float d[i in demandpoints][j in facilities] = distance[i][j];
Update for the more detailed specification you gave in the comments:
In order to handle the test1.csv you explained in the comments you could define a new tuple:
tuple Distance {
int demandpoint;
int facility;
float distance;
}
{Distance} distances = {};
and read/parse this exactly as you did parse the weight.csv file (with one additional field, of course).
Then you can create the distance matrix like so:
float d[i in I][j in J] = sum (dist in distances : dist.demandpoint == i && dist.facility == j) dist.distance;
Here I and J are the sets or ranges of demand points and facilities, respectively. See above for how you can get a set of all demand points defined in the tuple set. The created matrix will have an entry for each demandpoint/distance pair. The trick in the definition d is that there are two cases:
If a pair (i,j) is defined in test1.csv then the sum will match exactly one element in distances: the one that defines the distance between two points.
If a pair (i,j) is not defined in test1.csv then the sum will not match anything and the corresponding entry in the distance matrix will thus be 0.
An array(10^5 size) of 32-bit binary numbers is given, we're required to count the no. of ones for every bit of those numbers.
For example:
Array : {10101,1011,1010,1}
Counts : {1's place: 3, 2's place: 2, 3's place: 1, 4's place: 2, 5's place: 1}
No bit manipulation technique seems to satisfy the constraints to me.
Well, this should be solveable with two loops: one going over the array the other one masking the right bits. Running time should be not too bad for your constraints.
Here is a rust implementation (out of my head, not throughtfully tested):
fn main() {
let mut v = vec!();
for i in 1..50*1000 {
v.push(i);
}
let r = bitcount_arr(v);
r.iter().enumerate().for_each( |(i,x)| print!("index {}:{} ",i+1,x));
}
fn bitcount_arr(input:Vec<u32>) -> [u32;32] {
let mut res = [0;32];
for num in input {
for i in 0..31 {
let mask = 1 << i;
if num & mask != 0 {
res[i] += 1;
}
}
}
res
}
This can be done with transposed addition, though the array is a bit long for it.
To transpose addition, use an array of counters, but instead of using one counter for every position we'll use one counter for every bit of the count. So a counter that tracks for each position whether the count is even/odd, a counter that tracks for each position whether the count has a 2 in it, etc.
To add an element of the array into this, only half-add operations (& to find the new carry, ^ to update) are needed, since it's only a conditional increment: (not tested)
uint32_t counters[17];
for (uint32_t elem : array) {
uint32_t c = elem;
for (int i = 0; i < 17; i++) {
uint32_t nextcarry = counters[i] & c;
counters[i] ^= c;
c = nextcarry;
}
}
I chose 17 counters because log2(10^5) is just less than 17. So even if all bits are 1, the counters won't wrap.
To read off the result for bit k, take the k'th bit of every counter.
There are slightly more efficient ways that can add several elements of the array into the counters at once using some full-adds and duplicated counters.
UPDATE: I solved my problem (scroll down).
I'm writing a small C program and I want to do the following:
The program is connected to a mysql database (that works perfectly) and I want to do something with the data from the database. I get about 20-25 rows per query and I created my own struct, which should contain the information from each row of the query.
So my struct looks like this:
typedef struct {
int timestamp;
double rate;
char* market;
char* currency;
} Rate;
I want to pass an empty array to a function, the function should calculate the size for the array based on the returned number of rows of the query. E.g. there are 20 rows which are returned from a single SQL query, so the array should contain 20 objectes of my Rate struct.
I want something like this:
int main(int argc, char **argv)
{
Rate *rates = ?; // don't know how to initialize it
(void) do_something_with_rates(&rates);
// the size here should be ~20
printf("size of rates: %d", sizeof(rates)/sizeof(Rate));
}
How does the function do_something_with_rates(Rate **rates) have to look like?
EDIT: I did it as Alex said, I made my function return the size of the array as size_t and passed my array to the function as Rate **rates.
In the function you can access and change the values like (*rates)[i].timestamp = 123 for example.
In C, memory is either dynamically or statically allocated.
Something like int fifty_numbers[50] is statically allocated. The size is 50 integers no matter what, so the compiler knows how big the array is in bytes. sizeof(fifty_numbers) will give you 200 bytes here.
Dynamic allocation: int *bunch_of_numbers = malloc(sizeof(int) * varying_size). As you can see, varying_size is not constant, so the compiler can't figure out how big the array is without executing the program. sizeof(bunch_of_numbers) gives you 4 bytes on a 32 bit system, or 8 bytes on a 64 bit system. The only one that know how big the array is would be the programmer. In your case, it's whoever wrote do_something_with_rates(), but you're discarding that information by either not returning it, or taking a size parameter.
It's not clear how do_something_with_rates() was declared exactly, but something like: void do_something_with_rates(Rate **rates) won't work as the function has no idea how big rates is. I recommend something like: void do_something_with_rates(size_t array_size, Rate **rates). At any rate, going by your requirements, it's still a ways away from working. Possible solutions are below:
You need to either return the new array's size:
size_t do_something_with_rates(size_t old_array_size, Rate **rates) {
Rate **new_rates;
*new_rates = malloc(sizeof(Rate) * n); // allocate n Rate objects
// carry out your operation on new_rates
// modifying rates
free(*rates); // releasing the memory taken up by the old array
*rates = *new_rates // make it point to the new array
return n; // returning the new size so that the caller knows
}
int main() {
Rate *rates = malloc(sizeof(Rate) * 20);
size_t new_size = do_something_with_rates(20, &rates);
// now new_size holds the size of the new array, which may or may not be 20
return 0;
}
Or pass in a size parameter for the function to set:
void do_something_with_rates(size_t old_array_size, size_t *new_array_size, Rate **rates) {
Rate **new_rates;
*new_rates = malloc(sizeof(Rate) * n); // allocate n Rate objects
*new_array_size = n; // setting the new size so that the caller knows
// carry out your operation on new_rates
// modifying rates
free(*rates); // releasing the memory taken up by the old array
*rates = *new_rates // make it point to the new array
}
int main() {
Rate *rates = malloc(sizeof(Rate) * 20);
size_t new_size;
do_something_with_rates(20, &new_size, &rates);
// now new_size holds the size of the new array, which may or may not be 20
return 0;
}
Why do I need to pass the old size as a parameter?
void do_something_with_rates(Rate **rates) {
// You don't know what n is. How would you
// know how many rate objects the caller wants
// you to process for any given call to this?
for (size_t i = 0; i < n; ++i)
// carry out your operation on new_rates
}
Everything changes when you have a size parameter:
void do_something_with_rates(size_t size, Rate **rates) {
for (size_t i = 0; i < size; ++i) // Now you know when to stop
// carry out your operation on new_rates
}
This is a very fundamental flaw with your program.
I want to also want the function to change the contents of the array:
size_t do_something_with_rates(size_t old_array_size, Rate **rates) {
Rate **new_rates;
*new_rates = malloc(sizeof(Rate) * n); // allocate n Rate objects
// carry out some operation on new_rates
Rate *array = *new_rates;
for (size_t i = 0; i < n; ++i) {
array[i]->timestamp = time();
// you can see the pattern
}
return n; // returning the new size so that the caller knows
}
sizeof produces a value (or code to produce a value) of the size of a type or the type of an expression at compile time. The size of an expression can therefore not change during the execution of the program. If you want that feature, use a variable, terminal value or a different programming language. Your choice. Whatever. C's better than Java.
char foo[42];
foo has either static storage duration (which is only partially related to the static keyword) or automatic storage duration.
Objects with static storage duration exist from the start of the program to the termination. Those global variables are technically called variables declared at file scope that have static storage duration and internal linkage.
Objects with automatic storage duration exist from the beginning of their initialisation to the return of the function. These are usually on the stack, though they could just as easily be on the graph. They're variables declared at block scope that have automatic storage duration and internal linkage.
In either case, todays compilers will encode 42 into the machine code. I suppose it'd be possible to modify the machine code, though that several thousands of lines you put into that task would be much better invested into storing the size externally (see other answer/s), and this isn't really a C question. If you really want to look into this, the only examples I can think of that change their own machine code are viruses... How are you going to avoid that antivirus heuristic?
Another option is to encode size information into a struct, use a flexible array member and then you can carry both the array and the size around as one allocation. Sorry, this is as close as you'll get to what you want. e.g.
struct T_vector {
size_t size;
T value[];
};
struct T_vector *T_make(struct T_vector **v) {
size_t index = *v ? (*v)->size++ : 0, size = index + 1;
if ((index & size) == 0) {
void *temp = realloc(*v, size * sizeof *(*v)->value);
if (!temp) {
return NULL;
}
*v = temp;
// (*v)->size = size;
*v = 42; // keep reading for a free cookie
}
return (*v)->value + index;
}
#define T_size(v) ((v) == NULL ? 0 : (v)->size)
int main(void) {
struct T_vector *v = NULL; T_size(v) == 0;
{ T *x = T_make(&v); x->value[0]; T_size(v) == 1;
x->y = y->x; }
{ T *y = T_make(&v); x->value[1]; T_size(v) == 2;
y->x = x->y; }
free(v);
}
Disclaimer: I only wrote this as an example; I don't intend to test or maintain it unless the intent of the example suffers drastically. If you want something I've thoroughly tested, use my push_back.
This may seem innocent, yet even with that disclaimer and this upcoming warning I'll likely see a comment along the lines of: Each successive call to make_T may render previously returned pointers invalid... True, and I can't think of much more I could do about that. I would advise calling make_T, modifying the value pointed at by the return value and discarding that pointer, as I've done above (rather explicitly).
Some compilers might even allow you to #define sizeof(x) T_size(x)... I'm joking; don't do this. Do it, mate; it's awesome!
Technically we aren't changing the size of an array here; we're allocating ahead of time and where necessary, reallocating and copying to a larger array. It might seem appealing to abstract allocation away this way in C at times... enjoy :)
So for a homework assignment we had to make a program that converted a number from one base to another (i.e. 110 in base 2 to 6 in base 10). I asked my friend how he did his because I was having trouble and he just sent me his code and nothing else. Can someone explain the logic of this code so that I can make my own program and actually understand how to do this problem. Thanks!
import java.util.*;
public class Base_Converter {
public static final String value = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String args[]){
int x, y;
String num, base10 = "";
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number you want to convert.");
num = scan.nextLine();
num = num.toUpperCase();
System.out.println("What base is it in?");
x = scan.nextInt();
System.out.println("What base do you want to convert it to?");
y = scan.nextInt();
if(x <= 36 && y <= 36 && x > 1 && y > 1){
base10 = toBase10(num,x);
num = newBase(base10,y);
System.out.println(num);
}
}
public static String toBase10(String num, int from){
long total = 0;
int counter = num.length();
char[] stringArray = num.toCharArray();
for(char w : stringArray){
counter--;
total += value.indexOf(w)*Math.pow(from,counter);
}
return String.valueOf(total);
}
public static String newBase(String num, int to){
String total = "";
int current = 0;
while(Integer.valueOf(num) > 0){
current = Integer.valueOf(num)%to;
total = value.charAt(current)+total;
num = String.valueOf(Integer.valueOf(num)/to);
}
return total;
}
}
I think you should be focusing not on what your friend's code does, but instead with how to do the assignment yourself, because I think your problems lie with a lack of understanding on your part. Instead of leaving you high and dry though I'll walk you through some of the specifics of base-conversion.
First, read user input. It looks like you're using Java, so just use a scanner to do this. At minimum you'll want to read the number you're converting, what base it is in, and what base the output will be in.
Next, we want to convert the number. You could directly convert numbers to each other (i.e. converting base 2 to base 8) but that requires more brainpower than I am willing to offer right now. Instead, I would suggest always first converting the user-inputted number to base 10 (much like your friend did). So how do we convert a number of an unknown base to base 10?
So let's break down how a number is represented: lets say we have the number 234 in base ten. This is equivalent to 4*10^0 + 3*10^1 + 2*10^2 or 4 + 30 + 200 = 234. You can use this same conversion for any other numbers. I.E. if the number is 1763 in base 8, the value in base 10 will be 3*8^0 + 6*8^1 + 7*8^2 + 1*8^3 or 3 + 48 + 448 + 512 = 1011 base 10(try entering 1763 here for proof. So to convert to decimal, you just need to see to multiply each individual number time your base to the power of its place minus 1. For example, since 1 is the fourth number in the 1763 you multiply it times 8^(4-1). Since, you are reading a string from the user. You'll need to convert each character of the string to an integer using the ascii chart.
Now to convert from base ten to anything. Instead of multiplying, you just divide each value and write the remainder! I'll let someone else describe this procedure.
Now just store this new value as a string doing somethings like
String output = "";
output += newValue;
In computer science, just copying someone else's code is way more harmful than helpful. Hope this helps!
I have a problem to solve with Android, but it's really confusing.
Using the function below:
function accumulate(combiner, nullValue, list){
if(list.length == 0){
return nullValue;
}
var first = list.removeFirst();
return combiner(first, accumulate(combiner, nullValue, list));
}
Develop the function sumOfSquares which returns the sum of squares of a list (Example: 1² + 2² + 3²...)
sumOfSquares([1,2,3,4,5])
returns the number 55.
In this case, the function accumulate must be used. The variable "combiner" is a "pointer to a function". The implementation of the function "combiner" is part of the solution.
I have no problem with the basics, doing the sum of squares, etc, but the part "pointer to a function" really confused me.
If anyone can tell me which is the way to get to the answer, I will be thankful :)
I have done until the code below:
public class MainActivity extends Activity{
protected void onCreate(...){
....
List<Integer> list = new ArrayList<Integer>();
//Fill the list with values
long value = accumulate(sumOfSquares(list), 0, list);
//Show the value
}
private int sumOfSquares(List<Integer> list){
int sum = 0;
for(int i = 0; i < list.size(); i++){
sum += Math.pow(list.get(i), 2);
}
return sum;
}
private long accumulate(int combiner, long nullValue, List<Integer> list){
if(list.size() == 0){
return nullValue;
}
int first = list.get(0);
list.remove(0);
return combiner(first, accumulate(combiner, nullValue, list));
}
private long combiner(int first, int rest){
return first + rest;
}
}
In some languages, the notion of a pointer to a function makes sense, and you could write the code pretty much as you've given it in the example. Not in Java, though, which is what underlies Android. (Android is a bit of a weird choice for this, by the way...)
What you want to do in Java (without giving you the whole solution) is to define a
private int combiner(int first, int rest);
method that takes the first element of the list and the solution to the smaller problem defined by the rest of the list, and produces the answer from these two bits. In other words, if first is the first element, and rest is the sum of the squares of everything except the first element, what is the sum of the squares of the whole list (in terms of first and rest)?
Now your accumulate method does almost exactly what you've written out. It just removes the first element, recursively calls itself on the rest of the list, and returns the value of combining the first element with the result of the recursive call.
The nullValue is there to give you the sum of the squares of an empty list.
If you want to look up more of the details of the theory, you're basically doing functional programming but in an imperative language :)