This document provides examples of Kotlin programming concepts including:
- Null safety checks using safe calls (?.) and Elvis operator (?:) to handle null values.
- Smart casts that allow treating a variable as a more specific type after checking its type in an if statement.
- String templates using $ variable interpolation to embed values in strings.
- Range expressions using .., downTo, and step operators to iterate over a range of values.
- Higher order functions like let, apply, use, with that take functions as parameters and help scope variables or simplify code.
- When expressions as a replacement for switch/case with more powerful pattern matching capabilities.
- Functions for mutable and
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsSunil Yadav
The document provides coding challenges and their solutions for a May coding challenge. It includes problems such as finding the first bad version, counting jewels in stones, checking if a ransom note can be constructed from magazines, finding the majority element, checking if nodes are cousins in a binary tree, determining if points make a straight line, checking if a number is a perfect square, finding the town judge, flood filling an image, finding the single element in a sorted array, removing K digits from a number, and implementing a trie with various methods. Solutions are provided in Java, C++ and other languages using techniques like recursion, hashing, sorting and binary search.
This document provides information about LeetCode coding challenges for the month of April. It includes the problem statements and solutions for 6 coding challenges - Single Number, Happy Number, Maximum Subarray, Move Zeroes, Best Time to Buy and Sell Stock II, and Group Anagrams. It also provides links to the author's LeetCode, GitHub, LinkedIn and HackerRank profiles. The challenges are part of Week 1 and Week 2 of the April coding challenge.
This document discusses collections and queries in Java, including associative arrays (maps), lambda expressions, and the stream API. It provides examples of using maps like HashMap, LinkedHashMap and TreeMap to store key-value pairs. Lambda expressions are introduced as anonymous functions. The stream API is shown processing collections through methods like filter, map, sorted and collect. Examples demonstrate common tasks like finding minimum/maximum values, summing elements, and sorting lists.
Mixing functional programming approaches in an object oriented languageMark Needham
The document discusses applying functional programming approaches in object-oriented languages like C#. It starts with examples of filtering arrays using predicates and shows how this can be refactored to be more functional. It introduces interfaces for predicates, delegates for functions, and anonymous methods. Lambdas, type inference, extension methods and LINQ are presented as ways to further improve the functional style. Concerns like performance and side effects are addressed. Overall it promotes embracing functional techniques like passing functions as values to gain abstraction and reduce errors while also discussing where object-oriented approaches are still useful.
Programming Paradigms Which One Is The Best?Netguru
The document discusses different programming paradigms and which one may be best. It describes object-oriented programming, imperative programming, and declarative programming. For each, it provides examples in code to illustrate the paradigm. It argues that while imperative programming is popular and easy, it can be error-prone and not scale well. Declarative programming is described as simpler, safer, and more scalable by declaring intent rather than implementation. In the end, the document concludes that no single paradigm is best, and that they are often used together in practice.
1) Base types in Python include integers, floats, booleans, strings, bytes, lists, tuples, dictionaries, sets, and None. These types support various operations like indexing, slicing, mathematical operations, membership testing, etc.
2) Functions are defined using the def keyword and can take parameters and return values. Functions are called by specifying the function name followed by parentheses that may contain arguments.
3) Common operations on containers in Python include getting the length, minimum/maximum values, sum, sorting, checking for membership, enumerating, and zipping containers. Methods like append, extend, insert, remove, pop can modify lists in-place.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
The document discusses Python lists, tuples, and dictionaries. It provides examples of how to create, access, modify, and loop through each of these data types. Lists are ordered and changeable collections that allow duplicate elements. Tuples are ordered and unchangeable collections that allow duplicate elements. Dictionaries are unordered collections of key-value pairs that do not allow duplicate keys. The document demonstrates various methods and operations available for each data type, such as appending and removing elements from lists, accessing elements by index in lists and tuples, and adding or modifying elements in dictionaries.
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsSunil Yadav
The document provides coding challenges and their solutions for a May coding challenge. It includes problems such as finding the first bad version, counting jewels in stones, checking if a ransom note can be constructed from magazines, finding the majority element, checking if nodes are cousins in a binary tree, determining if points make a straight line, checking if a number is a perfect square, finding the town judge, flood filling an image, finding the single element in a sorted array, removing K digits from a number, and implementing a trie with various methods. Solutions are provided in Java, C++ and other languages using techniques like recursion, hashing, sorting and binary search.
This document provides information about LeetCode coding challenges for the month of April. It includes the problem statements and solutions for 6 coding challenges - Single Number, Happy Number, Maximum Subarray, Move Zeroes, Best Time to Buy and Sell Stock II, and Group Anagrams. It also provides links to the author's LeetCode, GitHub, LinkedIn and HackerRank profiles. The challenges are part of Week 1 and Week 2 of the April coding challenge.
This document discusses collections and queries in Java, including associative arrays (maps), lambda expressions, and the stream API. It provides examples of using maps like HashMap, LinkedHashMap and TreeMap to store key-value pairs. Lambda expressions are introduced as anonymous functions. The stream API is shown processing collections through methods like filter, map, sorted and collect. Examples demonstrate common tasks like finding minimum/maximum values, summing elements, and sorting lists.
Mixing functional programming approaches in an object oriented languageMark Needham
The document discusses applying functional programming approaches in object-oriented languages like C#. It starts with examples of filtering arrays using predicates and shows how this can be refactored to be more functional. It introduces interfaces for predicates, delegates for functions, and anonymous methods. Lambdas, type inference, extension methods and LINQ are presented as ways to further improve the functional style. Concerns like performance and side effects are addressed. Overall it promotes embracing functional techniques like passing functions as values to gain abstraction and reduce errors while also discussing where object-oriented approaches are still useful.
Programming Paradigms Which One Is The Best?Netguru
The document discusses different programming paradigms and which one may be best. It describes object-oriented programming, imperative programming, and declarative programming. For each, it provides examples in code to illustrate the paradigm. It argues that while imperative programming is popular and easy, it can be error-prone and not scale well. Declarative programming is described as simpler, safer, and more scalable by declaring intent rather than implementation. In the end, the document concludes that no single paradigm is best, and that they are often used together in practice.
1) Base types in Python include integers, floats, booleans, strings, bytes, lists, tuples, dictionaries, sets, and None. These types support various operations like indexing, slicing, mathematical operations, membership testing, etc.
2) Functions are defined using the def keyword and can take parameters and return values. Functions are called by specifying the function name followed by parentheses that may contain arguments.
3) Common operations on containers in Python include getting the length, minimum/maximum values, sum, sorting, checking for membership, enumerating, and zipping containers. Methods like append, extend, insert, remove, pop can modify lists in-place.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
The document discusses Python lists, tuples, and dictionaries. It provides examples of how to create, access, modify, and loop through each of these data types. Lists are ordered and changeable collections that allow duplicate elements. Tuples are ordered and unchangeable collections that allow duplicate elements. Dictionaries are unordered collections of key-value pairs that do not allow duplicate keys. The document demonstrates various methods and operations available for each data type, such as appending and removing elements from lists, accessing elements by index in lists and tuples, and adding or modifying elements in dictionaries.
This document discusses arrays in C programming. It defines an array as a collection of variables of the same type that are referenced by a common name. It describes single-dimensional and multi-dimensional arrays. Single-dimensional arrays are comprised of finite, homogeneous elements while multi-dimensional arrays have elements that are themselves arrays. The document provides examples of declaring, initializing, accessing, and implementing arrays in memory for both single and double-dimensional arrays. It includes sample programs demonstrating various array operations.
• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
An array is a collection of variables of the same data type stored in contiguous memory locations. There are two types of arrays: single dimensional and multi-dimensional arrays. A single dimensional array stores elements in adjacent memory locations. Multi-dimensional arrays can store arrays of arrays. Two dimensional arrays are commonly used to represent matrices. Arrays allow traversing, searching, and initializing elements. Functions can accept arrays as arguments which are treated as pointers to the first element.
Functional programming is usually classified as difficult. The jargon sounds scary and is creating a barrier to newcomers. This is a shame, since in the essence I would argue that functional programming is easier than object-oriented programming.
In this talk, I’ll outline the fundamentals of functional programming and we will take a look at some common constructs from the perspective of the foundations. Hopefully in the end you will walk away with your toes dipped into the world of functional programming wanting to know more. This talk is aimed for the object-oriented programmer. No prior knowledge about FP is required.
In this chapter we are going to get familiar with some of the basic presentations of data in programming: lists and linear data structures. Very often in order to solve a given problem we need to work with a sequence of elements. For example, to read completely this book we have to read sequentially each page, i.e. to traverse sequentially each of the elements of the set of the pages in the book. Depending on the task, we have to apply different operations on this set of data. In this chapter we will introduce the concept of abstract data types (ADT) and will explain how a certain ADT can have multiple different implementations. After that we shall explore how and when to use lists and their implementations (linked list, doubly-linked list and array-list). We are going to see how for a given task one structure may be more convenient than another. We are going to consider the structures "stack" and "queue", as well as their applications. We are going to get familiar with some implementations of these structures.
The document discusses different search techniques including binary search, bisection, and ternary search. It provides descriptions of binary search and gives iterative and recursive pseudocode implementations. It also discusses the logarithmic worst case performance of binary search. Ternary search is introduced as a technique for finding the minimum or maximum of a unimodal function. Bisection is described as dividing elements into two parts and sorting one part to enable binary search.
Erlang is a functional, concurrency-oriented, distributive, fault-tolerant programming language. It was designed for writing concurrent programs that "run forever" with a focus on fault tolerance through processes and message passing. Erlang uses processes, message passing, and distribution to enable concurrency and high availability.
The document summarizes work done by Group 19 on numerical analysis methods. It includes sections on finding roots using bisection, Newton-Raphson, and Secant methods. It also covers solving matrices using Gauss-Seidel and SOR methods, and approximations using polynomial approximation. For each method, it provides background information, full code, used libraries, and user guides. Mentors for the project were Professor Shlomo Mark and Mrs. Eti Amitai.
The Ring programming language version 1.5.3 book - Part 24 of 184Mahmoud Samir Fayed
The chapter discusses mathematical functions in Ring including trigonometric functions like sin, cos, and tan, logarithmic functions like log and log10, exponential functions like exp, and other functions like sqrt, ceil, floor, and random. Examples are provided to demonstrate how to use functions like sin, cos, tan, log, sqrt, and others in Ring.
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...Philip Schwarz
Learn how to write FP code that displays a graphical representation of all the numerous N-Queens solutions for N=4,5,6,7,8 .
See how to neatly solve the problem by exploiting its self-similarity and using a divide and conquer approach.
Make light work of assembling multiple images into a whole, by exploiting Doodle’s facilities for combining images using a relative layout.
See relevant FP functions, like Foldable’s intercalate and intersperse, in action.
Code for part 3: https://github.com/philipschwarz/n-queens-combinatorial-problem-scala-part-3
Erlang uses pattern matching rather than variable assignment. When using the = symbol in Erlang, it matches the left-hand side to the right-hand side rather than assigning a value. This means a variable can only be matched once - a bound variable cannot be reused like in other languages. So a statement like A = A + 1 would generate an error, as it is trying to match the already bound variable A to a new value.
This document introduces information theory and channel capacity models. It discusses several channel models including the binary symmetric channel (BSC), binary erasure channel, and additive white Gaussian noise channel. It explains how channel capacity is defined as the maximum rate of error-free transmission and derives the capacity for some basic channels. The document also covers channel coding techniques like interleaving that can improve performance by converting burst errors into random errors.
The document summarizes various functions in the Kotlin standard library including let, with, apply, run, also, takeIf, takeUnless, use, and repeat. It provides code examples to demonstrate how each function works and what it is commonly used for. let, with, apply, and also allow passing a receiver object to a lambda and accessing it as "it". takeIf and takeUnless return the receiver if a predicate is true or false, respectively. use automatically closes resources. repeat runs an action a specified number of times.
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...Flink Forward
In this talk we introduce the notion of approximate filter, join, and groupby operations for arrays. Typically, Flink streams contain primitive types and tuples where filter, join, and groupby operate on exact matches. But, exact matches are sometimes limiting. For example, the objects Array(100, 0, 100) and Array(100, 0, 101) may be “close enough” to match. To solve this problem, we introduce locality sensitive hashing (LSH) for arrays of numeric and string types. This technique encodes arrays into strings so that similar arrays are encoded to the same string. In other words, we ensure matching when arrays are similar, up to a degree of error. Therefore, it is easy to incorporate new approximate filter, join, and groupby design patterns built on the notion of exact matches. In conclusion, we highlight how Cisco Umbrella streams large signals stored in arrays and then clusters them using approximate filter, join, groupby methods to detect waves of botnets and cybercrime online.
Implement the following sorting algorithms Bubble Sort Insertion S.pdfkesav24
Implement the following sorting algorithms: Bubble Sort Insertion Sort. Selection Sort.
Merge Sort. Heap Sort. Quick Sort. For each of the above algorithms, measure the execution
time based on input sizes n, n + 10(i), n + 20(i), n + 30(i), .. ., n + 100(i) for n = 50000 and i =
100. Let the array to be sorted be randomly initialized. Use the same machine to measure all the
algorithms. Plot a graph to compare the execution times you collected in part(2).
Solution
This code wil create a graph for each plots comparing time for different sorting methods and also
save those plots in the current directory.
from random import shuffle
from time import time
import numpy as np
import matplotlib.pyplot as plt
def bubblesort(arr):
for i in range(len(arr)):
for k in range(len(arr)-1, i, -1):
if (arr[k] < arr[k-1]):
tmp = arr[k]
arr[k] = arr[k-1]
arr[k-1] = tmp
return arr
def selectionsort(arr):
for fillslot in range(len(arr)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if arr[location]>arr[positionOfMax]:
positionOfMax = location
temp = arr[fillslot]
arr[fillslot] = arr[positionOfMax]
arr[positionOfMax] = temp
return arr
def insertionsort(arr):
for i in range( 1, len( arr ) ):
tmp = arr[i]
k = i
while k > 0 and tmp < arr[k - 1]:
arr[k] = arr[k-1]
k -= 1
arr[k] = tmp
return arr
# def mergesort(arr):
#
# if len(arr)>1:
# mid = len(arr)//2
# lefthalf = arr[:mid]
# righthalf = arr[mid:]
#
# mergesort(lefthalf)
# mergesort(righthalf)
#
# i=0
# j=0
# k=0
# while i < len(lefthalf) and j < len(righthalf):
# if lefthalf[i] < righthalf[j]:
# arr[k]=lefthalf[i]
# i=i+1
# else:
# arr[k]=righthalf[j]
# j=j+1
# k=k+1
#
# while i < len(lefthalf):
# arr[k]=lefthalf[i]
# i=i+1
# k=k+1
#
# while j < len(righthalf):
# arr[k]=righthalf[j]
# j=j+1
# k=k+1
#
# return arr
def mergesort(x):
result = []
if len(x) < 2:
return x
mid = int(len(x)/2)
y = mergesort(x[:mid])
z = mergesort(x[mid:])
i = 0
j = 0
while i < len(y) and j < len(z):
if y[i] > z[j]:
result.append(z[j])
j += 1
else:
result.append(y[i])
i += 1
result += y[i:]
result += z[j:]
return result
def quicksort(arr):
less = []
equal = []
greater = []
if len(arr) > 1:
pivot = arr[0]
for x in arr:
if x < pivot:
less.append(x)
if x == pivot:
equal.append(x)
if x > pivot:
greater.append(x)
return quicksort(less)+equal+quicksort(greater) # Just use the + operator to join lists
else:
return arr
#### Heap sort
def heapsort(arr): #convert arr to heap
length = len(arr) - 1
leastParent = length / 2
for i in range(leastParent, -1, -1):
moveDown(arr, i, length)
# flatten heap into sorted array
for i in range(length, 0, -1):
if arr[0] > arr[i]:
swap(arr, 0, i)
moveDown(arr, 0, i - 1)
def moveDown(arr, first, last):
largest = 2 * first + 1
while largest <= last: #right child exists and is larger than left child
if (largest < last) and(arr[largest] < arr[largest + 1]):
largest += 1
# right child is larger than parent
if arr[largest] > arr[first]:
swap(arr, largest, first)# move down to largest child
first = largest
lar.
The document discusses the benefits of declarative programming using Scala. It provides examples of implementing algorithms and data structures declaratively in Scala. It also discusses the history and future of Scala, as well as how Scala encourages thinking about programs as transformations rather than changes to memory.
The document provides idiomatic Kotlin coding style guidelines and best practices for expressions, classes, functions, and the standard library. Some key recommendations include using 'when' and 'try' as expression bodies, avoiding classes just for functions, extracting non-essential APIs to extensions, using data classes, type aliases, and destructuring declarations, and leveraging functions like 'apply', 'filterIsInstance', and 'groupBy' from the standard library. Overall the document advises organizing code in a concise and functional way that fully utilizes Kotlin language features.
The Ring programming language version 1.8 book - Part 29 of 202Mahmoud Samir Fayed
This document provides information on mathematical functions available in the Ring programming language. It lists common trigonometric, logarithmic, exponential and other mathematical functions like sin(), cos(), tan(), log(), sqrt(), random() and provides examples of using some of these functions to calculate values.
Scala - where objects and functions meetMario Fusco
The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.
This document discusses arrays in C programming. It defines an array as a collection of variables of the same type that are referenced by a common name. It describes single-dimensional and multi-dimensional arrays. Single-dimensional arrays are comprised of finite, homogeneous elements while multi-dimensional arrays have elements that are themselves arrays. The document provides examples of declaring, initializing, accessing, and implementing arrays in memory for both single and double-dimensional arrays. It includes sample programs demonstrating various array operations.
• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
An array is a collection of variables of the same data type stored in contiguous memory locations. There are two types of arrays: single dimensional and multi-dimensional arrays. A single dimensional array stores elements in adjacent memory locations. Multi-dimensional arrays can store arrays of arrays. Two dimensional arrays are commonly used to represent matrices. Arrays allow traversing, searching, and initializing elements. Functions can accept arrays as arguments which are treated as pointers to the first element.
Functional programming is usually classified as difficult. The jargon sounds scary and is creating a barrier to newcomers. This is a shame, since in the essence I would argue that functional programming is easier than object-oriented programming.
In this talk, I’ll outline the fundamentals of functional programming and we will take a look at some common constructs from the perspective of the foundations. Hopefully in the end you will walk away with your toes dipped into the world of functional programming wanting to know more. This talk is aimed for the object-oriented programmer. No prior knowledge about FP is required.
In this chapter we are going to get familiar with some of the basic presentations of data in programming: lists and linear data structures. Very often in order to solve a given problem we need to work with a sequence of elements. For example, to read completely this book we have to read sequentially each page, i.e. to traverse sequentially each of the elements of the set of the pages in the book. Depending on the task, we have to apply different operations on this set of data. In this chapter we will introduce the concept of abstract data types (ADT) and will explain how a certain ADT can have multiple different implementations. After that we shall explore how and when to use lists and their implementations (linked list, doubly-linked list and array-list). We are going to see how for a given task one structure may be more convenient than another. We are going to consider the structures "stack" and "queue", as well as their applications. We are going to get familiar with some implementations of these structures.
The document discusses different search techniques including binary search, bisection, and ternary search. It provides descriptions of binary search and gives iterative and recursive pseudocode implementations. It also discusses the logarithmic worst case performance of binary search. Ternary search is introduced as a technique for finding the minimum or maximum of a unimodal function. Bisection is described as dividing elements into two parts and sorting one part to enable binary search.
Erlang is a functional, concurrency-oriented, distributive, fault-tolerant programming language. It was designed for writing concurrent programs that "run forever" with a focus on fault tolerance through processes and message passing. Erlang uses processes, message passing, and distribution to enable concurrency and high availability.
The document summarizes work done by Group 19 on numerical analysis methods. It includes sections on finding roots using bisection, Newton-Raphson, and Secant methods. It also covers solving matrices using Gauss-Seidel and SOR methods, and approximations using polynomial approximation. For each method, it provides background information, full code, used libraries, and user guides. Mentors for the project were Professor Shlomo Mark and Mrs. Eti Amitai.
The Ring programming language version 1.5.3 book - Part 24 of 184Mahmoud Samir Fayed
The chapter discusses mathematical functions in Ring including trigonometric functions like sin, cos, and tan, logarithmic functions like log and log10, exponential functions like exp, and other functions like sqrt, ceil, floor, and random. Examples are provided to demonstrate how to use functions like sin, cos, tan, log, sqrt, and others in Ring.
N-Queens Combinatorial Problem - Polyglot FP for fun and profit - Haskell and...Philip Schwarz
Learn how to write FP code that displays a graphical representation of all the numerous N-Queens solutions for N=4,5,6,7,8 .
See how to neatly solve the problem by exploiting its self-similarity and using a divide and conquer approach.
Make light work of assembling multiple images into a whole, by exploiting Doodle’s facilities for combining images using a relative layout.
See relevant FP functions, like Foldable’s intercalate and intersperse, in action.
Code for part 3: https://github.com/philipschwarz/n-queens-combinatorial-problem-scala-part-3
Erlang uses pattern matching rather than variable assignment. When using the = symbol in Erlang, it matches the left-hand side to the right-hand side rather than assigning a value. This means a variable can only be matched once - a bound variable cannot be reused like in other languages. So a statement like A = A + 1 would generate an error, as it is trying to match the already bound variable A to a new value.
This document introduces information theory and channel capacity models. It discusses several channel models including the binary symmetric channel (BSC), binary erasure channel, and additive white Gaussian noise channel. It explains how channel capacity is defined as the maximum rate of error-free transmission and derives the capacity for some basic channels. The document also covers channel coding techniques like interleaving that can improve performance by converting burst errors into random errors.
The document summarizes various functions in the Kotlin standard library including let, with, apply, run, also, takeIf, takeUnless, use, and repeat. It provides code examples to demonstrate how each function works and what it is commonly used for. let, with, apply, and also allow passing a receiver object to a lambda and accessing it as "it". takeIf and takeUnless return the receiver if a predicate is true or false, respectively. use automatically closes resources. repeat runs an action a specified number of times.
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...Flink Forward
In this talk we introduce the notion of approximate filter, join, and groupby operations for arrays. Typically, Flink streams contain primitive types and tuples where filter, join, and groupby operate on exact matches. But, exact matches are sometimes limiting. For example, the objects Array(100, 0, 100) and Array(100, 0, 101) may be “close enough” to match. To solve this problem, we introduce locality sensitive hashing (LSH) for arrays of numeric and string types. This technique encodes arrays into strings so that similar arrays are encoded to the same string. In other words, we ensure matching when arrays are similar, up to a degree of error. Therefore, it is easy to incorporate new approximate filter, join, and groupby design patterns built on the notion of exact matches. In conclusion, we highlight how Cisco Umbrella streams large signals stored in arrays and then clusters them using approximate filter, join, groupby methods to detect waves of botnets and cybercrime online.
Implement the following sorting algorithms Bubble Sort Insertion S.pdfkesav24
Implement the following sorting algorithms: Bubble Sort Insertion Sort. Selection Sort.
Merge Sort. Heap Sort. Quick Sort. For each of the above algorithms, measure the execution
time based on input sizes n, n + 10(i), n + 20(i), n + 30(i), .. ., n + 100(i) for n = 50000 and i =
100. Let the array to be sorted be randomly initialized. Use the same machine to measure all the
algorithms. Plot a graph to compare the execution times you collected in part(2).
Solution
This code wil create a graph for each plots comparing time for different sorting methods and also
save those plots in the current directory.
from random import shuffle
from time import time
import numpy as np
import matplotlib.pyplot as plt
def bubblesort(arr):
for i in range(len(arr)):
for k in range(len(arr)-1, i, -1):
if (arr[k] < arr[k-1]):
tmp = arr[k]
arr[k] = arr[k-1]
arr[k-1] = tmp
return arr
def selectionsort(arr):
for fillslot in range(len(arr)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if arr[location]>arr[positionOfMax]:
positionOfMax = location
temp = arr[fillslot]
arr[fillslot] = arr[positionOfMax]
arr[positionOfMax] = temp
return arr
def insertionsort(arr):
for i in range( 1, len( arr ) ):
tmp = arr[i]
k = i
while k > 0 and tmp < arr[k - 1]:
arr[k] = arr[k-1]
k -= 1
arr[k] = tmp
return arr
# def mergesort(arr):
#
# if len(arr)>1:
# mid = len(arr)//2
# lefthalf = arr[:mid]
# righthalf = arr[mid:]
#
# mergesort(lefthalf)
# mergesort(righthalf)
#
# i=0
# j=0
# k=0
# while i < len(lefthalf) and j < len(righthalf):
# if lefthalf[i] < righthalf[j]:
# arr[k]=lefthalf[i]
# i=i+1
# else:
# arr[k]=righthalf[j]
# j=j+1
# k=k+1
#
# while i < len(lefthalf):
# arr[k]=lefthalf[i]
# i=i+1
# k=k+1
#
# while j < len(righthalf):
# arr[k]=righthalf[j]
# j=j+1
# k=k+1
#
# return arr
def mergesort(x):
result = []
if len(x) < 2:
return x
mid = int(len(x)/2)
y = mergesort(x[:mid])
z = mergesort(x[mid:])
i = 0
j = 0
while i < len(y) and j < len(z):
if y[i] > z[j]:
result.append(z[j])
j += 1
else:
result.append(y[i])
i += 1
result += y[i:]
result += z[j:]
return result
def quicksort(arr):
less = []
equal = []
greater = []
if len(arr) > 1:
pivot = arr[0]
for x in arr:
if x < pivot:
less.append(x)
if x == pivot:
equal.append(x)
if x > pivot:
greater.append(x)
return quicksort(less)+equal+quicksort(greater) # Just use the + operator to join lists
else:
return arr
#### Heap sort
def heapsort(arr): #convert arr to heap
length = len(arr) - 1
leastParent = length / 2
for i in range(leastParent, -1, -1):
moveDown(arr, i, length)
# flatten heap into sorted array
for i in range(length, 0, -1):
if arr[0] > arr[i]:
swap(arr, 0, i)
moveDown(arr, 0, i - 1)
def moveDown(arr, first, last):
largest = 2 * first + 1
while largest <= last: #right child exists and is larger than left child
if (largest < last) and(arr[largest] < arr[largest + 1]):
largest += 1
# right child is larger than parent
if arr[largest] > arr[first]:
swap(arr, largest, first)# move down to largest child
first = largest
lar.
The document discusses the benefits of declarative programming using Scala. It provides examples of implementing algorithms and data structures declaratively in Scala. It also discusses the history and future of Scala, as well as how Scala encourages thinking about programs as transformations rather than changes to memory.
The document provides idiomatic Kotlin coding style guidelines and best practices for expressions, classes, functions, and the standard library. Some key recommendations include using 'when' and 'try' as expression bodies, avoiding classes just for functions, extracting non-essential APIs to extensions, using data classes, type aliases, and destructuring declarations, and leveraging functions like 'apply', 'filterIsInstance', and 'groupBy' from the standard library. Overall the document advises organizing code in a concise and functional way that fully utilizes Kotlin language features.
The Ring programming language version 1.8 book - Part 29 of 202Mahmoud Samir Fayed
This document provides information on mathematical functions available in the Ring programming language. It lists common trigonometric, logarithmic, exponential and other mathematical functions like sin(), cos(), tan(), log(), sqrt(), random() and provides examples of using some of these functions to calculate values.
Scala - where objects and functions meetMario Fusco
The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.
This document provides an introduction to the Scala programming language. It discusses that Scala is a hybrid language that is both object-oriented and functional, runs on the JVM, and provides seamless interoperability with Java. It highlights features of Scala such as pattern matching, traits, case classes, immutable data structures, lazy evaluation, and actors for concurrency.
The document provides solutions to various problems involving 1D arrays in C and Python. It includes programs to:
1. Reverse the elements of an array
2. Determine if an array contains all even, odd, or mixed elements
3. Count the number of even and odd elements in an array
4. Check if two arrays are equal
5. Find the sum of perfect square elements in an array
6. Find the minimum scalar product of two vectors
7. Find the smallest and largest elements in an array
8. Print all distinct elements in an array
9. Check if two arrays are disjoint
For each problem, it provides the algorithm, C and Python solutions, sample input/output,
The document provides information about Python programming language:
- Python was created in the late 1980s and became widely popular in the early 2000s.
- It is a high-level, general-purpose, interpreted programming language that can be used for web, desktop, game development, data science, and more.
- Some key features of Python include dynamic typing, automatic memory management, and being multi-paradigm supporting object-oriented, imperative, functional programming styles.
The document contains questions and program code related to C programming and data structures. Some key points:
- There are questions on sorting arrays, checking for loops in arrays, nested structures, sorting based on dates of birth, and implementing functions for book-author-shelf structures.
- Program code is provided as solutions to these questions, making use of structures, pointers, functions, and linked lists.
- One question asks to write a function to sort records in a linked list based on social security number, and code for creating, displaying, and sorting a linked list is given.
This document discusses monads and continuations in functional programming. It provides examples of using monads like Option and List to handle failure in sequences of operations. It also discusses delimited continuations as a low-level control flow primitive that can implement exceptions, concurrency, and suspensions. The document proposes using monads to pass implicit state through programs by wrapping computations in a state transformer (ST) monad.
The document describes various image filtering and processing techniques in Matlab code, including maximum, minimum, average, smoothing, median, difference, Prewitt, Sobel, unsharp mask, Robert, and Gaussian filters. It also provides examples of quicksort, perfect number, greatest common divisor (GCD), and palindrome algorithms in Java code, as well as descriptions of the Tower of Hanoi problem and finding the shortest path on a grid.
This document discusses using Kotlin for test suites and provides examples of writing unit tests in Kotlin compared to Java. It shows how Kotlin allows for cleaner, more readable tests through features like lambdas, extension functions, and DSL capabilities. Specifically, it provides an example of refactoring a test for a task presenter to initialize views into a clearer specification using the given-when-then syntax supported by testing frameworks like Spek for Kotlin. The refactored test checks that when a task with no response is assigned to the current user, the response button is enabled upon initializing the presenter's views.
The Ring programming language version 1.9 book - Part 31 of 210Mahmoud Samir Fayed
This document provides documentation on mathematical functions available in the Ring programming language. It lists common trigonometric, logarithmic, exponential and other mathematical functions along with examples of their usage syntax and output. Key functions covered include sin(), cos(), tan(), log(), exp(), sqrt(), random(), ceil(), floor(), and others. Examples are provided to demonstrate calculating trigonometric functions with radians and degrees as well as functions returning random numbers, absolute values, powers and more.
Scala presentation by Aleksandar ProkopecLoïc Descotte
This document provides an introduction to the Scala programming language. It discusses how Scala runs on the Java Virtual Machine, supports both object-oriented and functional programming paradigms, and provides features like pattern matching, immutable data structures, lazy evaluation, and parallel collections. Scala aims to be concise, expressive, and extensible.
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaPhilip Schwarz
(download for perfect quality) - See how recursive functions and structural induction relate to recursive datatypes.
Follow along as the fold abstraction is introduced and explained.
Watch as folding is used to simplify the definition of recursive functions over recursive datatypes
Part 1 - through the work of Richard Bird and Graham Hutton.
Errata:
slide 7, 11 fib(0) is 0,rather than 1
slide 23: was supposed to be followed by 2-3 slides recapitulating definitions of factorial and fibonacci with and without foldr, plus translation to scala
slide 36: concat not invoked in concat example
slides 48 and 49: unwanted 'm' in definition of sum
throughout: a couple of typographical errors
throughout: several aesthetic imperfections (wrong font, wrong font colour)
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
by Mario Fusco - Lambdas are the main feature introduced with Java 8, but the biggest part of Java developers are still not very familliar with the most common functional idioms and patterns. The purpose of this talk is presenting with practical examples concepts like high-order functions, currying, functions composition, persistent data structures, lazy evaluation, recursion, trampolines and monoids showing how to implement them in Java and how thinking functionally can help us to design and develop more readable, reusable, performant, parallelizable and in a word better, code.
Using Query Store in Azure PostgreSQL to Understand Query PerformanceGrant Fritchey
Microsoft has added an excellent new extension in PostgreSQL on their Azure Platform. This session, presented at Posette 2024, covers what Query Store is and the types of information you can get out of it.
SOCRadar's Aviation Industry Q1 Incident Report is out now!
The aviation industry has always been a prime target for cybercriminals due to its critical infrastructure and high stakes. In the first quarter of 2024, the sector faced an alarming surge in cybersecurity threats, revealing its vulnerabilities and the relentless sophistication of cyber attackers.
SOCRadar’s Aviation Industry, Quarterly Incident Report, provides an in-depth analysis of these threats, detected and examined through our extensive monitoring of hacker forums, Telegram channels, and dark web platforms.
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsPeter Muessig
The UI5 tooling is the development and build tooling of UI5. It is built in a modular and extensible way so that it can be easily extended by your needs. This session will showcase various tooling extensions which can boost your development experience by far so that you can really work offline, transpile your code in your project to use even newer versions of EcmaScript (than 2022 which is supported right now by the UI5 tooling), consume any npm package of your choice in your project, using different kind of proxies, and even stitching UI5 projects during development together to mimic your target environment.
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfUndress Baby
The quest for the best AI face swap solution is marked by an amalgamation of technological prowess and artistic finesse, where cutting-edge algorithms seamlessly replace faces in images or videos with striking realism. Leveraging advanced deep learning techniques, the best AI face swap tools meticulously analyze facial features, lighting conditions, and expressions to execute flawless transformations, ensuring natural-looking results that blur the line between reality and illusion, captivating users with their ingenuity and sophistication.
Web:- https://undressbaby.com/
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
E-commerce Development Services- Hornet DynamicsHornet Dynamics
For any business hoping to succeed in the digital age, having a strong online presence is crucial. We offer Ecommerce Development Services that are customized according to your business requirements and client preferences, enabling you to create a dynamic, safe, and user-friendly online store.
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j
Dr. Jesús Barrasa, Head of Solutions Architecture for EMEA, Neo4j
Découvrez les dernières innovations de Neo4j, et notamment les dernières intégrations cloud et les améliorations produits qui font de Neo4j un choix essentiel pour les développeurs qui créent des applications avec des données interconnectées et de l’IA générative.
What is Master Data Management by PiLog Groupaymanquadri279
PiLog Group's Master Data Record Manager (MDRM) is a sophisticated enterprise solution designed to ensure data accuracy, consistency, and governance across various business functions. MDRM integrates advanced data management technologies to cleanse, classify, and standardize master data, thereby enhancing data quality and operational efficiency.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemPeter Muessig
Learn about the latest innovations in and around OpenUI5/SAPUI5: UI5 Tooling, UI5 linter, UI5 Web Components, Web Components Integration, UI5 2.x, UI5 GenAI.
Recording:
https://www.youtube.com/live/MSdGLG2zLy8?si=INxBHTqkwHhxV5Ta&t=0
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
39. String templates
val apples = 4
val bananas = 3
println("I have $apples apples and " + (apples + bananas) + " fruits.")
> I have 4 apples.
> I have 4 apples.
> I have 4 apples and 7 fruits.
40. String templates
val apples = 4
val bananas = 3
println("I have $apples apples and ${apples+bananas} fruits.")
> I have 4 apples.
> I have 4 apples and 7 fruits.
> I have 4 apples and 7 fruits.
50. Range expressions
for (i in 1.0..2.0 step 0.3) {
print("$i ")
}
> 42
> 1.0 2.0
> 1.0 1.3 1.6 1.9
51. Lab 1
Foo Corporation needs a program to calculate how much to pay their hourly employees. The US Department
of Labor requires that employees get paid time and a half for any hours over 40 that they work in a single
week. For example, if an employee works 45 hours, they get 5 hours of overtime, at 1.5 times their base pay.
The State of Massachusetts requires that hourly employees be paid at least $8.00 an hour. Foo Corp requires
that an employee not work more than 60 hours in a week.
• Rules
• An employee gets paid (hours worked) × (base pay), for each hour up to 40 hours.
• For every hour over 40, they get overtime = (base pay) × 1.5.
• The base pay must not be less than the minimum wage ($8.00 an hour). If it is, print an error.
• If the number of hours is greater than 60, print an error message.
Write a method that takes the base pay and hours worked as parameters, and prints the total pay
or an error. Write a main method that calls this method for each of these employees:
Base Pay Hours Worked
Employee 1 $7.50 35
Employee 2 $8.20 47
Employee 3 $10.00 73
52. Lab 2
A group of ITI friends decide to run a Marathon. Their names and times (in minutes) are below:
Name Time (minutes)
Ahmed 341
Mohamed 273
Ismail 278
Hend 329
Aly 445
Hossam 402
Ola 388
Alaa 275
Basma 243
Mina 334
Nada 412
Saad 393
• Find the fastest runner. Print the name and his/her time (in minutes).
• Optional: Find the second fastest runner. Print the name and his/her time (in minutes).
53. Lab 3
• Create an Android a simple app with two buttons, one to count and
one to show a toast.
54. Lab 4
• Create an Android UI with one text field, centered at the top of the screen, and
one button. The text field will initially display the text Tap to Change Color.
• Every time you tap the button, you will generate a random color using RGB
values, change the text to that color, and display the values for the color in the
following format (assuming you are displaying a light grey with values
100/100/100): COLOR: 100r, 100g, 100b.
55. Lab 5
• Battery Status App
• Create an Android App that displays a colored
bar to display the battery's status.
• Display a battery drawable as follows:
0-25% - Red (battery low)
>25% <80% - Yellow (battery medium)
>80% - Green (battery good)
59. When expression
when (argument) {
m a t c h 1 - > f u n 1 ( )
m a t c h 2 - > f u n 2 ( )
e l s e - > f u n 3 ( )
}
Can be anything
60. When expression
( a r g u m e n t )
Match1 -> fun1()
match2 -> fun2()
e l s e - > f u n 3 ( )
}
Can be anything
61. When expression
var result: Int = when (argument) {
m a t c h 1 - > f u n 1 ( )
m a t c h 2 - > f u n 2 ( )
e l s e - > f u n 3 ( )
}
Can return result
63. When expression
override fun onCreateViewHolder(g: ViewGroup, type: Int) {
when (type) {
TYPE_TITLE -> TitleViewHolder(g)
TYPE_DESCRIPTION -> DescriptionViewHolder(g))
}
return null
}
64. When expression
o v e r r i d e f u n o n C r e a t e V i e w H o l d e r ( g : V i e w G r o u p ,
t y p e : I n t ) {
when (type) {
T Y P E _ T I T L E - > T i t l e V i e w H o l d e r ( g )
T Y P E _ D E S C R I P T I O N - >
D e s c r i p t i o n V i e w H o l d e r ( g ) )
}
r e t u r n n u l l
}
Can be placed after a = symbol
65. When expression
override fun onCreateViewHolder(g: ViewGroup, type: Int) = when (type) {
T Y P E _ T I T L E - > T i t l e V i e w H o l d e r ( g )
T Y P E _ D E S C R I P T I O N - >
D e s c r i p t i o n V i e w H o l d e r ( g ) )
e l s e - > n u l l
}
66. When expression
override fun onCreateViewHolder(g: ViewGroup, type: Int) = when (type) {
TYPE_TITLE -> TitleViewHolder(g)
TYPE_DESCRIPTION -> DescriptionViewHolder(g)
else -> null
}
67. When expression
override fun getItemViewType(index: Int) = when (dataList[index]) {
is Title -> TYPE_TITLE
is Description -> TYPE_DESCRIPTION
else -> TYPE_UNDEFINED
}
68. When expression
override fun getItemViewType(index: Int) = when (dataList[index]) {
is Title -> TYPE_TITLE
is Description -> TYPE_DESCRIPTION
else -> TYPE_UNDEFINED
}
Type checks possible
69. When expression
override fun getItemViewType(index: Int) = when (dataList[index]) {
is Title -> TYPE_TITLE
is Description -> TYPE_DESCRIPTION
else -> TYPE_UNDEFINED
}
70. When expression
override fun onBindViewHolder(viewHolder: ViewHolder, index: Int) {
val displayable: Displayable = dataList[index]
when (displayable) {
is Title -> initTitle(viewHolder, displayable)
is Description -> initDescription(viewHolder, displayable)
}
}
71. When expression
o v e r r i d e f u n o n B i n d V i e w H o l d e r ( v i e w H o l d e r : V i e w H o l d e r , i n d e x : I n t ) {
v a l d i s p l a y a b l e : D i s p l a y a b l e = d a t a L i s t [ i n d e x ]
W h e n ( d i s p l a y a b l e ) {
is Title -> initTitle(viewHolder, displayable)
is Description -> initDescription(viewHolder, displayable)
}
}
Smart cast
73. let, apply, use, with
• Higher-order functions - function that takes
functions as parameters, or returns a function.
74. let (scope function)
/**
* Calls the specified function [block] with `this` value as
* its argument and returns its result.
*/
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
80. use (try with resources function)
/**
* Executes the given [block] function on this resource and then
* closes it down correctly whether an exception is thrown or not.
*/
public inline fun <T : Closeable, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
// ommitted
} finally {
if (!closed) { close()
}
}
}
81. use
fun countUsers(): Long {
val database = openDatabase()
val result = database.count("users")
database.close()
return result
}
82. use
fun countUsers() = openDatabase().use { it.count("users") }
Automatically close
database
83. fun countUsers() = openDatabase().use { it.count("users") }
Refers to database object
use
85. with
/**
* Calls the specified function [block] with the given [receiver]
* as its receiver and returns its result.
*/
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
91. apply
/**
* Calls the specified function [block] with `this` value as its receiver
* and returns `this` value.
*/
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
102. Default values for function parameters
• Function parameters can have default values, which are used when a
corresponding argument is omitted.
• This allows for a reduced number of overloads compared to other
languages.
103. Default values for function parameters
fun query(table: String,
columns: Array<String>,
selection: String?,
selectionArgs : Array<String>?,
orderBy: String?): Cursor {
...
}
// function call
query("USERS", arrayOf("ID", "NAME"), null, null, "NAME")
104. Default values for function parameters
fun query(table: String,
columns: Array<String>,
selection: String? = null,
selectionArgs : Array<String>? = null,
orderBy: String? = null): Cursor {
...
}
// function call
query("USERS", arrayOf("ID", "NAME"), null, null, "NAME")
Default value
105. Default values for function parameters
fun query(table: String,
columns: Array<String>,
selection: String? = null,
selectionArgs : Array<String>? = null,
orderBy: String? = null): Cursor {
...
}
// function call
query("USERS", arrayOf("ID", "NAME"), null, null, "NAME")
106. Default values for function parameters
fun query(table: String,
columns: Array<String>,
selection: String? = null,
selectionArgs : Array<String>? = null,
orderBy: String? = null): Cursor {
...
}
// function call
query("USERS", arrayOf("ID", "NAME"), null, null, orderBy = "NAME")
Named argument
107. Default values for function parameters
fun query(table: String,
columns: Array<String>,
selection: String? = null,
selectionArgs : Array<String>? = null,
orderBy: String? = null): Cursor {
...
}
// function call
query("USERS", arrayOf("ID", "NAME"), null, null, orderBy = "NAME")
Not needed
108. Default values for function parameters
fun query(table: String,
columns: Array<String>,
selection: String? = null,
selectionArgs : Array<String>? = null,
orderBy: String? = null): Cursor {
...
}
// function call
query("USERS", arrayOf("ID", "NAME"), orderBy = "NAME")
111. Lazy property
val preference = getSharedPreferences("pref")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val username = preference.getString("username")
}
112. Lazy property
val preference = getSharedPreferences("pref")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val username = preference.getString("username")
}
Crash, require context
113. Lazy property
val preference by lazy { getSharedPreferences("pref") }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val username = preference.getString("username")
}
Won’t be executed until the
property is first used
114. Lazy property
val preference by lazy { getSharedPreferences("pref") }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val username = preference.getString("username")
}
121. Extension functions
public fun Int.isLollipopOrGreater(): Boolean {.
return this >= Build.VERSION_CODES.LOLLIPOP
}
if (Build.VERSION.SDK_INT.isLollipopOrGreater) {
// ...
}
122. Extension functions
public fun Int.isLollipopOrGreater(): Boolean {.
return this >= Build.VERSION_CODES.LOLLIPOP
}
if (16.isLollipopOrGreater) {
// ...
}
151. Data class
What it does?
Nothing, just hold data
What it provides?
● getters, setters
● equals()/hashCode()
● toString() ofthe form"User(name=John, age=42)"
● copy() function