Nested, dependant for loops: Summation formula and Big-O notation - big-o

Working under a time crunch here. Struggling to understand exactly what this problem is asking. Any help or pointers in the right direction would be greatly appreciated! Thanks in advanced.
The original problem is based on this given information:
for (int k = 0; k < 2*n; k++) {
cout << k << endl;
for (int i = k+1; i < n; i++)
{
m[i][j] = a[i][j] + b[i][j];
cout << m[i][j] << endl;
}
cout << i * k << endl;
}
For T(n) = http://www4c.wolframalpha.com/Calculate/MSP/MSP63941h503ff0a609230100002eieg6bhfe5gi70g?MSPStoreType=image/gif&s=23&w=167.&h=49.
And here is my problem:
Modify the code above to find the number of times the basic operation occurs (i.e. how many times does it go in the inner for loop?).
include
using namespace std;
int main()
{
int count = 0;
int n = 10;
for (int k = 0; k < 2*n; k++) {
cout << "outer: " << k << endl;
for (int i = k+1; i < n; i++) {
cout << "\tinner: " << i << endl;
count++;
}
}
cout << count << endl;
}
Write a summation based on the output of Step 1
Based on this, is T(n) equivalent to O(n) or O(n^2)
I'm confused about specifically what part 2 is asking for. But I found:
http://www4c.wolframalpha.com/Calculate/MSP/MSP4561hgb5f47a07e05g00000112a53ahh0670che?MSPStoreType=image/gif&s=30&w=109.&h=49.
To me this looks like O(N^2)?
I apologize for the formatting. I'm on mobile.

Let me see if I guide:
1. I think the count should be inside like this:
int main() {
int count = -1;
int n = 10;
for (int k = 0; k < 2*n; k++) {
count = 0;
cout << "outer: " << k << endl;
for (int i = k+1; i < n; i++) {
cout << "\tinner: " << i << endl;
count++;
}
cout << count << endl; //<<<here
}
}
Now collect the output (#here marker) and form a formula for the summation. I think this is Task#2.
Based on your formula (or summation) you will be able to generalize whether its o(n) or o(n^2).
This is definitely not linear.

Related

Explain the logic of the output please

I am new to C++. I know the output would be 1024, 10.
I just have no clue as to why log would print out 10, instead of 1.
int n = 1024;
int log = 0;
for (int i = 1; i < n; i = i * 2);
log++;
cout << n << " " << log << endl;
I believe you are missing just the brackets if you are trying to iterate over the loop and print out the log.
int n = 1024;
int log = 0;
for (int i = 1; i < n; i = i * 2)
{
log++;
cout << n << " " << log << endl;
}

Go through all the major diagonals in matrix, including principal

How do I go through all the diagonals in the matrix? There were similar questions, like this one, but they just calculate the sum. I need to perform certain operations going through all the diagonals, not just summing. To be clear, I need to traverse through it in way like in the picture:
I've came up with this solution, but it is awful:
for(int j = 0; j < m; j++) {
for(int i = 0; i < n && i + j < m; i++) {
cout << matrix[i][i + j] << " ";
}
cout << endl;
}
for(int i = 1; i < n; i++) {
for(int j = 0; j < m && i + j < n; j++) {
cout << matrix[j + i][j] << " ";
}
cout << endl;
}
For the matrix n*m I first go through every diagonal right from the main one, and then left from the main one, but this solution seems ugly to me.
You can use a simpler iteration at the cost of a modulo operation:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << a[(i+j)%n][j] << " ";
}
cout << endl;
}
You need a first loop to find the starting point of each diagonal, and a second loop to follow the diagonal.
Here is a pseudo-code, assuming the point (0, 0) is the lower one.
(i_start, j_start) = (1, 0)
While (1)
If (i_start, j_start) out of bound: break
(i, j) = (i_start, j_start)
While (1)
If (i, j) out of bound: break
Write matrix[i][j]
i--, j++
End while
If (i_start not max) i_start++
Else j_start++
End while

