How to create a For Loop in cplex - loops

I am new to cplex.
I would like to implement a loop for my MILP problem. It's about to add up.
For example like this:
time: 1 2 3 4
weight: 10 20 30 40
The solution should tell me the Summation weight at each time;
time: 1 2 3 4
sum_weight: 10 30 60 100
I hope my problem becomes clear.

It sounds like you want to use IBM ILOG Script (i.e., JavaScript). For example, the foodmanufact example has the following execute block at the end:
execute DISPLAY {
writeln(" Maximum profit = " , cplex.getObjValue());
for (var i in Months) {
writeln(" Month ", i, " ");
write(" . Buy ");
for (var p in Products)
write(Buy[i][p], "\t ");
writeln();
write(" . Use ");
for (p in Products)
write(Use[i][p], "\t ");
writeln();
write(" . store ");
for (p in Products)
write(Store[i][p], "\t ");
writeln();
}
}
This can be modified to show the sum of Buy over products, like so:
execute DISPLAY {
writeln(" Maximum profit = " , cplex.getObjValue());
for (var i in Months) {
writeln(" Month ", i, " ");
write(" . Buy ");
for (var p in Products)
write(Buy[i][p], "\t ");
writeln();
// START: Display the sum of Buy over products:
write(" . Sum(Buy) ");
var sumBuy = 0;
for (var p in Products) {
sumBuy += Buy[i][p];
write(sumBuy, "\t ");
}
writeln();
// END
write(" . Use ");
for (p in Products)
write(Use[i][p], "\t ");
writeln();
write(" . store ");
for (p in Products)
write(Store[i][p], "\t ");
writeln();
}
}
This gives output, like the following:
Maximum profit = 100278.703703704
...
Month 6
. Buy 480.37037037 629.62962963 0 730 0
. Sum(Buy) 480.37037037 1110 1110 1840 1840
. Use 0 200 0 230 20
. store 500 500 500 500 500

Related

How to find the index of a value in an array and use it to display a value in another array with the same index

I am new to Python and I have been stuck trying out a "simple banking program".
I have got everything right except for this bit:
If the user types S then:
Ask the user for the account number.
Search the array for that account number and find its position in the accountnumbers array.
Display the Name, and balance at the position found during the above search.
Originally it was just supposed to be through accounts 1-5, but now I am having trouble coming up with a way to search the account numbers if they are any number, not just 1 - 5. For example
The user makes his account numbers 34, 445, 340,2354 and 3245. Completely random account numbers with no order.
Here is what I have so far
names = []
accountNumbers = []
balance = []
def displaymenu():
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choiceInput()
def choiceInput():
choice = str(input("Please enter your choice: "))
if (choice == "P"):
populateAccount()
elif (choice == "S"):
accountNumb = int(input("Please enter the account number to search: "))
if (accountNumb > 0) and (accountNumb < 6):
print("Name is: " + str(names[accountNumb - 1]))
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
elif (accountNumb == accountNumbers):
index = names.index(accountNumb)
accountNumb = index
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
else:
print("The account number not found!")
elif (choice == "E"):
print("Thank you for using the program.")
print("Bye")
raise SystemExit
else:
print("Invalid choice. Please try again!")
displaymenu()
def populateAccount ():
name = 0
for name in range(5):
Names = str(input("Please enter a name: "))
names.append(Names)
account ()
name = name + 1
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
def balances ():
balances = int(input("Please enter a balance: "))
balance.append(balances)
displaymenu()
I have tried to use indexes and have not been able to find a solution.
Replace the following line of code
if (accountNumb > 0) and (accountNumb < 6):
with
if (accountNumb > 0) and (accountNumb < len(accountNumbers)):
My mistake. I messed up when appending the account number:
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
I appended
accountNumbers
not
accountNumber
the code should be
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumber)
balances()
also the searchArray function I made was:
def searchArray(accountNumbers):
x = int(input("Please enter an account number to search: "))
y = accountNumbers.index(x)
print("Name is: " + str(names[y]))
print(str(names[y]) + " account has a balance of: " + str(balance[y]))
rookie mistake , shouldnt be using such similar object names.

My totals are not adding up, but just staying as 0

