SlideShare a Scribd company logo
1 of 23
Download to read offline
Contest Tips and Tricks
Maxim Buzdalov
SPbSU ITMO
Zurich ETH Trainings
2010-03-20
Part 1: General Questions
● Coding Conventions
● Write Similar Things Similarly
● Learn Code Snippets by Heart and Fingers
● Writing Code on Paper
● Use of Standard Library
● Use of IDE
Coding Conventions
● Use the same coding conventions in your
team
● If the code is formatted according to your
conventions, you read it faster and
understand it better
● Example: Java Coding Conventions
● Feel free to slightly modify the conventions, if
the change makes code more clear
Write Similar Things Similarly
● Some algorithms contain similar code
several times
● There may be (and so, will be) mistakes, or
«copy-paste bugs»
● Need to develop a style which helps to avoid
making such mistakes
Write Similar Things Similarly
boolean intersect(Point src1, Point trg1,
Point src2, Point trg2) {
if (max(src1.x, trg1.x) < min(src2.x, trg2.x) ||
max(src1.y, trg1.y) < min(src2.y, trg2.y) ||
max(src2.x, trg2.x) < min(src1.x, trg1.x) ||
max(src2.y, trg2.y) < min(src1.y, trg1.y)
) {
return false;
}
int vmul00 = src2.sub(src1).vmul(trg1.sub(src1));
int vmul01 = src2.sub(src1).vmul(trg2.sub(src1));
int vmul10 = trg2.sub(trg1).vmul(src1.sub(trg1));
int vmul11 = trg2.sub(trg1).vmul(src2.sub(trg1));
return signum(vmul00) * signum(vmul01) <= 0
&& signum(vmul10) * signum(vmul11) <= 0;
}
Learn Code Snippets by Heart
and Fingers
● Lots of solutions contain well-known and
widely-used algorithms and data structures
● Some of them take too much time to
remember and implement properly
– Segment intersection
– Dijkstra algorithm with heap
– Segment tree & Fenwick tree
– Extended GCD (Integer equation solving)
– Self-balancing binary trees
– …
– Delaunay triangulation
Learn Code Snippets by Heart
and Fingers
● The solution is to:
– Carefully study the algorithm/DS, both idea and
implementation
– Make your fingers write the code independently of
your mind
● This helps to:
– Stop wasting time in recalling the details
– Think more globally while creating code
Writing Code on Paper
● Situation:
– You come up with an idea of an algorithm
– You have written out the calculations
– The computer is busy
– What to do?
● Problem:
– Some of the ideas may be forgotten
– The solution may contain inaccuracies, be
inefficient or simply wrong
– In either case, lots of time is wasted while coding
Writing Code on Paper
● Solution:
– Start writing code on paper, exactly as it will be on
the computer
– Some insignificant parts (e.g. evident #include
directives, or parts of template) may be omitted
● Why?
– Lots of work do not consume computer time
– Coding on paper has the effect similar with
discussion with a team-mate
– Coding on computer will be faster as it turns to
copying the code from paper
Use of Standard Library
● Make sure you know your coding language
and your standard library really good
● Avoid coding things from scratch if you have
them ready in the library
● This makes your code more efficient (often)
and containing less mistakes (always)
● Will you find a bug in a piece of code on the
next slide? I found it after my team-mates
spent two hours debugging their solution.
(SPb IFMO 4, NEERC Northern QF, 2006)
Use of Standard Library
for (int i = 0; i < n; ++i) {
for (int j = 1; j < n; ++j) {
if (a[i — 1] > a[i]) {
int tmp = a[i];
a[i] = a[i — 1];
a[i — 1] = tmp;
tmp = b[i];
b[i] = b[i — 1];
b[i] = tmp;
}
}
}
Use of IDE
● Code completion. Greatly speeds up coding
if used appropriately.
● Error highlighting and background
compilation. Can save time, especially at the
end of the contest.
● Static and dynamic analysis. Helps to find
logical bugs in the code when typing.
Use of IDE
● Refactoring. Provides you with much more
power than search-and-replace, useful when
developing big solutions for «technical»
problems.
● Code intentions. IDE shows pieces of code
that can be simplified, shortened or replaced
with use of standard library, and does the
proposed change in one action.
Example: Static & Dynamic
Analysis
Queue<Integer> qx = new ArrayDeque<Integer>();
Queue<Integer> qy = new ArrayDeque<Integer>();
qx.add(0);
qy.add(0);
while (!qx.isEmpty()) {
int x = qx.remove();
int y = qx.remove(); //the bug is here
for (int d = 0; d < 4; ++d) {
int nx = x + dx[d];
int ny = y + dy[d];
if (!used[nx][ny] && !field[nx][ny]) {
qx.add(nx);
qy.add(ny);
used[nx][ny] = true;
}
}
}
The declaration of qy is hinted: «The contents of a collection are updated but
never queried»
Part 2: Special Questions
● Overflow and underflow
● Issues with Graphs
● Geometry Problems
Overflow and Underflow
● You must carefully check types you use for
integer variables for overflow
● Estimate the bounds of values you store in a
variable (e.g., the answer for a problem)
● Constructions like:
int a = <...>
int b = <...>
long long c = a * b;
do not do what you want!
● Things like “Wrong Answer, test 47” often
happen because of the overflow
Overflow and Underflow
● A special case of the overflow problem – loss
of precision in floating-point numbers
● Precision loss of arithmetic operations (for
positive values):
– addition – small loss;
– multiplication – small loss;
– division – small loss;
– subtraction – large loss.
● double stores about 14-15 decimal digits.
● long double stores about than 18 digits.
● Trigonometry operations cause huge
precision loss. For different operations, the
loss is different. Use appropriate ones.
● Small precision being required sometimes
means we should use numerical algorithms
● Precision of 1e-3 is not always small – look
at the absolute value (e.g. 1e9 → 12 digits)
Overflow and Underflow
Issues with Graphs
● Always check the statement to answer the
following questions and the solution for
proper support:
– Is the graph connected?
– Is the graph unidirectional or bidirectional?
(Compare: “unidirectional” and “undirected”)
– Can it contain cycles?
– Are loops allowed?
– Are duplicate edges allowed?
● It is helpful to determine possible graph
types (e.g. a tree, a bipartite graph, a
strongly connected graph, etc)
Geometry Problems
● The “constant multiple” for geometry
algorithms is often quite large. Be accurate!
● “class point” is good. Always code this way.
● Compare doubles with “epsilon”
– Make epsilon a global constant
– Write “less”, “equal”, “signum” functions and so on
– Use these functions instead of “<”, “>”, “==”
Geometry Problems
● Estimate magnitude of values being
compared
– What's the difference between the following pieces
of code:
double vmul00 = (a – b) ^ (c – d);
double vmul01 = (a – b) ^ (c – e);
return less_eq(vmul00 * vmul01, 0);
and
return signum(vmul00) * signum(vmul01) <= 0;
?
Geometry Problems
● Sometimes it is better to code geometry in
integers
● When coding that way, sometimes you will
have to either:
– using 64-bit integers or even arbitrary-precision
arithmetic;
– modify the formula to decrease the needed
number of digits.
● The problem of floating-point precision is
converted to a problem of integer oveflow
Thank you!
Any questions?