Can somebody tell me what this sorting algorithm is called?

So my teacher told me about the bubble sorting technique and it looks like it runs too many times, so I came up with this, I'm fairly sure that it's already been made and I want to know what it's called.
Here it is:
#include <iostream>
using namespace std;
int main()
{
int n, k = 0, i, min, aux;
cout << "N:";cin >> n;
int v[n];
for(i=0;i<n;i++)
cin >> v[i];
do{
for(i=k;i<n;i++){
if(i==k)
min = i;
if(v[i] < v[min])
min = i;
}
aux = v[k];
v[k] = v[min];
v[min] = aux;
k ++;
}while(k<n-1);
cout << "\n";
for(i=0;i<n-1;i++){
cout << v[i] << ",";
}
cout << v[n-1] << ".";
}
This is called selection sort. Good job coming up with it on your own, you can read about it here.

How many characters need to be added to a string to make a palindrome

I just faced an interview in TCS , My last question was to write an algorithm to find how many characters need to be added in a string to make it a palindrome. I started out, but wasnt able to complete. what would be a way to find that?
String palindrome = "helllllll";
char [] chars = palindrome.toCharArray();
for (int i = 0; i < chars.length; i++) {
int j = 0;
for (; j < chars.length - i; j++) {
if (chars[i+j] != chars [chars.length - 1-j])
break;
}
if (j == chars.length - i) {
System.out.println (i);
break;
}
}
As what Niklas said:
Find the leftmost character in the right half of the string that is a potential "mirror point" of a palindrome. It induces the solution. Also consider even-length palindromes
So as an example code that explains your question, this performs a palindrome test and then print it out in reverse without characters like '!', ', or '?'
And i have marked out the process that answers your question with a caption:
#include<iostream>
#include<string>
using namespace std;
int main()
{
//Variables and arrays
int const index = 30;
char Phrase[index];
char Reverse[index];
char* Palindrome = Reverse;
int i, j;
cout << "Please enter a sentence to be tested as a palindrome: ";
cin.getline(Phrase, 30);
int length = strlen(Phrase);
bool test = true;
for(i = 0, j = length-1; i < j; i++, j--) //Loops from zero to half of the string
{
if(test) // if it is a palindrome so far
{
while(!isalpha(Phrase[i]) && i < j) { i++; }
while(!isalpha(Phrase[j]) && i < j) { j--; }
if(Phrase[i] != Phrase[j]) //Check if the characters match
{
test = false;
}
}
else
{
break;
}
}
if(test)
{
cout << endl << "Phrase/Word is a Palindrome." << endl << endl;
for(j = strlen(Phrase) - 1; j >= 0; Palindrome++, j--)
{
*Palindrome = Phrase[j];
}
cout << "The phrase and reverse statement is: " << Reverse << endl << endl;
}
else
{
cout << endl << "Phrase/Word is not a Palindrome." << endl << endl;
}
system("Pause");
return 0;
}

Finding all possible sub-optimal(not optimal!!!) solutions in optimization

