I'm doing an OTSP Problem and it gives me "Problem has no primal feasible solution"
The problem is simple. The program deals with supplying customers using delivery vehicles, the program determines the optimal routes (short distances) to satisfy the demand of the clients, so that each delivery vehicle supplies the demand of the customers without exceeding its capacity.
set Rep; # Dealer vehicles
set Cli;
param cantCli;
param cantRep;
param dem { Cli };
param capacRep { Rep };
param coordxCli { Cli };
param coordyCli { Cli };
param distCli { i in Cli , j in Cli : i != j } := sqrt((coordxCli[i] - coordxCli[j])^2 + (coordyCli[i] - coordyCli[j])^2); # Distance
var X { i in Cli, j in Cli , k in Rep : i != j }, binary; # Variable of route (used arcs)
var u { i in Cli :i != 'rep' } >= 0; # To delete de subroutes
var visitRep { i in Cli , k in Rep },binary; # 1 if dealer vehicle k visit client i.
s.t. R1 { j in Cli , k in Rep : j != 'rep' } : sum { i in Cli : i != j } X[i,j,k] = 1; # Just enter 1 arc on each client
s.t. R2 { i in Cli , k in Rep : i != 'rep' } : sum { j in Cli : i != j } X[i,j,k] = 1; # Just 1 arc leaves each client
s.t. R3 { k in Rep } : sum { i in Cli , j in Cli : j == 'rep' and i != j } X[i,j,k] <= cantRep; # All the dealer vehicles must enter to the 'rep' (depot)
s.t. R4 { k in Rep } : sum { i in Cli , j in Cli : i == 'rep' and i != j } X[i,j,k] <= cantRep; # All the dealer vehicles must leave the 'rep' (depot)
s.t. R5 { i in Cli , j in Cli , k in Rep : i != 'rep' and j != 'rep' and i != j } : u[j] - u[i] + capacRep[k] * (1 - X[i,j,k]) >= 1; # Delete subroutes
s.t. R6 { i in Cli : i != 'rep' } : sum { k in Rep } visitRep[i,k] = 1; # Each client is visited only once
s.t. R7 { k in Rep } : sum { i in Cli : i!= 'rep' } dem[i] <= capacRep[k]; # The capacity of the dealer vehicle must not be exceeded
minimize Z { k in Rep } : sum { i in Cli , j in Cli : i != j } distCli[i,j] * X[i,j,k];
solve;
for { k in Rep , i in Cli, j in Cli : i != j and X[i,j,k] == 1 } {
printf " %s %5s %5s %8s \n",i,j,k,X[i,j,k];
}
data;
param cantCli := 8;
param cantRep := 3;
param : Rep : capacRep := # The dealer Vehicles
'Rep1' 80
'Rep2' 150
'Rep3' 100;
# Clients and their choords
param : Cli : coordxCli coordyCli dem :=
'rep' 20 0 40
'c1' 40 200 30
'c2' 150 -50 20
'c3' 60 100 50
'c4' 80 150 20
'c5' 120 50 30
'c6' 150 100 30
'c7' 200 120 10
'c8' 250 50 40;
end;
Note: At the moment the code is for TSP + Bus routing , but the objective is OTSP + Bus routing.
Here is the code. Thank you in advance
Its your constraint Number 7 s.t. R7 which leads your problem into infeasibility.
The sum of all Client demands should be lower or equal to the respective Car-Capacity.
While the summed up demand is 230 the maximum capacity of the vehicles is limited to 80, 100 and 150. That seems to be infeasible.
Related
Due to this fact:
If a map entry is created during iteration, that entry may be produced
during the iteration or may be skipped. The choice may vary for each
entry created and from one iteration to the next.
It's not safe to add key-values to map during iteration:
var m = make(map[string]int)
m["1"] = 1
m["2"] = 2
m["3"] = 3
for k, v := range m {
if strings.EqualFold( "2", k){
m["4"] = 4
}
fmt.Println(k, v)
}
Sometimes "4" key is produced, sometimes not.
What is the workaround to make it always produced?
Create another map with the items you want to add to the original map, and after the iteration, you merge them.
var m = make(map[string]int)
m["1"] = 1
m["2"] = 2
m["3"] = 3
var n = make(map[string]int)
for k := range m {
if strings.EqualFold("2", k) {
n["4"] = 4
}
}
for k, v := range n {
m[k] = v
}
for _, v := range m {
fmt.Println(v)
}
Can you please help me with this excercise? I do not know much about math algorithms and even less about R language. Thank you.
A program reads an integer from the user. If the value entered by the user is less than 2 then program should display an error. Otherwise program should display the prime numbers that can be multiplied together to compute n, with one factor appearing on each line. For example:
The prime factors of 72 are: 2, 2, 2, 3, 3
I have this code in C that calculates the prime numbers
#include <stdio.h>
int main()
{
int i, j, num, isPrime;
/* Input a number from user */
printf("Enter any number to print Prime factors: ");
scanf("%d", &num);
printf("All Prime Factors of %d are: \n", num);
/* Find all Prime factors */
for(i=2; i<=num; i++)
{
/* Check 'i' for factor of num */
if(num%i==0)
{
/* Check 'i' for Prime */
isPrime = 1;
for(j=2; j<=i/2; j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/* If 'i' is Prime number and factor of num */
if(isPrime==1)
{
printf("%d, ", i);
}
}
}
return 0;
}
But output is only this
All Prime Factors of 72 are: 2, 3
Instead of this:
2, 2, 2, 3, 3
I also do not have a clue how to translate this to R.
Using Recursion
prime_factors <- function(x, i=2, factors = NULL){
if(x<i) factors
else if(! x %% i) prime_factors(x/i, i, c(factors, i))
else prime_factors(x, i+1, factors)
}
prime_factors(72)
[1] 2 2 2 3 3
Using While loop:
prime_factors_Loop <- function(x){
factors = c()
i = 2
while(x >= i){
if(! x %% i) {
factors <- c(factors, i)
x <- x/i
i <- i - 1
}
i <- i + 1
}
factors
}
prime_factors_Loop(72)
[1] 2 2 2 3 3
Using packages
First, install the CRAN package numbers on your computer.
install.packages("numbers")
Now, load the package in your R session and get the prime factors.
library(numbers)
primeFactors(600851475143)
This is what I wrote some time back, it may require some improvement though. Updated it according to your requirement.
get_prime_factors <- function() {
num <- as.numeric(readline(prompt="Enter number: " ))
n <- num
if (n > 2) {
numvec <- numeric()
while(n %% 2 == 0){
numvec = c(numvec, 2)
n = n/2
}
i = 3
while(n != 1) {
while(n %% i == 0) {
numvec = c(numvec, i)
n = n/i
}
i = i + 2
}
sprintf("All Prime Factors of %d are:%s", num, paste0(sort(numvec), collapse = ","))
}
else {
stop("Try a bigger number")
}
}
Running with few sample examples :
get_prime_factors()
Enter number: 100
#[1] "All Prime Factors of 100 are : 2,2,5,5"
get_prime_factors()
Enter number: 72
#[1] "All Prime Factors of 72 are : 2,2,2,3,3"
get_prime_factors()
Enter number: -9
Error in get_prime_factors() : Try a bigger number
I am trying to implement the fizz buzz problem using maps in go lang. However, this code requires improvement in its working. It keeps on printing undesired and redundant results due to the for loop that iterates over the map. I tried a lot of solutions but failed. Is it feasible without using any help of a slice of keys?
package main
import "fmt"
func fizzbuzz(i int) {
myMap:= make(map[int]string)
myMap[3] = "fizz"
myMap[5] = "buzz"
myMap[15] = "fizzbuzz"
for k,v:= range myMap{
if i%k==0 {fmt.Printf("%v \n",v)
} else {fmt.Printf("%v \n",i)}
}
}
func main() {
for i:=1;i<10000;i++ {
fizzbuzz(i)
}
}
With a map
With your rule set, the entire for loop should be to decide if the i number is to be replaced with a word. But you emit a result in each iteration. At most one result should be emitted by the for. If i is not dividable by any of the keys, then i should be emitted.
Keys may be multiples of others (e.g. 15 = 3 * 5), and if the i number is dividable by such a key, we want to emit the word associated with the greatest key. So the for loop should not emit anything, because if you find a good key, there may be a greater one. So the loop should just find the greatest good key.
After the loop you can check if any good key was found, and if so, emit the word associated with it, else emit the number:
var rules = map[int]string{
3: "fizz",
5: "buzz",
15: "fizzbuzz",
}
func fizzbuzz(i int) {
max := -1
for k := range rules {
if i%k == 0 && k > max {
max = k
}
}
if max < 0 {
fmt.Println(i)
} else {
fmt.Println(rules[max])
}
}
func main() {
for i := 1; i < 100; i++ {
fizzbuzz(i)
}
}
Output (try it on the Go Playground):
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz
fizz
...
With an ordered slice
You can get better performance if the rules are sorted by the keys descending, in which case you can check the keys in that order (greatest first), and then the first that qualifies will be the greatest. So you can emit the result immediately, and return.
If execution continues after the loop, we know no keys were good, we can emit the i number:
var rules = []struct {
n int
word string
}{
{15, "fizzbuzz"},
{5, "buzz"},
{3, "fizz"},
}
func fizzbuzz(i int) {
for _, rule := range rules {
if i%rule.n == 0 {
fmt.Println(rule.word)
return
}
}
fmt.Println(i)
}
Try this on the Go Playground.
General (excluding multiples from rules)
Although you started with a rule set where 15 = 3 * 5 was included in the rules, this should not be the case; you should only list 3 and 5, 15 should be implicit.
In this case, you have to check all the rules of course, because each good key should emit a word. And you have to remember if a good key was found, and only emit the i number otherwise.
This is how you can do it:
var rules = []struct {
n int
word string
}{
{3, "fizz"},
{5, "buzz"},
}
func fizzbuzz(i int) {
found := false
for _, rule := range rules {
if i%rule.n == 0 {
found = true
fmt.Print(rule.word)
}
}
if !found {
fmt.Print(i)
}
fmt.Println()
}
Try it on the Go Playground.
Note: in this solution you could also use a map instead of the slice; the reason why I used a slice is so that in case of multiple good keys the emitted words will always be in the same order (defined by increasing keys), as iteration order of keys in a map is not defined. For details, see Why can't Go iterate maps in insertion order?
As mentioned, the order of items in a map, is not deterministic in Go. Though here are some simple solutions:
func fizzbuzz(n int) {
for i := 1; i <= n; i++ {
switch {
case i%15 == 0:
println("fizzbuzz")
case i%5 == 0:
println(`buzz`)
case i%3 == 0:
println(`fizz`)
default:
println(i)
}
}
}
func fizzbuzzList(n int) []string {
var res []string
for i := 1; i <= n; i++ {
switch {
case i%15 == 0:
res = append(res, `fizzbuzz`)
case i%5 == 0:
res = append(res, `buzz`)
case i%3 == 0:
res = append(res, `fizz`)
default:
res = append(res, strconv.Itoa(i))
}
}
return res
}
func fizzbuzzLazy(n int) chan string {
var res = make(chan string)
go func() {
for i := 1; i <= n; i++ {
switch {
case i%15 == 0:
res <- `fizzbuzz`
case i%5 == 0:
res <- `buzz`
case i%3 == 0:
res <- `fizz`
default:
res <- strconv.Itoa(i)
}
}
close(res)
}()
return res
}
And usage:
fizzbuzz(20)
for _, v := range fizzbuzzList(20) {
println(v)
}
for v := range fizzbuzzLazy(20) {
println(v)
}
I'm trying to generate incremental combinations from a string, like:
// for "23405"
2
3
4
5
23
34
40
05
234
340
405
2340
3405
23405
I'm doing it with nested loops:
str := "23405"
for i := 0; i <= len(str); i++ {
for j := 0; j <= i; j++ {
fmt.Println(str[j:i])
}
}
Is it possible to do the same with recursive function? I'm writing it with go but an example in any language would be helpful. Here's the playground link.
Here's my attempt of recursion: https://repl.it/ElYY/9
package main
import "fmt"
func reverse(str string, length int, i int) {
if len(str) > length+i && length > 0 {
fmt.Println(str[i:length+i])
reverse(str, length, i+1)
} else if len(str) == length+i && length > 0 {
fmt.Println(str[i:length+i])
reverse(str, length-1, 0)
}
}
func recIterate(str string, length int, i int) {
if length > i {
fmt.Println(str[i:len(str)-length+i+1])
recIterate(str, length, i+1)
} else if length == i && length > 0{
recIterate(str, length-1, 0)
}
}
func main() {
str := "234051234"
recIterate(str, len(str), 0)
// reverse(str, len(str), 0)
}
Shout out to nexus66 for helping~
I've got the following grid of numbers centered around 0 and increasing in spiral. I need an algorithm which would receive number in spiral and return x; y - numbers of moves how to get to that number from 0. For example for number 9 it would return -2; -1. For 4 it would be 1; 1.
25|26|... etc.
24| 9|10|11|12
23| 8| 1| 2|13
22| 7| 0| 3|14
21| 6| 5| 4|15
20|19|18|17|16
This spiral can be slightly changed if it would help the algorithm to be better.
Use whatever language you like. I would really appreciate mathematical explanation.
Thank you.
First we need to determine which cycle (distance from center) and sector (north, east, south or west) we are in. Then we can determine the exact position of the number.
The first numbers in each cycle is as follows: 1, 9, 25
This is a quadratic sequence: first(n) = (2n-1)^2 = 4n^2 - 4n + 1
The inverse of this is the cycle-number: cycle(i) = floor((sqrt(i) + 1) / 2)
The length of a cycle is: length(n) = first(n+1) - first(n) = 8n
The sector will then be:
sector(i) = floor(4 * (i - first(cycle(i))) / length(cycle(i)))
Finally, to get the position, we need to extrapolate from the position of the first number in the cycle and sector.
To put it all together:
def first(cycle):
x = 2 * cycle - 1
return x * x
def cycle(index):
return (isqrt(index) + 1)//2
def length(cycle):
return 8 * cycle
def sector(index):
c = cycle(index)
offset = index - first(c)
n = length(c)
return 4 * offset / n
def position(index):
c = cycle(index)
s = sector(index)
offset = index - first(c) - s * length(c) // 4
if s == 0: #north
return -c, -c + offset + 1
if s == 1: #east
return -c + offset + 1, c
if s == 2: #south
return c, c - offset - 1
# else, west
return c - offset - 1, -c
def isqrt(x):
"""Calculates the integer square root of a number"""
if x < 0:
raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0:
return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a+b)
while True:
y = (x + n//x)//2
if y >= x:
return x
x = y
Example:
>>> position(9)
(-2, -1)
>>> position(4)
(1, 1)
>>> position(123456)
(-176, 80)
Do you mean something like this? I did not implement any algorithm and the code can be written better but it works - that's always a start :) Just change the threshold value for whatever you wish and you'll get the result.
static int threshold=14, x=0, y=0;
public static void main(String[] args) {
int yChange=1, xChange=1, count=0;
while( !end(count) ){
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y--;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x++;
}
xChange++;
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y++;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x--;
}
xChange++;
}
}
public static boolean end(int count){
if(count<threshold){
return false;
}else{
System.out.println("count: "+count+", x: "+x+", y: "+y);
return true;
}
}