You are on page 1of 10

double wallisFormula(int n) {

return Math.PI*( n>0?.5/wallisFormula(n-1)/n:.5);


}
You're a math teacher at an elementary school. Today you taught your class basic
arithmetic operations ("+", "-", "*", "/") and now you need to give the students
some homework. You have a lot of expressions in the format a <operation> b = c,
where a, b, and c are some integers and operation is one of the operations given
above.

Information about these expressions is stored in the table expressions, which has
the structure:

id: the unique operation id;


a: an integer;
b: an integer;
operation: one of the operations given above ("+", "-", "*", or "/");
c: an integer.
The homework you're going to give is simple: For each expression, the student needs
to determine whether it's correct or not, i.e. whether it's true that the
expression to the left of the = sign equals c.

Since you have many students and checking all their answers manually is a lot of
work, you want to streamline the process by automatically identifying all the
expressions that are correct. Given the table expressions, build the resulting
table as follows: The table should have the same columns as the initial table does,
but it should only contain those rows that represent correct expressions. The rows
should be ordered by id.

Example

For the following table expressions

id a b operation c
1 2 3 + 5
2 2 3 + 6
3 3 2 / 1
4 4 7 * 28
5 54 2 - 27
6 3 0 / 0
the output should be

id a b operation c
1 2 3 + 5
4 4 7 * 28
Explanation:

2 + 3 = 5 - correct;
2 + 3 = 6 - incorrect;
3 / 2 = 1 - incorrect;
4 * 7 = 28 - correct;
54 - 2 = 27 - incorrect;
3 / 0 = 0 - incorrect.
[time limit] 10000ms (mysql)
1.select id,a,b,operation,c from
(select id,a,b,operation,c, case
when operation='+' then a+b
when operation='-' then a-b
when operation='/' then a/b
when operation='*' then a*b
end as ceva
from expressions ) exp where c=ceva;

2.select *
from expressions
where elt(locate(operation, "+-*/"), a+b, a-b, a*b, a/b) = c;
Definition and Usage
The LOCATE() function returns the position of the first occurrence of a substring
in a string.
Note: The POSITION() function is a synonym for the LOCATE() function.
Syntax
LOCATE(substring, string, start)
Parameter Values
Parameter Description
substring Required. The substring to search for in string
string Required. The string that will be searched
start Optional. The starting position for the search. Position 1 is default
LOCATE() performs a case-insensitive search
The first position in string is 1
If substring is not found within string, the LOCATE() function will return 0
Search for "com" in string "W3Schools.com" (start at position 3), and return
position:

SELECT LOCATE("com", "W3Schools.com", 3) AS MatchPosition;

ELT() function

MySQL ELT() returns the string at the index number specified in the list of
arguments. The first argument indicates the index of the string to be retrieved
from the list of arguments.

It returns NULL when the index number is less than 1 or index number is greater
than the number of the string specified as arguments.

Note: According to Wikipedia ELT stands for Extract, Load, Transform (ELT), a data
manipulation process.
Syntax:

ELT(index number, string1, string2, string3,�)


Argument

Name Description
index number An integer.
string1, string2, string3,� List of strings.

SELECT ELT(4,'this','is','the','elt');

Copy
Sample Output:

mysql> SELECT ELT(4,'this','is','the','elt');


+--------------------------------+
| ELT(4,'this','is','the','elt') |
+--------------------------------+
| elt |
+--------------------------------+
1 row in set (0.02 sec)
Example of MySQL ELT() function with greater index number
The following MySQL statement will return NULL because the index number is more
than the number of strings

Example of MySQL ELT() function with index value zero(0)

The following MySQL statement will return the NULL because the index number is less
than 1.

Code:

SELECT ELT(0,'this','is','the','elt');

Copy
Sample Output:

mysql> SELECT ELT(0,'this','is','the','elt');


