Issue with Implementing PrimeSieve() in Go

Similar documents
Arrays and Strings

More on Strings & Arrays

Arrays/Slices Store Lists of Variables

Lecture 9: Lists. Lists store lists of variables. Declaring variables that hold lists. Carl Kingsford, , Fall 2015

A Slice of Life

From Last Time... Given a bacterial genome (~3 Mbp), where is ori?

Conditionals !

Conditionals & Loops /

Fundamentals: Expressions and Assignment

Summary of Go Syntax /

Lecture 10: Lindenmayer Systems

Go Cheat Sheet. Operators. Go in a Nutshell. Declarations. Basic Syntax. Hello World. Functions. Comparison. Arithmetic. Credits

Overview of List Syntax

Advanced Systems Programming

VARIABLES AND TYPES CITS1001

Maps /

Last Time: Objects and Abstraction. If it walks like a circle, swims like a circle, and quacks like a circle...!

Go for Java Developers

CS 320: Concepts of Programming Languages

Arrays. Lecture 11 CGS 3416 Spring March 6, Lecture 11CGS 3416 Spring 2017 Arrays March 6, / 19

Swift. Introducing swift. Thomas Woodfin

Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs

CS558 Programming Languages

Pointers /

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Lecture 2 Tao Wang 1

Advanced Python. Executive Summary, Session 1

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

Exercise: Inventing Language

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Arrays. Lecture 11 CGS 3416 Fall October 26, 2015

Variable initialization and assignment

CS558 Programming Languages

COMP 202 Java in one week

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

SWIFT - CLOSURES. Global Functions Nested Functions Closure Expressions. Have a name. Capture values from enclosing function

array Indexed same type

COMP520 - GoLite Type Checking Specification

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

Introduction to Swift. Dr. Sarah Abraham

Overview. Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays. Initialization Searching

Getting started with Java

CSC148 Fall 2017 Ramp Up Session Reference

ENGI 1020 Introduction to Computer Programming J U L Y 5, R E Z A S H A H I D I

Language Reference Manual

CSc Introduction to Computing

CS205: Scalable Software Systems

COMP-520 GoLite Tutorial

Help Topic: MOOS-IvP String Utilities

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

GaE Graphs Ain t Easy. Andrew Jones (adj2129) Kevin Zeng (ksz2109) Samara Nebel (srn2134)

GOLD Language Reference Manual

Types, Variables, and Constants

Good Luck! CSC207, Fall 2012: Quiz 1 Duration 25 minutes Aids allowed: none. Student Number:

Chapter 6 Single-dimensional Arrays

Open2Test Test Automation Framework for SilkTest - Coding Standards for Developers

BTE2313. Chapter 2: Introduction to C++ Programming

Programming Languages

Conditionals. For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations:

Use of scanf. scanf("%d", &number);

Problem Solving for Intro to Computer Science

Lecture 5: Variables and Functions

Intro. Scheme Basics. scm> 5 5. scm>

. p.1/23. Today. 1. Questions and discussion from lecture. 2. Type-checking Functions Arrays Records (maybe)

cs1114 REVIEW of details test closed laptop period

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

PHP. Interactive Web Systems

COMP520 - GoLite Type Checking Specification

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion (Solutions)

Common LISP Tutorial 1 (Basic)

Operational Semantics of Cool

Lecture 16: Object-oriented Programming

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Exercise: Using Numbers

CSCI Test 1.Spring 2004 Student Id: Grading: Undergrads, you are responsible for 110 points. Grads: you are responsible for 120 points

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

COS 126 General Computer Science Fall Written Exam 1

Comp Exam 1 Overview.

Computational Expression

Programming with Java

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

The type of all data used in a C (or C++) program must be specified

COMP520 - GoLite Type Checking Specification

Introduction to Python

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

BİL200 TUTORIAL-EXERCISES Objective:

Fall 2017 CISC124 9/16/2017

ANSWERS. Birkbeck (University of London) Software and Programming 1 In-class Test Feb Student Name Student Number. Answer all questions

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

TYPES, VALUES AND DECLARATIONS

Ruby: Objects and Dynamic Types

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

DaMPL. Language Reference Manual. Henrique Grando

Introduction to Programming, Aug-Dec 2006

Violations of the contract are exceptions, and are usually handled by special language constructs. Design by contract

Computers and Programming Section 450. Lab #1 C# Basic. Student ID Name Signature

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Transcription:

Slices 02-201

