Rubik's Cube Algorithm
|
|
- Aleesha Prudence Gardner
- 5 years ago
- Views:
Transcription
1 Rubik's Cube Algorithm The assignment was to create an algorithm that would solve a randomly organized Rubik's Cube. While very simple on the surface, this problem turned out to be incredibly complex, much like the Rubik's Cube itself. The standard Rubik's Cube is a 3x3x3 brick with a total of six faces. The goal is quite simple, to maneuver all the like colors to be on the same side, however given approximately *10^20 possible combinations to choose from, this simple description betrays its true complexity. I began by searching the Internet forsome sort of common answer to this question as I have never been able to solve the Cube myself. What I found was a large number of accepted solutions. Most centered around some philosophy such as solve in layers or solve in progressively large bricks. It seemed that a number of them were also particularly well suited to speed solving or solving in very few total moves. I decided in the end, to choose an algorithm that used the fewest number of moves and also was well documented. I was daunted by the task of accounting for the incredible number of cases even in the simplified solution I had found, but was still confident I could do it. After I sat down to code, I my confidence soon wavered. The sheer number of possibilities was overwhelming. So I changed my tactic and decided to simply try to solve the problem in any way that I could. This lead me to the rather inefficient though effective method of brute force. Although I had decided on brute force, there were still a number of options to choose from. I ended up choosing a solution that mixed the iterative with a bit of recursion. What resulted was a solution broken into moves. In order that the algorithm be understand I will walk through it in plain English. Initially, the Rubik's Cube is declared and stored within a three dimensional array. The first dimension represents the face number. These run 0-5 to account for the six sides of the cube. The next two arrays create a 3x3 grid and simulate one face of the cube. Each element in the three dimensional array is the simply assigned as a value the number of its original face. Because of this, it is very easy to determine if the cube has been solved by comparing each element's location to its original value. After being initialized, the cube is scrambled x number of moves. This is accomplished by randomly generating a number and using this number to rotate a certain face in one of three directions x times. The legal turns are clockwise, counterclockwise and a half turn.
2 After scrambling the cube, the algorithm begins its work. For efficiency's sake I chose to read in n (the number of moves scrambled) to the solve algorithm. If this had not been done, the algorithm would have had to check to see if it had solved after every step. At this point two arrays are declared of depth equal to the number of moves the cube was scrambled. Each element in the arrays contain instructions for how to act at that particular move level. One array is used to store the face to be rotated and the other is to keep track of the type of rotation. Used in conjunction, the two arrays will give the correct move at any move level. For example, using rotation[3] and face[3] will yield the fourth action to take (because arrays are indexed from 0) in a series of moves. All that remains then is to update the move series after each trial so that each move pattern can be tried. What the algorithm really comes down to is almost as simple as binary counting. The first move is operated on first. Turn the first face clockwise then check for correctness. If it is not solved, revert to the scrambled cube. Initially I was reverting to the scrambled cube reversing the moves just applied, but this becomes impractical at higher move levels. After reverting, the type of turn is incremented to turn counter clockwise and the checks are again performed. After the last type of rotation is performed, the face to rotated is incremented. So now face 2 is turned clockwise and then is incremented to turn counter clockwise. The pattern continues in this way until all 18 possibilities have been tried for move number zero. When this happens, the behavior of move number one is changed. Move one now will rotate counter clockwise and move zero will again iterate through all 18 possibilities. Once this happens, move one is incremented again until it is time to increment move number 2. This call is done recursively so that no matter how many moves are to be made, the update function will keep calling itself. If the update function ever tries to increment move number n+1, we know the solution was not found and the solution can not be found in n moves. It is apparent that the solution will be found if the number of moves scrambled is correctly specified. Unfortunately, this algorithm is extremely poor to scale and on large numbers is too slow to be of any use. As is shown in the figures below, this algorithm scales very poorly.
3 Average Running Time (moves) Running Time (sec) Number of Iterations Row 38 Number of Moves Scrambled Time Elapsed (sec) Row 18 Number of Moves Scrambled Number of Moves Test # Seconds Elapsed Test #
4 There were a number of things that I learned from this assignment. First of all, we are not at a point yet, nor I don't think we ever will be, where efficiency of code can be made up for in the hardware. It seems that these days programmers do not need to crunch each byte to optimize their code and that is a good thing in most cases, but it can lead to sloppy code. In my case however, I simply did not have the time or patience to implement an efficient solution. So I reproved to myself as well that more time spent planning up front will lead to cleaner code in the end. I think my problem was that as the deadline approached and I did not have a concrete algorithm for solving even by brute force, I panicked a bit and began designing algorithms on the fly and coding them right off. I spent a large chunk of my time switching between various algorithms and wasted a lot of time that way. I switched between trying to solve the algorithm completely recursively to maintaining the current state via a two dimensional array to doing it all iteratively. The design I ended up with was actually I had scrapped earlier for its lack of potential. I think I just needed to design a solid design and stick with it. As a result of my lack of foresight, my code has a long way to go in terms of efficiency. Even looking at the code now, there are a number of changes I would like to make. For simplicity's sake, I decided that after every move I would revert to the scrambled cube I had been given instead of just going back one move. The algorithm I settled on is simply iterating through all possible solutions and so only the last move needs to change each time to accomplish this. But what I did was redo every move on every attempt and this surely cost a fair bit of time. I did think of doing it this way, but the problems involved in knowing how many moves to backtrack seemed difficult to deal with. Now I realize that I could return an integer from my update function to tell me how many move levels had been change, but at the time I was just trying to get code that functioned at all, let alone efficiently. One change that I did make was to replace my function for returning to the scrambled state. The old method would perform the moves it had just done in reverse order to give the original scrambled cube. The new way simply sets the cube's value back to the scrambled state stored in memory. Over the short term, the first method would be faster, but if done over too many moves, it becomes very slow and so I switched my method. In the future, I would try this algorithm recursively as it lends itself to a recursive solution. However, as it is unlikely that I will ever be tasked with this same problem ever again, I should just take away a few lessons. The first is that I also work better on a full complement of sleep. I
5 solved the bugs in my code in an hour after I slept whereas I had been spending hours debugging on little sleep. Secondly, and related to the first point, I probably should try and start as early as possible on projects because unforeseen problems always come up. Lastly, and most importantly, the design phase of any project needs to outlast the coding phase. A solid design leads to solid coding and a flawed design that can cause problems and rewrites for years to come.
6 Resources for Algorithm Development Lee, Jasmine. "Beginner Solution to the Rubik's Cube." 16 Jan April < Petrus, Lars. "Rubik's Cube Solution." 9 Mar April <
7 // RubiksCube program by Appendix // Here is the finished project :) // Note: The code for creating the cube and rotating was done in colaberation // with Joel and that group's work. // The code uses brute force to exhaust all possible move patterns given the number // of moves from solving. #include <iostream> #include <math.h> #include <ctime> using namespace std; class RubiksCube public: RubiksCube(); void rotateclockwise(int face, int cube[6][3][3]); void rotatecounter(int face, int cube[6][3][3]); void rotatehalf(int face, int cube[6][3][3]); void resetcube(int cube[6][3][3]); void scramblecube(int moves); void viewcube(int cube[6][3][3]); void solve(int moves); bool update (int rotation [], int face[6], int level, int moves); bool issolved(int cube[6][3][3]); private: int cubestore[6][3][3]; //cube[face][row][column] //cube is layed out like a die (opposite sides add up to 5) // 0 Top (3x3 matrix) // Middle order (wraps around) (3x3 matrix) // 5 Bottom (3x3 matrix) // Obviously the cube can be rotated but everything is relative ; RubiksCube::RubiksCube()
8 ; for(int i=0; i<6; i++) for(int j=0; j<3; j++) for(int k=0; k<3; k++) cubestore[i][j][k] = i; void RubiksCube::rotateClockwise(int face, int cube[6][3][3]) // Out of bounds checking done on other end int temp; //rotate the numbers on the face itself //corners temp = cube[face][0][0]; cube[face][0][0] = cube[face][2][0]; cube[face][2][0] = cube[face][2][2]; cube[face][2][2] = cube[face][0][2]; cube[face][0][2] = temp; //edges temp = cube[face][0][1]; cube[face][0][1] = cube[face][1][0]; cube[face][1][0] = cube[face][2][1]; cube[face][2][1] = cube[face][1][2]; cube[face][1][2] = temp; //rotate the other layer that is connected switch (face) case 0: for(int i = 0; i<3; i++) //rotating along the top layer temp = cube[1][0][i]; cube[1][0][i] = cube[2][0][i]; cube[2][0][i] = cube[4][0][i]; cube[4][0][i] = cube[3][0][i]; cube[3][0][i] = temp; case 1: for(int i=0; i<3; i++)
9 temp = cube[0][2][i]; cube[0][2][i] = cube[3][2-i][2]; cube[3][2-i][2] = cube[5][0][2-i]; cube[5][0][2-i] = cube[2][i][0]; cube[2][i][0] = temp; case 2: for(int i=0; i<3; i++) temp = cube[0][2-i][2]; cube[0][2-i][2] = cube[1][2-i][2]; cube[1][2-i][2] = cube[5][2-i][2]; cube[5][2-i][2] = cube[4][i][0]; cube[4][i][0] = temp; case 3: for(int i=0; i<3; i++) temp = cube[0][i][0]; cube[0][i][0] = cube[4][2-i][2]; cube[4][2-i][2] = cube[5][i][0]; cube[5][i][0] = cube[1][i][0]; cube[1][i][0] = temp; case 4: for(int i=0; i<3; i++) temp = cube[0][0][i]; cube[0][0][i] = cube[2][i][2]; cube[2][i][2] = cube[5][2][2-i]; cube[5][2][2-i] = cube[3][2-i][0]; cube[3][2-i][0] = temp; case 5: for(int i = 0; i<3; i++) //rotate bottom layer temp = cube[1][2][i]; cube[1][2][i] = cube[3][2][i]; cube[3][2][i] = cube[4][2][i]; cube[4][2][i] = cube[2][2][i]; cube[2][2][i] = temp;
10 ; return; void RubiksCube::rotateCounter(int face, int cube[6][3][3]) //Out of bounds checking done on other end int temp; //rotate the numbers on the face itself //corners temp = cube[face][0][0]; cube[face][0][0] = cube[face][0][2]; cube[face][0][2] = cube[face][2][2]; cube[face][2][2] = cube[face][2][0]; cube[face][2][0] = temp; //edges temp = cube[face][0][1]; cube[face][0][1] = cube[face][1][2]; cube[face][1][2] = cube[face][2][1]; cube[face][2][1] = cube[face][1][0]; cube[face][1][0] = temp; //rotate connected layer switch (face) case 0: for(int i = 0; i<3; i++) //rotating along the top layer temp = cube[1][0][i]; cube[1][0][i] = cube[3][0][i]; cube[3][0][i] = cube[4][0][i]; cube[4][0][i] = cube[2][0][i]; cube[2][0][i] = temp; case 1: for(int i=0; i<3; i++) temp = cube[0][2][i]; cube[0][2][i] = cube[2][i][0]; cube[2][i][0] = cube[5][0][2-i]; cube[5][0][2-i] = cube[3][2-i][2]; cube[3][2-i][2] = temp;
11 case 2: for(int i=0; i<3; i++) temp = cube[0][2-i][2]; cube[0][2-i][2] = cube[4][i][0]; cube[4][i][0] = cube[5][2-i][2]; cube[5][2-i][2] = cube[1][2-i][2]; cube[1][2-i][2] = temp; case 3: for(int i=0; i<3; i++) temp = cube[0][i][0]; cube[0][i][0] = cube[1][i][0]; cube[1][i][0] = cube[5][i][0]; cube[5][i][0] = cube[4][2-i][2]; cube[4][2-i][2] = temp; case 4: for(int i=0; i<3; i++) temp = cube[0][0][i]; cube[0][0][i] = cube[3][2-i][0]; cube[3][2-i][0] = cube[5][2][2-i]; cube[5][2][2-i] = cube[2][i][2]; cube[2][i][2] = temp; case 5: for(int i = 0; i<3; i++) //rotate bottom layer temp = cube[1][2][i]; cube[1][2][i] = cube[2][2][i]; cube[2][2][i] = cube[4][2][i]; cube[4][2][i] = cube[3][2][i]; cube[3][2][i] = temp; ; return; void RubiksCube::rotateHalf(int face, int cube[6][3][3])
12 rotateclockwise(face, cube); rotateclockwise(face, cube); return; void RubiksCube::resetCube(int cube[6][3][3]) for(int i=0; i<6; i++) for(int j=0; j<3; j++) for(int k=0; k<3; k++) cube[i][j][k] = cubestore[i][j][k]; void RubiksCube::scrambleCube(int moves) srand(time(0)); int face, type; for(int i=0; i<moves; i++) face = (rand() % 6); type = (rand() % 3); if(type == 0) rotateclockwise(face, cubestore); if(type == 1) rotatecounter(face, cubestore); if(type == 2) rotatehalf(face, cubestore); viewcube(cubestore); // Display cube after scramble for reference return; // Displays cube face by face in a line to take up less room // Positions 1-3 on the read out are the top layer; 4-6 are the middle; 7-9 the bottom; void RubiksCube::viewCube(int cube[6][3][3]) for (int i=0; i<6; i++)
13 cout << "Face: " << i << " -> "; for (int j=0; j<3; j++) for (int k=0; k<3; k++) cout << cube[i][j][k] << " "; cout << endl; cout << endl; return; bool RubiksCube::isSolved(int cube[6][3][3]) for (int i=0; i < 6; i++) for (int j=0; j<3; j++) for (int k=0; k<3; k++) if (cube[i][j][k]!= i) return false; return true; void RubiksCube::solve(int moves) bool solved = false; int test [6][3][3]; // Set test to equal cubestore's scrambled state resetcube(test); int rotation[moves]; for (int x = 0; x < moves; x++) rotation[x] = 0; int face[moves];
14 for (int x = 0; x < moves; x++) face[x] = 0; int counter = 0; // Counts number of tries at the puzzle int inc = -1; while (!solved) // Iterate through all possible combinations of moves if (!update (rotation, face, inc, moves)) cout << "This cube was more than " << moves; cout << " moves away from completion and was not solved" << endl; exit (1); // Do the rotations for (int m = 0; m < moves; m++) if (rotation[m] == 0) rotateclockwise(face[m], test); else if (rotation[m] == 1) rotatecounter(face[m], test); else // if (rotation[m] == 2) rotatehalf(face[m], test); if (issolved(test)) // Test for solved solved = true; cout << "Solved :) " << endl; cout << "Found answer on try number: " << counter << endl; viewcube(test); else // if the solution not found on this try //viewcube(test); // show cube for each failed attempt resetcube(test); // Put cube back to its scrambled state
15 return; counter++; // Count number of cycles performed // Recursively updates the two arrays that hold the type of moves for each level // so that all possible rotation patterns are found bool RubiksCube::update (int rotation [], int face[6], int inc, int moves) int next = inc + 1; if (next < moves) if (rotation[next] < 2) // Cycle through types of rotation // 0 - Clockwise; 1 - Counter; 2 - Half; rotation[next]++; else if (rotation[next] == 2) // After cycled through rotations... // Change which face is being rotated rotation[next] = 0; the next move if (face[next] < 5) face[next]++; else if (face[next] == 5) // After all faces rotated in every direction... // Change what happens on face[next] = 0; // Update next move level up if(!update(rotation, face, next, moves)) return false; else return false; // If move limit is exceeded return true;
16 int main() time_t start = time(0); int moves = 7; RubiksCube mycube; cout << "Scrambling..." << endl; cout << "----- Scrambled Cube -----" << endl; mycube.scramblecube(moves); cout << "Searching for answer..." << endl; mycube.solve(moves); time_t end = time(0); cout << "Solution took: " << end - start << " seconds" << endl; return 0;
Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved
Chapter Four: Loops Slides by Evan Gallagher The Three Loops in C++ C++ has these three looping statements: while for do The while Loop while (condition) { statements } The condition is some kind of test
More informationSol. Sol. a. void remove_items_less_than(int arr[], int size, int value) #include <iostream> #include <ctime> using namespace std;
r6.14 For the operations on partially filled arrays below, provide the header of a func tion. d. Remove all elements that are less than a given value. Sol a. void remove_items_less_than(int arr[], int
More informationExploring Performance Tradeoffs in a Sudoku SAT Solver CS242 Project Report
Exploring Performance Tradeoffs in a Sudoku SAT Solver CS242 Project Report Hana Lee (leehana@stanford.edu) December 15, 2017 1 Summary I implemented a SAT solver capable of solving Sudoku puzzles using
More informationChapter Four: Loops II
Chapter Four: Loops II Slides by Evan Gallagher & Nikolay Kirov Chapter Goals To understand nested loops To implement programs that read and process data sets To use a computer for simulations Processing
More informationBuilding on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements
Chapter 5 Looping Building on the foundation Now that we know a little about cout cin math operators boolean operators making decisions using if statements Advantages of Computers Computers are really
More informationChapter 10 - Notes Applications of Arrays
Chapter - Notes Applications of Arrays I. List Processing A. Definition: List - A set of values of the same data type. B. Lists and Arrays 1. A convenient way to store a list is in an array, probably a
More informationPractice Problems for the Final
ECE-250 Algorithms and Data Structures (Winter 2012) Practice Problems for the Final Disclaimer: Please do keep in mind that this problem set does not reflect the exact topics or the fractions of each
More informationData Structures Lecture 3 Order Notation and Recursion
Data Structures Lecture 3 Order Notation and Recursion 1 Overview The median grade.cpp program from Lecture 2 and background on constructing and using vectors. Algorithm analysis; order notation Recursion
More informationWhy Is Repetition Needed?
Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,
More informationLinear Search. Sorting Algorithms. linear search code. Sorting in Ascending Order Selection Sort. Selection sort algorithm
Linear Search Additional CPSC1620 topics Searching, Sorting, Big(O) template functions, classes The idea of a linear search is to walk through the entire list until the value is found. The list does not
More informationMultiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationIntroduction to Programming I COS1511 School of Computing Revision Notes
Introduction to Programming I COS1511 School of Computing Revision Notes UNISA 2018 1 Introduction Some key basic principles to remember: Apply the BODMAS rules of Mathematics for all calculations; The
More informationCSCI 104 Runtime Complexity. Mark Redekopp David Kempe
1 CSCI 104 Runtime Complexity Mark Redekopp David Kempe 2 Runtime It is hard to compare the run time of an algorithm on actual hardware Time may vary based on speed of the HW, etc. The same program may
More informationChapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.
Chapter 13 Recursion Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Recursive void Functions Tracing recursive calls Infinite recursion, overflows Recursive Functions that Return
More information1 Definition of Reduction
1 Definition of Reduction Problem A is reducible, or more technically Turing reducible, to problem B, denoted A B if there a main program M to solve problem A that lacks only a procedure to solve problem
More informationComputer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons
Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite
More informationDefinition: A data structure is a way of organizing data in a computer so that it can be used efficiently.
The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without
More informationSolving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;
Solving a 2D Maze Let s use a 2D array to represent a maze. Let s start with a 10x10 array of char. The array of char can hold either X for a wall, for a blank, and E for the exit. Initially we can hard-code
More information(Refer Slide Time: 02.06)
Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 27 Depth First Search (DFS) Today we are going to be talking
More informationLearning Recursion. Recursion [ Why is it important?] ~7 easy marks in Exam Paper. Step 1. Understand Code. Step 2. Understand Execution
Recursion [ Why is it important?] ~7 easy marks in Exam Paper Seemingly Different Coding Approach In Fact: Strengthen Top-down Thinking Get Mature in - Setting parameters - Function calls - return + work
More informationIII. Classes (Chap. 3)
III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,
More informationAgenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures
The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF
More informationDELHI PUBLIC SCHOOL TAPI
Loops Chapter-1 There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed
More information// The next 4 functions return true on success, false on failure
Stacks and Queues Queues and stacks are two special list types of particular importance. They can be implemented using any list implementation, but arrays are a more practical solution for these structures
More informationIslamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.
Islamic University of Gaza Computer Engineering Dept. C++ Programming For Industrial And Electrical Engineering By Instructor: Ruba A. Salamh Chapter Four: Loops 2 Chapter Goals To implement while, for
More informationCS140 Final Project. Nathan Crandall, Dane Pitkin, Introduction:
Nathan Crandall, 3970001 Dane Pitkin, 4085726 CS140 Final Project Introduction: Our goal was to parallelize the Breadth-first search algorithm using Cilk++. This algorithm works by starting at an initial
More informationCSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion
CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion Review from Lectures 5 & 6 Arrays and pointers, Pointer arithmetic and dereferencing, Types of memory ( automatic, static,
More informationREVIEW. The C++ Programming Language. CS 151 Review #2
REVIEW The C++ Programming Language Computer programming courses generally concentrate on program design that can be applied to any number of programming languages on the market. It is imperative, however,
More informationTo become familiar with array manipulation, searching, and sorting.
ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,
More informationMachine Language Instructions Introduction. Instructions Words of a language understood by machine. Instruction set Vocabulary of the machine
Machine Language Instructions Introduction Instructions Words of a language understood by machine Instruction set Vocabulary of the machine Current goal: to relate a high level language to instruction
More informationData Structure Series
Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after
More informationA SHORT COURSE ON C++
Introduction to A SHORT COURSE ON School of Mathematics Semester 1 2008 Introduction to OUTLINE 1 INTRODUCTION TO 2 FLOW CONTROL AND FUNCTIONS If Else Looping Functions Cmath Library Prototyping Introduction
More informationPointers. Reference operator (&) ted = &andy;
Pointers We have already seen how variables are seen as memory cells that can be accessed using their identifiers. This way we did not have to care about the physical location of our data within memory,
More informationReview Questions I Spring 2010
Review Questions I Spring 2010 The following review questions are similar to the kinds of questions you will be expected to answer on Exam I (tentatively scheduled for Mar. 4), which will cover LCR, chs.
More informationModule 4. Constraint satisfaction problems. Version 2 CSE IIT, Kharagpur
Module 4 Constraint satisfaction problems Lesson 10 Constraint satisfaction problems - II 4.5 Variable and Value Ordering A search algorithm for constraint satisfaction requires the order in which variables
More informationComputer Science II Lecture 1 Introduction and Background
Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis,
More informationIntroduction to Programming
Introduction to Programming Summer Term 2015 Dr. Adrian Kacso, Univ. Siegen adriana.dkacsoa@duni-siegena.de Tel.: 0271/740-3966, Office: H-B 8406 State: May 6, 2015 Betriebssysteme / verteilte Systeme
More informationLab 14 SERACHI G Dr. John P. Abraham
Lab 14 SERACHI G Dr. John P. Abraham We can only do a linear search on an unsorted array, but on a sorted array we can do a binary search. In this chapter we will study two different algorithms for searching,
More informationAssignment 1: grid. Due November 20, 11:59 PM Introduction
CS106L Fall 2008 Handout #19 November 5, 2008 Assignment 1: grid Due November 20, 11:59 PM Introduction The STL container classes encompass a wide selection of associative and sequence containers. However,
More information5. Control Statements
5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements
More informationMore Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4
More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 Ziad Matni Dept. of Computer Science, UCSB Administrative CHANGED T.A. OFFICE/OPEN LAB HOURS! Thursday, 10 AM 12 PM
More informationDiscussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:
Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;
More information1 Unit 8 'for' Loops
1 Unit 8 'for' Loops 2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment
More informationChapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?
Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use countercontrolled, sentinel-controlled,
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationLecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)
Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of
More informationHow to approach a computational problem
How to approach a computational problem A lot of people find computer programming difficult, especially when they first get started with it. Sometimes the problems are problems specifically related to
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #44 Multidimensional Array and pointers In this video, we will look at the relation between Multi-dimensional
More informationEE 355 Unit 11b. Doubly-Linked Lists and Deques. Mark Redekopp
1 EE 355 Unit 11b Doubly-Linked Lists and Deques Mark Redekopp 2 Singly-Linked List Review Used structures/classes and pointers to make linked data structures Singly-Linked Lists dynamically allocates
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 B Cynthia Lee Recursion! The exclamation point isn t there only because this is so exciting, it also relates to one of our recursion examples. Recursion Factorial! Recursive
More informationDesigning Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6
Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6 Ziad Matni Dept. of Computer Science, UCSB Announcements Homework #5 due today Lab #3
More informationIntroduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)
Introduction to C++ 1. General C++ is an Object oriented extension of C which was derived from B (BCPL) Developed by Bjarne Stroustrup (AT&T Bell Labs) in early 1980 s 2. A Simple C++ Program A C++ program
More informationNote 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...
CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?
More informationLecture Notes on Binary Decision Diagrams
Lecture Notes on Binary Decision Diagrams 15-122: Principles of Imperative Computation William Lovas Notes by Frank Pfenning Lecture 25 April 21, 2011 1 Introduction In this lecture we revisit the important
More informationComputer Science II Lecture 2 Strings, Vectors and Recursion
1 Overview of Lecture 2 Computer Science II Lecture 2 Strings, Vectors and Recursion The following topics will be covered quickly strings vectors as smart arrays Basic recursion Mostly, these are assumed
More informationThe Stack, Free Store, and Global Namespace
Pointers This tutorial is my attempt at clarifying pointers for anyone still confused about them. Pointers are notoriously hard to grasp, so I thought I'd take a shot at explaining them. The more information
More informationTHE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)
THE INTEGER DATA TYPES STORAGE OF INTEGER TYPES IN MEMORY All data types are stored in binary in memory. The type that you give a value indicates to the machine what encoding to use to store the data in
More informationLab Instructor : Jean Lai
Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.
More informationBITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)
BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional
More informationFunctions, Pointers, and the Basics of C++ Classes
Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.
More informationCS 2110 Summer 2011: Assignment 2 Boggle
CS 2110 Summer 2011: Assignment 2 Boggle Due July 12 at 5pm This assignment is to be done in pairs. Information about partners will be provided separately. 1 Playing Boggle 1 In this assignment, we continue
More informationSoftware Testing Prof. Rajib Mall Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur. Lecture 13 Path Testing
Software Testing Prof. Rajib Mall Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 13 Path Testing Welcome to this session and we will discuss about path
More informationThese are notes for the third lecture; if statements and loops.
These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern
More informationSecurity Coding Module - Buffer Overflow Data Gone Wild CS1
Security Coding Module - Buffer Overflow Data Gone Wild CS1 Background Summary: Buffer overflow occurs when data is input or written beyond the allocated bounds of an buffer, array, or other object causing
More informationCSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1
CSE 1 Complexity Analysis Program Efficiency [Sections 12.1-12., 12., 12.9] Count number of instructions executed by program on inputs of a given size Express run time as a function of the input size Assume
More information1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.
1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format
More informationCS2255 HOMEWORK #1 Fall 2012
CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The
More information#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }
1. (9 pts) Show what will be output by the cout s in this program. As in normal program execution, any update to a variable should affect the next statement. (Note: boolalpha simply causes Booleans to
More informationArrays and Linked Lists
Arrays and Linked Lists Abstract Data Types Stacks Queues Priority Queues and Deques John Edgar 2 And Stacks Reverse Polish Notation (RPN) Also known as postfix notation A mathematical notation Where every
More informationName MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.
CMPSC11 Final (Study Guide) Fall 11 Prof Hartman Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) This is a collection of statements that performs
More informationIntroduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms
Introduction to Linked Lists Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Lecture Slides Friday, September 25, 2009 Glenn G. Chappell Department of Computer Science
More informationExam I Review Questions Fall 2010
Exam I Review Questions Fall 2010 The following review questions are similar to the kinds of questions you will be expected to answer on Exam I (scheduled for Oct. 14), which will cover LCR, chs. 1 7,
More informationCS 103 Unit 15. Doubly-Linked Lists and Deques. Mark Redekopp
1 CS 103 Unit 15 Doubly-Linked Lists and Deques Mark Redekopp 2 Singly-Linked List Review Used structures/classes and pointers to make linked data structures Singly-Linked Lists dynamically allocates each
More informationData Structures Lesson 9
Data Structures Lesson 9 BSc in Computer Science University of New York, Tirana Assoc. Prof. Marenglen Biba 1-1 Chapter 21 A Priority Queue: The Binary Heap Priority Queue The priority queue is a fundamental
More informationCISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)
CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts) For this lab you may work with a partner, or you may choose to work alone. If you choose to work with a partner, you are still responsible for the lab
More informationVariables. Data Types.
Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting
More informationIncrement and the While. Class 15
Increment and the While Class 15 Increment and Decrement Operators Increment and Decrement Increase or decrease a value by one, respectively. the most common operation in all of programming is to increment
More informationthe Queue queue ADT using the STL queue designing the simulation simulation with STL queue using STL list as queue using STL vector as queue
the Queue 1 The Queue Abstract Data Type queue ADT using the STL queue 2 Simulating a Printer Queue designing the simulation simulation with STL queue 3 adapting STL list and vector using STL list as queue
More informationDocumentation Nick Parlante, 1996.Free for non-commerical use.
Documentation Nick Parlante, 1996.Free for non-commerical use. A program expresses an algorithm to the computer. A program is clear or "readable" if it also does a good job of communicating the algorithm
More information6. Pointers, Structs, and Arrays. 1. Juli 2011
1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 50 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung
More informationName SECTION: 12:45 2:20. True or False (12 Points)
Name SECION: 12:45 2:20 rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables
More information1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?
Exercises with solutions. 1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl? #include b) What using statement do you always put at the top of
More informationScientific Computing
Scientific Computing Martin Lotz School of Mathematics The University of Manchester Lecture 1, September 22, 2014 Outline Course Overview Programming Basics The C++ Programming Language Outline Course
More informationCache Awareness. Course Level: CS1/CS2. PDC Concepts Covered: PDC Concept Locality False Sharing
Cache Awareness Course Level: CS1/CS PDC Concepts Covered: PDC Concept Locality False Sharing Bloom Level C C Programming Knowledge Prerequisites: Know how to compile Java/C++ Be able to understand loops
More information16. Linked Structures and Miscellaneous
16. Linked Structures and Miscellaneous The main purpose of this section is to look at the cool topic of linked data structures. This is where we use one object to point to the next object in a structure
More informationC++ For Science and Engineering Lecture 12
C++ For Science and Engineering Lecture 12 John Chrispell Tulane University Monday September 20, 2010 Comparing C-Style strings Note the following listing dosn t do what you probably think it does (assuming
More informationBITG 1113: Array (Part 1) LECTURE 8
BITG 1113: Array (Part 1) LECTURE 8 1 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D)
More informationLecture 4 Searching Arrays
Lecture 4 Searching Arrays 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning One of the fundamental and recurring problems in computer science is to find elements in collections,
More informationLecture Notes on Linear Search
Lecture Notes on Linear Search 15-122: Principles of Imperative Computation Frank Pfenning Lecture 5 January 28, 2014 1 Introduction One of the fundamental and recurring problems in computer science is
More informationOn the Practical Use of Bead Sort
Abstract We discuss some issues regarding the practical use of Bead Sort [ACD02]. We do not want to query the basic idea of sorting using a natural algorithm nor the interesting theoretical results, but
More informationLab: Supplying Inputs to Programs
Steven Zeil May 25, 2013 Contents 1 Running the Program 2 2 Supplying Standard Input 4 3 Command Line Parameters 4 1 In this lab, we will look at some of the different ways that basic I/O information can
More informationExam 3 Chapters 7 & 9
Exam 3 Chapters 7 & 9 CSC 2100-002/003 29 Mar 2017 Read through the entire test first BEFORE starting Put your name at the TOP of every page The test has 4 sections worth a total of 100 points o True/False
More informationChapter 20 Hash Tables
Chapter 20 Hash Tables Dictionary All elements have a unique key. Operations: o Insert element with a specified key. o Search for element by key. o Delete element by key. Random vs. sequential access.
More informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationMeasuring algorithm efficiency
CMPT 225 Measuring algorithm efficiency Timing Counting Cost functions Cases Best case Average case Worst case Searching Sorting O Notation O notation's mathematical basis O notation classes and notations
More informationSolution to CSE 250 Final Exam
Solution to CSE 250 Final Exam Fall 2013 Time: 3 hours. December 13, 2013 Total points: 100 14 pages Please use the space provided for each question, and the back of the page if you need to. Please do
More informationPerfect square. #include<iostream> using namespace std; int main(){ int a=1; int square; while(true){ } cout<<square<<endl; }
Lab 3 Kaikai Bian Perfect square #include using namespace std; int main(){ int a=1; int square; while(true){ } cout
More informationArrays and functions Multidimensional arrays Sorting and algorithm efficiency
Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same
More informationAlgorithms... 1 Changing state... 1 Calculations... 3 Processing information... 4 Calling methods... 6 The Call Stack... 7 Wrap up...
7. ALGORITHMS AND METHOD CALLS Algorithms... 1 Changing state... 1 Calculations... 3 Processing information... 4 Calling methods... 6 The Call Stack... 7 Wrap up... 9 Algorithms You now know quite a lot
More information