+--------------------------------+
| ELT(0,'this','is','the','elt') |
+--------------------------------+
| NULL |
+--------------------------------+
1 row in set (0.00 sec

You are managing a small newspaper subscription service. Anyone who uses it can
subscribe to a large number of different newspapers for a full year or just a half
year.

The information about subscriptions is stored in the full_year and half_year


tables, which have the following structures:

full_year:
id: the unique subscription ID;
newspaper: the newspaper's name;
subscriber: the name of the subscriber.
half_year
id: the unique subscription ID;
newspaper: the newspaper's name;
subscriber: the name of the subscriber.
Given the full_year and half_year tables, compose the result as follows: The
resulting table should have one column subscriber that contains all the distinct
names of anyone who is subscribed to a newspaper with the word Daily in its name.
The table should be sorted in ascending order by the subscribers' first names.

Example

The following tables full_year

id newspaper subscriber
1 The Paragon Herald Crissy Sepe
2 The Daily Reporter Tonie Moreton
3 Morningtide Daily Erwin Chitty
4 Daily Breakfast Tonie Moreton
5 Independent Weekly Lavelle Phu
and half_year
id newspaper subscriber
1 The Daily Reporter Lavelle Phu
2 Daily Breakfast Tonie Moreton
3 The Paragon Herald Lia Cover
4 The Community Gazette Lavelle Phu
5 Nova Daily Lia Cover
6 Nova Daily Joya Buss
the output should be

subscriber
Erwin Chitty
Joya Buss
Lavelle Phu
Lia Cover
Tonie Moreton
[time limit] 10000ms (mysql)

SELECT DISTINCT subscriber


FROM
(
SELECT *
FROM full_year
UNION
SELECT *
FROM half_year
) x
WHERE newspaper LIKE "%Daily%"
ORDER BY subscriber ASC;

Your friend wants to become a professional tour guide and travel all around the
world. In pursuit of this dream, she enrolled in tour guide school. The professors
in this school turned out to be very demanding, and one of them gave your friend a
difficult assignment that she has to finish over the weekend.

Here's the task: Given a list of countries, your friend should calculate the
average population and total population of all the countries in the list. To help
her, you have decided to write a function that will calculate the required values
for any number of countries. The countries table in which the countries are stored
has the following structure:

name: the name of the country;


continent: the continent on which the country is situated;
population: the population of the country.
Your task is to return a new table that contains the number of countries in the
given list, along with their average and total population, in columns titled
number, average and total.

Example

For the following table countries


name continent population
Grenada North America 103328
Monaco Europe 38400
San Marino Europe 33005
Vanuatu Australia 277500
the output should be

number average total


4 113058.2500 452233
[time limit] 10000ms (mysql)

CREATE PROCEDURE countriesInfo()


BEGIN
select count(*) as number,avg(population) as average,sum(population) as total
From countries;
END

Your company is planning to expand internationally very soon. You have been tasked
with preparing a report on foreign markets and potential competitors.

After some investigation, you've created a database containing a foreignCompetitors


table, which has the following structure:

competitor: the name of the competitor;


country: the country in which the competitor is operating.
In your report, you need to include the number of competitors per country and an
additional row at the bottom that contains a summary: ("Total:",
total_number_of_competitors)

Given the foreignCompetitors table, compose the resulting table with two columns:
country and competitors. The first column should contain the country name, and the
second column should contain the number of competitors in this country. The table
should be sorted by the country names in ascending order. In addition, it should
have an extra row at the bottom with the summary, as described above.

Example

For the following table foreignCompetitors

competitor country
Acme Corp USA
GLOBEX USA
Openmedia France
K-bam USA
Hatdrill UK
Hexgreen Germany
D-ranron France
Faxla Spain
the output should be

country competitors
France 2
Germany 1
Spain 1
UK 1
USA 3
Total: 8
[time limit] 10000ms (mysql)
select ifnull(country, "Total:") as country, count(competitor) as competitors
from foreignCompetitors
group by country
with rollup;

//method 1: matrix multiplication


//
// the one below is a good solution, it don't use the perfect square hint and can
solve many kind of this recursion, using matrix multiplication
// long extendedFibonacci(long a, long b, long n) {

// //using 2 matrix: A = [[a*a+b*2, a], [a,2]]


// // B = [[a,1],[b,0]]
// // A * B^n will represent this matrix:
// // [[S(n+2), S(n+1)],
// // [S(n+1), S(n) ]]
// // So all we need is find above result and return the number at
position [1][1] of the result matrix
// // we use exponential by squaring to reduce calculation time

// long[] B[] = {{a*a+b+b, a, a, 2},{a , 1, b, 0}}, D;


// //basically matrix multiplication represent as 1d array, in this special
case, only 2x2 matrix will be use
// for(; n > 0 ; n/=2)
// for(int i = 0; i < 2; i++){

// D = new long[4];
// //binary representation of s is what position of two arary that
should be multiply together
// for(int s = -156052336, j = 0; j<8 ; s>>=4)
// D[j/2] = (D[j++/2] + B[i][s&3] * B[1][(s&15)/4]) % 1000000007;

// if( i+~n%2==0 | i>0)


// B[i] = D;
// }

// return B[0][3];
// }
//
//
// method 2: recursion equation solver
//
// suppose we have the following equation:
//
// F(N) = a F(N-1) + b F(N-2)
//
// => solve the equation:
// r^2 - a r - b = 0
//
// suppose we have 2 solution: r1 and r2
//
// so, F(N) will have the form:
//
// F(N) = a1 * r1 ^ N + a2 * r2 ^ N
// with a1 and a2 are the constants which must be found
//
// with the given value of F(0) and F(1), we have:
//
// F(0) = 2 => a1 + a2 = 2
// F(1) = a => a1 r1 + a2 r2 = a
// solve the above system of equation, we have what we need to find
//
//
long extendedFibonacci(long a, long d, long n) {
d += Math.sqrt(a*a+4*d) - d;
long r = a-d>>1, m = 7, p = 1, q = 1;

//just solving recurence equation relation


//S_n is now a1 * r1 ^ n + a2 * r2 ^ n;

for(a-=r, m += 1e9 ; n > 0 ; r = r*r % m, a = a * a % m, n/=2)


if(n%2>0){
p = p * r % m;
q = q * a % m;
}

return (p+q+m)%m;

select count(id) number_of_nulls


from departments
where description is null
or trim(description) in ('null', 'nil', '-');

SELECT
@c := @c * LENGTH(characters) AS `combinations`
FROM
discs,
(SELECT @c := 1) AS counter
ORDER BY
`combinations` DESC
LIMIT
1;

BEGIN
SELECT substring_index(ExtractValue(xml_doc, '//catalog//book//author'),'
', 2) as author
FROM catalogs
order by author;
END

select sum(case when first_team_score>second_team_score then first_team_score-


second_team_score
when first_team_score<second_team_score then
-first_team_score+second_team_score end)as gd,(case when
first_team_score>second_team_score then 1
when first_team_score<second_team_score then 2 end)as team
from
scores
Group by team;
def is_left_entrance_clear(parkingLot, luckySpot):
nodes_to_check = []
x = luckySpot[0]
while x <= luckySpot[2]: # on same row
y = luckySpot[1]-1
while y >= 0:
nodes_to_check.append((x, y))
y -= 1
x += 1
for x, y in nodes_to_check:
if parkingLot[x][y] == 1:
return False
return True

def is_right_entrance_clear(parkingLot, luckySpot):


nodes_to_check = []
x = luckySpot[2]
while x < len(parkingLot[0]): # on same row
y = luckySpot[3]+1
while y < len(parkingLot[0]):
nodes_to_check.append((x, y))
y += 1
x += 1
for x, y in nodes_to_check:
if parkingLot[x][y] == 1:
return False
return True

def is_up_entrance_clear(parkingLot, luckySpot):


nodes_to_check = []
x = luckySpot[0]-1
while x >= 0: # on same row
y = luckySpot[1]
while y <= luckySpot[3]:
nodes_to_check.append((x, y))
y += 1
x -= 1
for x, y in nodes_to_check:
if parkingLot[x][y] == 1:
return False
return True

def is_down_entrance_clear(parkingLot, luckySpot):


nodes_to_check = []
x = luckySpot[2]+1
while x < len(parkingLot): # on same row
y = luckySpot[1]
while y <= luckySpot[3]:
nodes_to_check.append((x, y))
y += 1
x += 1
for x, y in nodes_to_check:
if parkingLot[x][y] == 1:
return False
return True

def define_spot_orientation(luckySpot):
if abs(luckySpot[1]-luckySpot[3]) > abs(luckySpot[0]-luckySpot[2]):
return "horizontal"
else:
return "vertical"

def is_entrance_exist(parkingLot, luckySpot):


if define_spot_orientation(luckySpot) == "horizontal":
return is_left_entrance_clear(parkingLot, luckySpot) or
is_right_entrance_clear(parkingLot, luckySpot)
else: # spot orientation "vertical"
return is_up_entrance_clear(parkingLot, luckySpot) or
is_down_entrance_clear(parkingLot, luckySpot)

def is_lucky_spot_empty(parkingLot, luckySpot):


x = luckySpot[0]
while x <= luckySpot[2]:
y = luckySpot[1]
while y <= luckySpot[3]:
if parkingLot[x][y] == 1:
return False
y += 1
x += 1
return True

def is_spot_fit_car(carDimensions, luckySpot):


return carDimensions[0] > luckySpot[2] - luckySpot[0] or carDimensions[1] >
luckySpot[3] - luckySpot[1]

def parkingSpot(carDimensions, parkingLot, luckySpot):


# Make sure the car can fit the spot
if not is_spot_fit_car(carDimensions, luckySpot):
return False

# Make sure the spot is empty


if not is_lucky_spot_empty(parkingLot, luckySpot):
return False

# Make sure there is a free entry large enough to the spot


if not is_entrance_exist(parkingLot, luckySpot):
return False

return True

istNode<int>*temp=*l;
ListNode<int> *currentNode=*l;
ListNode<int> *previousNode=NULL;
ListNode<int> *nextNode=NULL;
while(currentNode!=NULL)
{
nextNode=currentNode->next;
currentNode->next=previousNode;
previousNode=currentNode;
currentNode=nextNode;

}
*l=previousNode;
ListNode<int>*temp1=*l;
while(temp1!=NULL)
{
cout<<temp1->value;
temp1=temp1->next;
cout<<temp->value;
temp=temp->next;

}
santosh.chapaneri@ieee.org

You might also like