Whenever I run my code, all my totals end up as just zero. What am I missing?
while (theaterNumber != -999)
childTicketInOneTotal += childTicketInOne;
adultTicketInOneTotal += adultTicketInOne;
childTicketInTwoTotal += childTicketInTwo;
adultTicketInTwoTotal += adultTicketInTwo;
if (theaterNumber == 1)
{System.out.print("How many child tickets were sold?");
childTicketInOne = keyboard.nextInt();
System.out.print("How many adult tickets were sold?");
adultTicketInOne = keyboard.nextInt();
System.out.print("Which theater was used (1 or 2)? Enter -999 to complete inputs.");
theaterNumber = keyboard.nextInt();}
else if (theaterNumber == 2)
{System.out.print("How many child tickets were sold?");
childTicketInTwo = keyboard.nextInt();
System.out.print("How many adult tickets were sold?");
adultTicketInTwo = keyboard.nextInt();
System.out.print("Which theater was used (1 or 2)? Enter -999 to complete inputs.");
theaterNumber = keyboard.nextInt();}}
//Display totals
System.out.println();
System.out.println("Theater 1 Totals:");
System.out.println("Adult Tickets Sold: "+ adultTicketInOneTotal +"");
System.out.println("Child Tickets Sold: "+ childTicketInOneTotal +"");
System.out.printf("Total Amount Made: $%.2f \n\n", totalAmountTheaterOne);
System.out.println();
System.out.println("Theater 2 Totals:");
System.out.println("Adult Tickets Sold: "+ adultTicketInTwoTotal +"");
System.out.println("Child Tickets Sold: "+ childTicketInTwoTotal +"");
System.out.printf("Total Amount Made: $%.2f \n\n", totalAmountTheaterTwo);
}}
What language is this? You probably want to initialize your variables before the loop starts and add the input before the output, something like this:
childTicketInOneTotal = 0;
adultTicketInOneTotal = 0;
childTicketInTwoTotal = 0;
adultTicketInTwoTotal = 0;
while (theaterNumber != -999){
if (theaterNumber == 1)
{System.out.print("How many child tickets were sold?");
childTicketInOne = keyboard.nextInt();
System.out.print("How many adult tickets were sold?");
adultTicketInOne = keyboard.nextInt();
System.out.print("Which theater was used (1 or 2)? Enter -999 to complete inputs.");
theaterNumber = keyboard.nextInt();}
else if (theaterNumber == 2)
{System.out.print("How many child tickets were sold?");
childTicketInTwo = keyboard.nextInt();
System.out.print("How many adult tickets were sold?");
adultTicketInTwo = keyboard.nextInt();
# end if not needed?
System.out.print("Which theater was used (1 or 2)? Enter -999 to complete inputs.");
theaterNumber = keyboard.nextInt();}}
childTicketInOneTotal += childTicketInOne;
adultTicketInOneTotal += adultTicketInOne;
childTicketInTwoTotal += childTicketInTwo;
adultTicketInTwoTotal += adultTicketInTwo;
//Display totals
System.out.println();
System.out.println("Theater 1 Totals:");
System.out.println("Adult Tickets Sold: "+ adultTicketInOneTotal +"");
System.out.println("Child Tickets Sold: "+ childTicketInOneTotal +"");
System.out.printf("Total Amount Made: $%.2f \n\n", totalAmountTheaterOne);
System.out.println();
System.out.println("Theater 2 Totals:");
System.out.println("Adult Tickets Sold: "+ adultTicketInTwoTotal +"");
System.out.println("Child Tickets Sold: "+ childTicketInTwoTotal +"");
System.out.printf("Total Amount Made: $%.2f \n\n", totalAmountTheaterTwo);
}}

Find highest earning company from while loop

I need to find the company with the highest earnings.
So far I am able to pull out the highest total Earnings from the loop but have no idea how to get the company name that ties with this highest earnings.
while( count <= noOfComp)
{
System.out.print("Enter Company: ");
companyName = kb.nextLine();
System.out.print("Number of hires: ");
noOfHires = kb.nextInt();
kb.nextLine();
//calculations
totalEarnings = noOfHires * 2500 + 10000;
System.out.println("Total Earnings of company is :" + totalEarnings);
totalEarned = "" + totalEarnings;
if(totalEarnings > large ) //If statement for largest number
{
large = totalEarnings;
}
allTotalEarnings += totalEarnings;
count++;
}
You can assign the highest earning company name and its earnings in variables after the calculation by comparing with previous highest with calculated one.
String highCompanyName = "";int highCompanyEarning = 0;
while( count <= noOfComp)
{
System.out.print("Enter Company: ");
companyName = kb.nextLine();
System.out.print("Number of hires: ");
noOfHires = kb.nextInt();
kb.nextLine();
//calculations
totalEarnings = noOfHires * 2500 + 10000;
System.out.println("Total Earnings of company is :" + totalEarnings);
totalEarned = "" + totalEarnings;
if(totalEarnings> highCompanyEarning ) //If statement for largest number
{
highCompanyEarning = totalEarnings;
highCompanyName = companyName;
}
allTotalEarnings += totalEarnings;//the purpose of it is not clear so left as it is.
count++;
}
System.out.println("Highest Earnings company is :" + highCompanyName );
System.out.println("Earning of that company is :" + highCompanyEarning );