More Related Content

Similar to Contest Tips and Tricks

Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytechyannick grenzinger
 
Keep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any languageKeep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any languageMick Andrew
 
Concept of Algorithm.pptx
Concept of Algorithm.pptxConcept of Algorithm.pptx
Concept of Algorithm.pptxElProfesor14
 
CS8461 - Design and Analysis of Algorithms
CS8461 - Design and Analysis of AlgorithmsCS8461 - Design and Analysis of Algorithms
CS8461 - Design and Analysis of AlgorithmsKrishnan MuthuManickam
 
An introduction to Competitive Programming
An introduction to Competitive ProgrammingAn introduction to Competitive Programming
An introduction to Competitive ProgrammingGaurav Agarwal
 
Design and Analysis of Algorithm ppt for unit one
Design and Analysis of Algorithm ppt for unit oneDesign and Analysis of Algorithm ppt for unit one
Design and Analysis of Algorithm ppt for unit onessuserb7c8b8
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010Clay Helberg
 
Lotusphere 2007 AD505 DevBlast 30 LotusScript Tips
Lotusphere 2007 AD505 DevBlast 30 LotusScript TipsLotusphere 2007 AD505 DevBlast 30 LotusScript Tips
Lotusphere 2007 AD505 DevBlast 30 LotusScript TipsBill Buchan
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptMard Geer
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptSourabhPal46
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureStyle & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureNick Pruehs
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programmingJuggernaut Liu
 
Computer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming IComputer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming I💻 Anton Gerdelan
 

Similar to Contest Tips and Tricks (20)

Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
 
Keep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any languageKeep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any language
 
Concept of Algorithm.pptx
Concept of Algorithm.pptxConcept of Algorithm.pptx
Concept of Algorithm.pptx
 