I am writing a CPLEX optimization code to generate a matrix, which takes r and n as the command line arguments, but they may be assumed 2 and 4 for now.
The condition for generating the matrix is that the sum of elements in any row or in any column should equal 10, where the elements are integers between 0 and 10. (i.e. doubly-stochastic matrix)
I turned this condition into the constraint, and generated the matrix, but it only gives a matrix with 10s and 0s.
I think it is because CPLEX always finds the "optimal" solution, but for the problem I want to solve, this is not going to help much.
I want matrices with some 6, 7, 8, 9, 10, and 0~5 for the rest.
I want to generate all possible matrices satisfying such condition (and some more condition to be added later) so that I could test all of them and exhaust the case.
How can I do that?
I am looking into this solution pool thing, and it is not easy..
Also,
cplex.out() << "number of solutions = " << cplex.getSolnPoolNsolns() << endl;
this gives 1... meaning that there is only one solution, while I know there are millions of those matrices.
If you have any ideas how to generate all the 'sub-optimal' matrices, please help me.
Thank you.
I attached my code in IPGenMat.cpp, and aa.sol was the solution it gave me.
I also copied it here below.
(In short, two questions: 1. how can I find 'less optimal' solutions? 2. how can I find all of such solutions?)
#include<ilcplex/ilocplex.h>
#include<vector>
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main(int argc, char** argv) {
if (argc < 2) {
cerr << "Error: " << endl;
return 1;
}
else {
int r, n;
stringstream rValue(argv[1]);
stringstream nValue(argv[2]);
rValue >> r;
nValue >> n;
int N=n*r;
int ds = 10; //10 if doubly-stochastic, smaller if sub-doubly stochastic
IloEnv env;
try {
IloModel model(env);
IloArray<IloNumVarArray> m(env, N);
for (int i=0; i<N; i++) {
m[i] = IloNumVarArray(env, N, 0, 10, ILOINT);
}
IloArray<IloExpr> sumInRow(env, N);
for (int i=0; i<N; i++) {
sumInRow[i] = IloExpr(env);
}
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
sumInRow[i] += m[i][j];
}
}
IloArray<IloRange> rowEq(env, N);
for (int i=0; i<N; i++) {
rowEq[i] = IloRange(env, ds, sumInRow[i], 10); //doubly stochastic
}
IloArray<IloExpr> sumInColumn(env, N);
for (int i=0; i<N; i++) {
sumInColumn[i] = IloExpr(env);
}
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
sumInColumn[i] += m[j][i];
}
}
IloArray<IloRange> columnEq(env, N);
for (int i=0; i<N; i++) {
columnEq[i] = IloRange(env, ds, sumInColumn[i], 10); //doubly stochastic
}
for (int i=0; i<N; i++) {
model.add(rowEq[i]);
model.add(columnEq[i]);
}
IloCplex cplex(env);
cplex.extract(model);
cplex.setParam(IloCplex::SolnPoolAGap,0.0);
cplex.setParam(IloCplex::SolnPoolIntensity,4);
cplex.setParam(IloCplex::PopulateLim, 2100000000);
cplex.populate();//.solve();
cplex.out() << "solution status = " << cplex.getStatus() << endl;
cplex.out() << "number of solutions = " << cplex.getSolnPoolNsolns() << endl;
cplex.out() << endl;
cplex.writeSolutions("aa.sol");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cplex.out() << cplex.getValue(m[i][j]) << " | ";
}
cplex.out() << endl;
}
cplex.out() << endl;
}
catch(IloException& e) {
cerr << " ERROR: " << e << endl;
}
catch(...) {
cerr << " ERROR: " << endl;
}
env.end();
return 0;
}
}
You might try using PORTA's vint utility or PPL for this instead. CPLEX is geared for optimissation problems, not enumeration problems.
I'd add that, while your problem is a tiny optimisation problem, it's a really huge enumeration problem. There are likely to be far more solutions that you'd know what to do with. You might try narrowing down what you want and trying to express that using linear inequalities.
SolnPoolAGap Sets an absolute tolerance on the objective value for the solutions in the solution pool. Solutions that are worse (either greater in the case of a minimization, or less in the case of a maximization) than the objective of the incumbent solution according to this measure are not kept in the solution pool.
So, to obtain sub-optimal solutions you should put a higher value than 0.0
in this parameter
Let's just assume your solution is some matrix with entries m_i_j. Express your problem in terms of a set of binary decision variables, e.g. m_i_j_v meaning "the matrix at row i and column i has value v". Then after you solve the problem, you can take add another constraint that sums over all the decision variables that are set, and force them to be N-1. This will exclude this as the solution. Rinse an Repeat until the problem becomes infeasible.

Resources