Issue with Implementing PrimeSieve() in Go func PrimeSieve(n int) [n+1]bool { var iscomposite [n+1]bool //ERROR! biggestprime := 2 for biggestprime < n for i:=2; i<=n/biggestprime; i++ { iscomposite[i+biggestprime] = true biggestprime++ for biggestprime<n &&iscomposite[biggestprime]{ biggestprime++ return iscomposite Go only allows us to create an array of constant size.

Slices: Everything Arrays Should Be A slice variable is declared by not specifying a size in [] var a []int // at this point a has the special value nil // and can t be used as an array a = make([]int, 10, 20) Creates an array of size 20 with a slice of size 10 inside it. 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 1! 2! 3! 4! 5! 6! 7! 8! 9! 10! 11! 12! 13! 14! 15! 16! 17! 18! 19! Length of this slice is 10! Underlying array has size 20!

Omitting the Third Parameter var a []int a = make([]int, 10) // this is the same as make([]int, 10, 10)

We Can Still Change Items var a []int a = make([]int, 10) a[3] = -18 a[9] = 100 a[10] = 1 //error: out of range

Passing a Variable as Slice Length m := 100 var b []string b = make([]string, m) // this is OK!

Defining a Slice in One Line m := 100 b := make([]string, m) // this is OK!

Recall: Literals... The Other Side of = Integer literals: a sequence of digits 0 9 72 6402 000734 String literals: a sequence of characters between Hi there 1+ =4 3.14159 Unicode strings are supported. bool (Boolean) literals: either true or false true false

Array and Slice Literals We can manually create slices (useful if you have a short list of data that may change): var a = []float64{3.2, -30.1, 84.72, 62.0 var prime = []int{2,3,5,7,11 We can also use array literals (useful for a short list of data that is fixed): var b = [3]float64{2.8, -30.1, 13.2 var odds = [4]int{1,3,5,7

Fixing PrimeSieve func PrimeSieve(n int) []bool { iscomposite := make([]bool, n+1) //Fixed! biggestprime := 2 for biggestprime < n for i:=2; i<=n/biggestprime; i++ { iscomposite[i+biggestprime] = true biggestprime++ for biggestprime<n && iscomposite[biggestprime]{ biggestprime++ return iscomposite

Issue #2: Arrays Copied in Function Calls func Max(A [10000000]int) int { m := 0 for i := range A { if i == 0 A[i] > m { m = A[i] return m func main() { var numbers [10000000]int // fill numbers with random integers for i := range numbers { numbers[i] = rand.int() fmt.println(max(numbers)) A new array A is created and the contents from numbers is copied over (wasteful of memory).

Passing a Slice as an Argument We can also pass a slice (of unknown length) as a function argument. func Max(list []int) int { var m int = list[0] for i := range list { if list[i] > m { m = list[i] return m

Passing a Slice as an Argument func Fudge1(list []int) { list[0] = 1 func Fudge2(list [100]int) { list[0] = 1

Passing a Slice as an Argument func Fudge1(list []int) { list[0] = 1 Exercise: What is printed in main()? func Fudge2(list [100]int) { list[0] = 1 func main() { list1 := make([]int, 100) var list2 [100]int Fudge1(list1) Fudge2(list2) fmt.println(list1[0], list2[0])

Passing a Slice as an Argument func Fudge1(list []int) { list[0] = 1 Exercise: What is printed in main()? func Fudge2(list [100]int) { list[0] = 1 Answer: 1 0 func main() { list1 := make([]int, 100) var list2 [100]int Fudge1(list1) Fudge2(list2) fmt.println(list1[0], list2[0])

Looping Over Both Indices and Elements range also lets us loop over both the index and the elements of a slice. func Max(list []int) int { var m int for j, v := range list { if j == 0 v > m { m = v return m

The Blank Identifier func Sum(A []int) int { var result int for i, val := range A { result = result + val return result Think: What is the issue here?

The Blank Identifier func Sum(A []int) int { var result int for i, val := range A { result = result + val return result Error! Variable i declared and never used.

The Blank Identifier func Sum(A []int) int { var result int for i, val := range A { result = result + val return result Error! Variable i declared and never used. func Sum(A []int) int { var result int for _, val := range A { result = result + val return result Blank identifier _ (single underscore) is useful when declaring a variable that is never used.

Recall: Substrings in Go s := Hi There! fmt.println(s[3:5]) // prints Th fmt.println(s[1:]) // prints i There! fmt.println(s[:4]) // prints Hi T var str string = s[3:6] fmt.println(str) fmt.println(str[0]) // prints The // prints T H i T h e r e! 0 1 2 3 4 5 6 7 8 Subslicing works in the same way.

Subslices: A Picture s := make([]int, 10, 20) for i:=1; i<10; i++ { s[i] = -i - 1 s! array! start! 0! end! 9! -1! -2! -3! -4! -5! -6! -7! -8! -9! -10! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 1! 2! 3! 4! 5! 6! 7! 8! 9! 10! 11! 12! 13! 14! 15! 16! 17! 18! 19!

Subslices: A Picture s := make([]int, 10, 20) for i:=1; i<10; i++ { s[i] = -i - 1 var q []int = s[8:15] s! q! array! array! start! 0! start! 8! end! 9! end! 14! -1! -2! -3! -4! -5! -6! -7! -8! -9! -10! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 1! 2! 3! 4! 5! 6! 7! 8! 9! 10! 11! 12! 13! 14! 15! 16! 17! 18! 19!

Subslices: A Picture s := make([]int, 10, 20) for i:=1; i<10; i++ { s[i] = -i - 1 var q []int = s[8:15] s! q! array! array! start! 0! start! 8! end! 9! end! 14! -1! -2! -3! -4! -5! -6! -7! -8! -9! -10! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 0! 1! 2! 3! 4! 5! 6! 7! 8! 9! 10! 11! 12! 13! 14! 15! 16! 17! 18! 19! Both slices refer to the same underlying array. len(q) == 7 fmt.println(q[0]) // -9 fmt.println(q[6]) // -15 fmt.println(q[15]) // ERROR s[8] == q[0] s[9] = 12 // now q[1] == 12 too!

The append() and copy() Operations s := make([]int, 10) s = append(s, 5) 0! 0! 0! 0! 0 0! 0! 0! 0 0! 5 0! 1! 2! 3! 4! 5! 6! 7! 8! 9! 10 s! c := make([]int, 11) copy(c, s) 0! 0! 0! 0! 0 0! 0! 0! 0 0! 5! 0! 1! 2! 3! 4! 5! 6! 7! 8! 9! 10! c!