Connect Four game in Scala

I'm trying to make a connect four game in scala. Currently i have the board print out and ask player 1 for a move, once player 1 choses a number a board prints out with an X in the column where player 1 chose. then player 2 picks a number. My problem is that once i pick a number that player's letter fills the whole column and you ant build on top of that.
heres an example of what happens
. X . O X . . .
. X . O X . . .
. X . O X . . .
. X . O X . . .
. X . O X . . .
. X . O X . . .
. X . O X . . .
. X . O X . . .
0 1 2 3 4 5 6 7
// Initialize the grid
val table = Array.fill(9,8)('.')
var i = 0;
while(i < 8){
table(8)(i) = (i+'0').toChar
i = i+1;
}
/* printGrid: Print out the grid provided */
def printGrid(table: Array[Array[Char]]) {
table.foreach( x => println(x.mkString(" ")))
}
/*//place of pieces X
def placeMarker(){
val move = readInt
//var currentRow = 7
while (currentRow >= 0)
if (table(currentRow)(move) != ('.')){
currentRow = (currentRow-1)
table(currentRow)(move) = ('X')
return (player2)}
else{
table(currentRow)(move) = ('X')
return (player2)
}
}
//place of pieces O
def placeMarker2(){
val move = readInt
//var currentRow = 7
while (currentRow >= 0)
if (table(currentRow)(move) != ('.')){
currentRow = (currentRow-1)
table(currentRow)(move) = ('O')
return (player1)}
else{
table(currentRow)(move) = ('O')
return (player1)
}
}
*/
def placeMarker1(){
val move = readInt
var currentRow = 7
while (currentRow >= 0)
if (table(currentRow)(move) !=('.'))
{currentRow = (currentRow-1)}
else{table(currentRow)(move) = ('X')}
}
def placeMarker2(){
val move = readInt
var currentRow = 7
while (currentRow >= 0)
if (table(currentRow)(move) !=('.'))
{currentRow = (currentRow-1)}
else{table(currentRow)(move) = ('O')}
}
//player 1
def player1(){
printGrid(table)
println("Player 1 it is your turn. Choose a column 0-7")
placeMarker1()
}
//player 2
def player2(){
printGrid(table)
println("Player 2 it is your turn. Choose a column 0-7")
placeMarker2()
}
for (turn <- 1 to 32){
player1
player2
}
Your global state is messing you up: var currentRow = 7
Instead of trying to keep track of a global "currentRow" across all columns, I'd recommend one of two things:
Keep a separate "currentRow" for each column in a currentRows array.
Just iterate through the column each time you place a piece to find the lowest empty slot.
Actually, it looks like you were originally doing the second suggestion, but you commented out your local currentRow variables and declared a global (instance-level) one instead.

Text file over written and not appended

So far I have this program doing what i want. However when running through it will overwrite the last employee record instead of just adding to the file. I'm new to prgramming and have been staring at this for hours and i can't get it yet. Just need a little nudge in the right direction.
# Define Employee Class
# Common Base Class for all Employees
class EmployeeClass:
def Employee(fullName, age, salary):
fullName = fullName
age = age
salary = salary
def displayEmployee():
print("\n")
print("Name: " + fullName)
print("Age: " + age)
print("Salary: " + salary)
print("\n")
EmployeeArray = []
Continue = True
print ("Employee Information V2.0")
while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")
choice = input("Pick an option: ")
if choice == "1":
fullName = input ("Enter Full Name: ")
if fullName == "":
blankName = input ("Please enter a name or quit: ")
if blankName == "quit":
print ("Goodbye!")
print ("Hope to see you again.")
Continue = False
break
age = input ("Enter Age: ")
salary = input ("Enter Salary: ")
EmployeeRecords = open ('EmployeeRecords.txt' , 'w')
EmployeeRecords.write("Full Name: " + fullName + '\n')
EmployeeRecords.write("Age: " + age + '\n')
EmployeeRecords.write("Salary: " + salary + '\n')
EmployeeRecords.close()
elif choice == "2":
EmployeeRecords = open ('EmployeeRecords.txt', 'r')
data = EmployeeRecords.read()
print ("\n")
print (data)
EmployeeRecords.close
elif choice == "3":
answer = input ("Are you sure you want to quit? " "yes/no: ")
if answer == "yes" or "y":
print ("Bye!")
Continue = False
else:
Continue
else:
print ("Please choose a valid option")
print ("\n")
You are opening the file to be rewritten each time, based on the control string passed to open. Change open ('EmployeeRecords.txt, 'w')to open ('EmployeeRecords.txt', 'a+'). and the records will be appended to the end of the file.
Append mode should work.
EmployeeRecords = open('EmployeeRecords.txt', 'a')

Resources