CS8461 - Design and Analysis of Algorithms
CS8461 - Design and Analysis of AlgorithmsCS8461 - Design and Analysis of Algorithms
CS8461 - Design and Analysis of Algorithms
 
An introduction to Competitive Programming
An introduction to Competitive ProgrammingAn introduction to Competitive Programming
An introduction to Competitive Programming
 
Architecture presentation 4
Architecture presentation 4Architecture presentation 4
Architecture presentation 4
 
Design and Analysis of Algorithm ppt for unit one
Design and Analysis of Algorithm ppt for unit oneDesign and Analysis of Algorithm ppt for unit one
Design and Analysis of Algorithm ppt for unit one
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010
 
Cloud accounting software uk
Cloud accounting software ukCloud accounting software uk
Cloud accounting software uk
 
Introduction to Parallelization ans performance optimization
Introduction to Parallelization ans performance optimizationIntroduction to Parallelization ans performance optimization
Introduction to Parallelization ans performance optimization
 
Lotusphere 2007 AD505 DevBlast 30 LotusScript Tips
Lotusphere 2007 AD505 DevBlast 30 LotusScript TipsLotusphere 2007 AD505 DevBlast 30 LotusScript Tips
Lotusphere 2007 AD505 DevBlast 30 LotusScript Tips
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.ppt
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.ppt
 
Style & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & StructureStyle & Design Principles 01 - Code Style & Structure
Style & Design Principles 01 - Code Style & Structure
 
Introduction to Parallelization ans performance optimization
Introduction to Parallelization ans performance optimizationIntroduction to Parallelization ans performance optimization
Introduction to Parallelization ans performance optimization
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programming
 
Computer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming IComputer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming I
 
College1
College1College1
College1
 
Illustrated Code (ASE 2021)
Illustrated Code (ASE 2021)Illustrated Code (ASE 2021)
Illustrated Code (ASE 2021)
 

Recently uploaded

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 

Recently uploaded (20)

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 

