Let Set B={4,2,8,6,5};
how to write below sets in CPLEX
Set E={p| for all b∈B , p=random integer in range(0,b)}
Set F= {Set of all E} (need multiple sets of E using varying random integers p)
{int} B={4,2,8,6,5};
range r=1..4;
{int} E[i in r]={rand(b) | b in B};
tuple f
{
{int} s;
}
{f} F={<E[i]> | i in r};
execute
{
writeln(F);
}
gives
{<{0 2 4}> <{3 1 0 5}> <{0 5 2 3}> <{3 1 6 4}>}
but could give other results (random) ....
Related
I want to write simple insertion sort function using fold_left but I also want to pass function that will specify order in my sort fun.
What I don't know, is how to pass it to fold_left..
let rec insert f l e =
match l with
| [] -> [e]
| h :: t -> if f e h then h :: insert f t e else e :: l;;
let insertion_sort f l = List.fold_left insert f [] l;;
let less x y = x < y;;
let result = insertion_sort less [2 ; 5 ; 1 ; 9 ; 7 ; -2 ; 0 ; 124];;
This what I am talking about but fold_left doesn't accept that solution.
When I make specialization of sort function then it works just fine.
let insertLess = insert less;;
let insertion_sortLess l = List.fold_left insertLess [] l;;
let result = insertion_sortLess [2 ; 5 ; 1 ; 9 ; 7 ; -2 ; 0 ; 124];;
# val result : int list = [124; 9; 7; 5; 2; 1; 0; -2]
List.fold_left insert f ... will apply insert and f as separate arguments to List.fold_left. What you want is List.fold (insert f) ..., which will apply f to insert, and then the result of that to List.fold_left.
Edit: In addition, you don't need to define less. You can pass > as a function directly by surrounding it in parentheses: insertion_sort (<) ...
I have three sets, say:
a=[1 1 1 1];
b=[2 2 2];
c=[3 3];
Now, I have to find out all unique combinations by taking 3 elements from all sets..
So in matlab, I can do it:
>> a=[1 1 1 1];
>> b=[2 2 2];
>> c=[3 3];
>> all=[a b c];
>> nchoosek(all,3)
>> unique(nchoosek(all,3),'rows')
The o/p is:
1 1 1
1 1 2
1 1 3
1 2 2
1 2 3
1 3 3
2 2 2
2 2 3
2 3 3
How to write the logic behind the program in pseudocode?
Here's how I would do it:
Create a dictionary of item counts.
Recurse on this dictionary k times, taking care not to pick items that are not or no longer in the pool.
When recursing, skip items that are smaller (by some criterion) than the current item in order to get a unique list.
In pseudocode:
function ucombok_rec(count, k, lowest)
{
if (k == 0) return [[]];
var res = [];
for (item in count):
if (item >= lowest && count[item] > 0) {
count[item]--;
var combo = ucombok_rec(count, k - 1, item);
for (c in combo) res ~= [[item] ~ c];
count[item]++;
}
return res;
}
function ucombok(s, k)
{
if (!s) return []; // nothing to do
var count = {};
var lowest = min(s); // min. value in set
for (item in s) count[item]++; // create item counts
return ucombok_rec(count, k, lowest); // recurse
}
In this code, [] denotes a list or vector, {} a dictionary or map and the tilde ~ means list concatenation. The count decrements and increments around the recursion remove an item temporarily from the item pool.
In your example, where the pool is made up of three lists, you' d call the function like this:
c = ucombok(a ~ b ~ c, 3)
So for the following sub string
1 2 3 4 5 6 7 8 9 10 11
a b c d a b c d a b x
Which is the prefix function? Me and one of my friends computed it and we have different results, mine is:
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 2
and his:
a b c d a b c d a b x
0 0 0 0 1 2 3 4 1 2 0
If I am wrong, why is that?
The prefix table should be:
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 0
so both versions given are not right.
For the last entry of your table
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 2
^
|
this one
to be correct, the suffix of length 2 of a b c d a b c d a b x which is b x would also have to be its length 2 prefix, which is a b instead.
In case of entries different from zero in the prefix table corresponding prefixes and suffixes have been marked in the table below:
a 0
a b 0
a b c 0
a b c d 0
a b c d a 1
-
=
a b c d a b 2
---
===
a b c d a b c 3
-----
=====
a b c d a b c d 4
-------
=======
a b c d a b c d a 5
---------
=========
a b c d a b c d a b 6
-----------
===========
a b c d a b c d a b x 0
My KMP function in java:
public int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
Result for prefix arrays:
[-1, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0]
Neither of your answers are correct. The prefix function or partial match table would be the following:
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 0
Your answer was correct upto index 10. But in the last index you have done something wrong. The reason why value of index 11 of partial match table would 0 is because there are no proper prefix which matches any proper suffix of the string upto index 11. Because all proper suffixes at this position will end with x and no proper prefix at this position will end with x.
If you have problem understanding what actually prefix function or partial index table means you can take a look into this document. It has a very good explanation. Hope it helps.
both of your answers are wrong. correct one will be
a b c d a b c d a b x
0 0 0 0 1 2 3 4 5 6 0
Let's say I have the following variables defined:
a = 6
b = 4
c = 0
I want to assign the first non-zero value to another variable, but in reverse order (c -> b -> a). I originally tried d = c || b || a, but that still resulted in 0. Is there a one-liner way of doing this?
Use detect
[c,b,a].detect { |i| i > 0 }
[c,b,a].select { |i| i > 0 }.first => 4
Note
This is not a REBOL-specific question. You can answer it in any language.
Background
The REBOL language supports the creation of domain-specific languages known as "dialects" in REBOL parlance. I've created such a dialect for list comprehensions, which aren't natively supported in REBOL.
A good cartesian product algorithm is needed for list comprehensions.
The Problem
I've used meta-programming to solve this, by dynamically creating and then executing a sequence of nested foreach statements. It works beautifully. However, because it's dynamic, the code is not very readable. REBOL doesn't do recursion well. It rapidly runs out of stack space and crashes. So a recursive solution is out of the question.
In sum, I want to replace my meta-programming with a readable, non-recursive, "inline" algorithm, if possible. The solution can be in any language, as long as I can reproduce it in REBOL. (I can read just about any programming language: C#, C, C++, Perl, Oz, Haskell, Erlang, whatever.)
I should stress that this algorithm needs to support an arbitrary number of sets to be "joined", since list comprehension can involve any number of sets.
3 times Faster and less memory used (less recycles).
cartesian: func [
d [block! ]
/local len set i res
][
d: copy d
len: 1
res: make block! foreach d d [len: len * length? d]
len: length? d
until [
set: clear []
loop i: len [insert set d/:i/1 i: i - 1]
res: change/only res copy set
loop i: len [
unless tail? d/:i: next d/:i [break]
if i = 1 [break]
d/:i: head d/:i
i: i - 1
]
tail? d/1
]
head res
]
How about something like this:
#!/usr/bin/perl
use strict;
use warnings;
my #list1 = qw(1 2);
my #list2 = qw(3 4);
my #list3 = qw(5 6);
# Calculate the Cartesian Product
my #cp = cart_prod(\#list1, \#list2, \#list3);
# Print the result
foreach my $elem (#cp) {
print join(' ', #$elem), "\n";
}
sub cart_prod {
my #sets = #_;
my #result;
my $result_elems = 1;
# Calculate the number of elements needed in the result
map { $result_elems *= scalar #$_ } #sets;
return undef if $result_elems == 0;
# Go through each set and add the appropriate element
# to each element of the result
my $scale_factor = $result_elems;
foreach my $set (#sets)
{
my $set_elems = scalar #$set; # Elements in this set
$scale_factor /= $set_elems;
foreach my $i (0 .. $result_elems - 1) {
# Calculate the set element to place in this position
# of the result set.
my $pos = $i / $scale_factor % $set_elems;
push #{$result[$i]}, $$set[ $pos ];
}
}
return #result;
}
Which produces the following output:
1 3 5
1 3 6
1 4 5
1 4 6
2 3 5
2 3 6
2 4 5
2 4 6
For the sake of completeness, Here's Robert Gamble's answer translated into REBOL:
REBOL []
cartesian: func [
{Given a block of sets, returns the Cartesian product of said sets.}
sets [block!] {A block containing one or more series! values}
/local
elems
result
row
][
result: copy []
elems: 1
foreach set sets [
elems: elems * (length? set)
]
for n 0 (elems - 1) 1 [
row: copy []
skip: elems
foreach set sets [
skip: skip / length? set
index: (mod to-integer (n / skip) length? set) + 1 ; REBOL is 1-based, not 0-based
append row set/(index)
]
append/only result row
]
result
]
foreach set cartesian [[1 2] [3 4] [5 6]] [
print set
]
; This returns the same thing Robert Gamble's solution did:
1 3 5
1 3 6
1 4 5
1 4 6
2 3 5
2 3 6
2 4 5
2 4 6
Here is a Java code to generate Cartesian product for arbitrary number of sets with arbitrary number of elements.
in this sample the list "ls" contains 4 sets (ls1,ls2,ls3 and ls4) as you can see "ls" can contain any number of sets with any number of elements.
import java.util.*;
public class CartesianProduct {
private List <List <String>> ls = new ArrayList <List <String>> ();
private List <String> ls1 = new ArrayList <String> ();
private List <String> ls2 = new ArrayList <String> ();
private List <String> ls3 = new ArrayList <String> ();
private List <String> ls4 = new ArrayList <String> ();
public List <String> generateCartesianProduct () {
List <String> set1 = null;
List <String> set2 = null;
ls1.add ("a");
ls1.add ("b");
ls1.add ("c");
ls2.add ("a2");
ls2.add ("b2");
ls2.add ("c2");
ls3.add ("a3");
ls3.add ("b3");
ls3.add ("c3");
ls3.add ("d3");
ls4.add ("a4");
ls4.add ("b4");
ls.add (ls1);
ls.add (ls2);
ls.add (ls3);
ls.add (ls4);
boolean subsetAvailabe = true;
int setCount = 0;
try{
set1 = augmentSet (ls.get (setCount++), ls.get (setCount));
} catch (IndexOutOfBoundsException ex) {
if (set1 == null) {
set1 = ls.get(0);
}
return set1;
}
do {
try {
setCount++;
set1 = augmentSet(set1,ls.get(setCount));
} catch (IndexOutOfBoundsException ex) {
subsetAvailabe = false;
}
} while (subsetAvailabe);
return set1;
}
public List <String> augmentSet (List <String> set1, List <String> set2) {
List <String> augmentedSet = new ArrayList <String> (set1.size () * set2.size ());
for (String elem1 : set1) {
for(String elem2 : set2) {
augmentedSet.add (elem1 + "," + elem2);
}
}
set1 = null; set2 = null;
return augmentedSet;
}
public static void main (String [] arg) {
CartesianProduct cp = new CartesianProduct ();
List<String> cartesionProduct = cp.generateCartesianProduct ();
for (String val : cartesionProduct) {
System.out.println (val);
}
}
}
use strict;
print "#$_\n" for getCartesian(
[qw(1 2)],
[qw(3 4)],
[qw(5 6)],
);
sub getCartesian {
#
my #input = #_;
my #ret = map [$_], #{ shift #input };
for my $a2 (#input) {
#ret = map {
my $v = $_;
map [#$v, $_], #$a2;
}
#ret;
}
return #ret;
}
output
1 3 5
1 3 6
1 4 5
1 4 6
2 3 5
2 3 6
2 4 5
2 4 6
EDIT: This solution doesn't work. Robert Gamble's is the correct solution.
I brainstormed a bit and came up with this solution:
(I know most of you won't know REBOL, but it's a fairly readable language.)
REBOL []
sets: [[1 2 3] [4 5] [6]] ; Here's a set of sets
elems: 1
result: copy []
foreach set sets [elems: elems * (length? set)]
for n 1 elems 1 [
row: copy []
foreach set sets [
index: 1 + (mod (n - 1) length? set)
append row set/(index)
]
append/only result row
]
foreach row result [
print result
]
This code produces:
1 4 6
2 5 6
3 4 6
1 5 6
2 4 6
3 5 6
(Upon first reading the numbers above, you may think there are duplicates. I did. But there aren't.)
Interestingly, this code uses almost the very same algorithm (1 + ((n - 1) % 9) that torpedoed my Digital Root question.