Contest Tips and Tricks

  • 1. Contest Tips and Tricks Maxim Buzdalov SPbSU ITMO Zurich ETH Trainings 2010-03-20
  • 2. Part 1: General Questions ● Coding Conventions ● Write Similar Things Similarly ● Learn Code Snippets by Heart and Fingers ● Writing Code on Paper ● Use of Standard Library ● Use of IDE
  • 3. Coding Conventions ● Use the same coding conventions in your team ● If the code is formatted according to your conventions, you read it faster and understand it better ● Example: Java Coding Conventions ● Feel free to slightly modify the conventions, if the change makes code more clear
  • 4. Write Similar Things Similarly ● Some algorithms contain similar code several times ● There may be (and so, will be) mistakes, or «copy-paste bugs» ● Need to develop a style which helps to avoid making such mistakes
  • 5. Write Similar Things Similarly boolean intersect(Point src1, Point trg1, Point src2, Point trg2) { if (max(src1.x, trg1.x) < min(src2.x, trg2.x) || max(src1.y, trg1.y) < min(src2.y, trg2.y) || max(src2.x, trg2.x) < min(src1.x, trg1.x) || max(src2.y, trg2.y) < min(src1.y, trg1.y) ) { return false; } int vmul00 = src2.sub(src1).vmul(trg1.sub(src1)); int vmul01 = src2.sub(src1).vmul(trg2.sub(src1)); int vmul10 = trg2.sub(trg1).vmul(src1.sub(trg1)); int vmul11 = trg2.sub(trg1).vmul(src2.sub(trg1)); return signum(vmul00) * signum(vmul01) <= 0 && signum(vmul10) * signum(vmul11) <= 0; }
  • 6. Learn Code Snippets by Heart and Fingers ● Lots of solutions contain well-known and widely-used algorithms and data structures ● Some of them take too much time to remember and implement properly – Segment intersection – Dijkstra algorithm with heap – Segment tree & Fenwick tree – Extended GCD (Integer equation solving) – Self-balancing binary trees – … – Delaunay triangulation
  • 7. Learn Code Snippets by Heart and Fingers ● The solution is to: – Carefully study the algorithm/DS, both idea and implementation – Make your fingers write the code independently of your mind ● This helps to: – Stop wasting time in recalling the details – Think more globally while creating code
  • 8. Writing Code on Paper ● Situation: – You come up with an idea of an algorithm – You have written out the calculations – The computer is busy – What to do? ● Problem: – Some of the ideas may be forgotten – The solution may contain inaccuracies, be inefficient or simply wrong – In either case, lots of time is wasted while coding
  • 9. Writing Code on Paper ● Solution: – Start writing code on paper, exactly as it will be on the computer – Some insignificant parts (e.g. evident #include directives, or parts of template) may be omitted ● Why? – Lots of work do not consume computer time – Coding on paper has the effect similar with discussion with a team-mate – Coding on computer will be faster as it turns to copying the code from paper
  • 10. Use of Standard Library ● Make sure you know your coding language and your standard library really good ● Avoid coding things from scratch if you have them ready in the library ● This makes your code more efficient (often) and containing less mistakes (always) ● Will you find a bug in a piece of code on the next slide? I found it after my team-mates spent two hours debugging their solution. (SPb IFMO 4, NEERC Northern QF, 2006)
  • 11. Use of Standard Library for (int i = 0; i < n; ++i) { for (int j = 1; j < n; ++j) { if (a[i — 1] > a[i]) { int tmp = a[i]; a[i] = a[i — 1]; a[i — 1] = tmp; tmp = b[i]; b[i] = b[i — 1]; b[i] = tmp; } } }
  • 12. Use of IDE ● Code completion. Greatly speeds up coding if used appropriately. ● Error highlighting and background compilation. Can save time, especially at the end of the contest. ● Static and dynamic analysis. Helps to find logical bugs in the code when typing.
  • 13. Use of IDE ● Refactoring. Provides you with much more power than search-and-replace, useful when developing big solutions for «technical» problems. ● Code intentions. IDE shows pieces of code that can be simplified, shortened or replaced with use of standard library, and does the proposed change in one action.
  • 14. Example: Static & Dynamic Analysis Queue<Integer> qx = new ArrayDeque<Integer>(); Queue<Integer> qy = new ArrayDeque<Integer>(); qx.add(0); qy.add(0); while (!qx.isEmpty()) { int x = qx.remove(); int y = qx.remove(); //the bug is here for (int d = 0; d < 4; ++d) { int nx = x + dx[d]; int ny = y + dy[d]; if (!used[nx][ny] && !field[nx][ny]) { qx.add(nx); qy.add(ny); used[nx][ny] = true; } } } The declaration of qy is hinted: «The contents of a collection are updated but never queried»
  • 15. Part 2: Special Questions ● Overflow and underflow ● Issues with Graphs ● Geometry Problems
  • 16. Overflow and Underflow ● You must carefully check types you use for integer variables for overflow ● Estimate the bounds of values you store in a variable (e.g., the answer for a problem) ● Constructions like: int a = <...> int b = <...> long long c = a * b; do not do what you want! ● Things like “Wrong Answer, test 47” often happen because of the overflow
  • 17. Overflow and Underflow ● A special case of the overflow problem – loss of precision in floating-point numbers ● Precision loss of arithmetic operations (for positive values): – addition – small loss; – multiplication – small loss; – division – small loss; – subtraction – large loss.
  • 18. ● double stores about 14-15 decimal digits. ● long double stores about than 18 digits. ● Trigonometry operations cause huge precision loss. For different operations, the loss is different. Use appropriate ones. ● Small precision being required sometimes means we should use numerical algorithms ● Precision of 1e-3 is not always small – look at the absolute value (e.g. 1e9 → 12 digits) Overflow and Underflow
  • 19. Issues with Graphs ● Always check the statement to answer the following questions and the solution for proper support: – Is the graph connected? – Is the graph unidirectional or bidirectional? (Compare: “unidirectional” and “undirected”) – Can it contain cycles? – Are loops allowed? – Are duplicate edges allowed? ● It is helpful to determine possible graph types (e.g. a tree, a bipartite graph, a strongly connected graph, etc)
  • 20. Geometry Problems ● The “constant multiple” for geometry algorithms is often quite large. Be accurate! ● “class point” is good. Always code this way. ● Compare doubles with “epsilon” – Make epsilon a global constant – Write “less”, “equal”, “signum” functions and so on – Use these functions instead of “<”, “>”, “==”
  • 21. Geometry Problems ● Estimate magnitude of values being compared – What's the difference between the following pieces of code: double vmul00 = (a – b) ^ (c – d); double vmul01 = (a – b) ^ (c – e); return less_eq(vmul00 * vmul01, 0); and return signum(vmul00) * signum(vmul01) <= 0; ?
  • 22. Geometry Problems ● Sometimes it is better to code geometry in integers ● When coding that way, sometimes you will have to either: – using 64-bit integers or even arbitrary-precision arithmetic; – modify the formula to decrease the needed number of digits. ● The problem of floating-point precision is converted to a problem of integer oveflow