#sortarray
Explore tagged Tumblr posts
initialcommit · 5 years ago
Photo
Tumblr media
Refresher on how to sort an array in Python, Java, JavaScript, C, and PHP. Follow @initialcommit for more programming content. Check out our website https://initialcommit.io for programming articles, books, live sessions, and how to create your own code-oriented website. #initialcommit #sort #array #sortarray #list #sortlist #python #pythonprogramming #java #javaprogramming #javascript #cprogramming #php #programming #coding #learnprogramming #learncoding #softwaredevelopment https://www.instagram.com/p/CA0L1-hluMh/?igshid=xo0rgc4njz23
0 notes
beautywithcodes · 5 years ago
Video
youtube
How to move negative elements || Competitive Programming
0 notes
myprogrammingsolver · 3 years ago
Text
CS Lab 9 Sorting Solution
CS Lab 9 Sorting Solution
Goal In this lab the performance of basic sorting algorithms will be explored. Resources Chapter 8: An Introduction to Sorting Java Files SortArray.java SortDriver.java The basic sorts have already been implemented in the SortArray class. You will make a new class SortArrayInstrumented that will be based on that class. It will allow you to gather statistics about the sorts. The SortDriver…
Tumblr media
View On WordPress
0 notes
Text
JavaScript:sort()を用いた並び替え方法のサンプル
Tumblr media
JavaScriptで配列内の要素を並び替えたい(ソートしたい)場合に使用するsort()メソッドは、デフォルトでは各要素の文字列比較に基づいて辞書順にソートするため、多くの場合は利用する際に何らかのルールを指定すると思います。 いずれも簡易的にはなりますが、その何らかのルールを用いたsort()の記述サンプルを紹介します。
非破壊ソートを行う
sort()は元の配列内容を変更する破壊的メソッドとなるので、ソート処理は行いたいけど元の配列は別の処理で使うなどの理由でそのまま残しておきたい場合は、処理を行う前にあらかじめ配列を複製しておき、その複製した配列に対して処理を行う必要があります。 配列を複製する方法はいくつかありますが、代表的で且つ短い記述量でできるものとしては下記があります。
JavaScript
// 元の配列 const array = ['red', 'blue', 'yellow', 'green', 'orange']; // slice()で複製 const copyArray01 = array.slice(); // Array.from()で複製 const copyArray02 = Array.from(array); // スプレッド構文で複製 const copyArray03 = [...array];
ちな��に、以下でsort()の使用例をいくつか紹介していきますが、サンプルコードとして記載しているものはいずれもスプレッド構文で複製したものに対して処理を行っています。
数値を基準に昇順・降順に並び替える
数値の大きさで並び替える場合は下記のように記述し、サンプルコードのascArrayで行っている処理が昇順、descArrayで行っている処理が降順となります。
JavaScript
const array = [2, 8, 1, 4, 9, 7, 10, 5, 3, 6]; const ascArray = [...array].sort((a, b) => a - b); console.log(ascArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const descArray = [...array].sort((a, b) => b - a); console.log(descArray); // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
文字列を長さを基準に昇順・降順へ並び替える
文字列の長さで並び替える場合はlengthを使用します。
JavaScript
const array = ['HTML', 'JavaScript', 'Go', 'PHP', 'Python', 'Swift', 'CSS', 'Ruby']; const ascArray = [...array].sort((a, b) => a.length - b.length); console.log(ascArray); // ['Go', 'PHP', 'CSS', 'HTML', 'Ruby', 'Swift', 'Python', 'JavaScript'] const descArray = [...array].sort((a, b) => b.length - a.length); console.log(descArray); // ['JavaScript', 'Python', 'Swift', 'HTML', 'Ruby', 'PHP', 'CSS', 'Go']
日付を基準に昇順・降順へ並び替える
日付で並び替える場合はnew Date()を使用します。
JavaScript
const array = ['1940/10/9', '1967/2/20', '1943/2/25', '1942/6/18', '1969/1/14', '1940/7/7', '1965/5/16']; const ascArray = [...array].sort((a, b) => new Date(a) - new Date(b)); console.log(ascArray); // ['1940/7/7', '1940/10/9', '1942/6/18', '1943/2/25', '1965/5/16', '1967/2/20', '1969/1/14'] const descArray = [...array].sort((a, b) => new Date(b) - new Date(a)); console.log(descArray); // ['1969/1/14', '1967/2/20', '1965/5/16', '1943/2/25', '1942/6/18', '1940/10/9', '1940/7/7']
大文字・小文字関係なくアルファベット順に並び替える
例として下記のような配列があったとします。
JavaScript
const array = ['red', 'Blue', 'yellow', 'green', 'Orange', 'Pink', 'aqua', 'purple', 'White', 'black'];
これをアルファベット順に並び替えとなると、アルファベットはA(a)から始まるので['aqua', 'black', 'Blue', 'green', ...]のようになるのを想定しますが、単純にsort()を実行するだけでは下記のように大文字の文字列が先頭から並びます。
JavaScript
const sortArray = [...array].sort(); console.log(sortArray); // ['Blue', 'Orange', 'Pink', 'White', 'aqua', 'black', 'green', 'purple', 'red', 'yellow']
大文字・小文字関係なくアルファベット順で並び替える場合は下記のようにtoLowerCase()を使用し、一時的に文字列を小文字に変換してから比較を行うことで想定通りのアルファベット順になります。
JavaScript
const sortArray = [...array].sort((a, b) => a.toLowerCase() < b.toLowerCase() ? -1 : 1); console.log(sortArray); // ['aqua', 'black', 'Blue', 'green', 'Orange', 'Pink', 'purple', 'red', 'White', 'yellow']
独自の並びルールに基づいて並び替える
こちらは上で紹介してきたものとは違い、予め並び順の正解となるルール(サンプルコードのorderRule)を用意しておき、その並び順に合わせて指定した配列内の要素を並び替えるものです。
JavaScript
const orderRule = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'], array = ['午', '辰', '卯', '子', '申']; const sortArray = [...array].sort((a, b) => orderRule.indexOf(a) - orderRule.indexOf(b)); console.log(sortArray); // ['子', '卯', '辰', '午', '申']
オブジェクトを並び替える
上で紹介してきたものはすべて配列を例にしてきましたが、もちろんオブジェクトでも使用できます。 ここでは例として下記のようなオブジェクトがあったとします。
JavaScript
const array = [ { id: 5, name: 'Banana', price: 400 }, { id: 1, name: 'Grape', price: 600 }, { id: 3, name: 'Orange', price: 300 }, { id: 4, name: 'Apple', price: 300 }, { id: 2, name: 'Strawberry', price: 300 }, ];
ひとつの値を基準に並び替える
サンプルオブジェクトには5種類の果物がバラバラに格納されていますが、これをpriceの値を基準に昇順へ並び替え���い場合は下記のように記述します。
JavaScript
const sortArray = [...array].sort((a, b) => a.price - b.price); console.log(sortArray); // [ // {id: 3, name: 'Orange', price: 300} // {id: 4, name: 'Apple', price: 300} // {id: 2, name: 'Strawberry', price: 300} // {id: 5, name: 'Banana', price: 400} // {id: 1, name: 'Grape', price: 600} // ]
複数の値を基準に並び替える
並び替えのルールはひとつの値だけでなく複数の値を基準にすることもできます。 例えば、priceの値を基準に降順へ並び替えつつ、priceの値が同じ場合はさらにidの値を基準に昇順へ並び替えたい場合は下記のように記述します。
JavaScript
const sortArray = [...array].sort((a, b) => (b.price - a.price) || (a.id - b.id)); console.log(sortArray); // [ // {id: 1, name: 'Grape', price: 600} // {id: 5, name: 'Banana', price: 400} // {id: 2, name: 'Strawberry', price: 300} // {id: 3, name: 'Orange', price: 300} // {id: 4, name: 'Apple', price: 300} // ]
0 notes
programmingsolver · 5 years ago
Text
Lab 9 Sorting Solution
Lab 9 Sorting Solution
Goal
In this lab the performance of basic sorting algorithms will be explored.
Resources
Chapter 8: An Introduction to Sorting
Java Files
SortArray.java
SortDriver.java
The basic sorts have already been implemented in the SortArray class. You will make a new class
SortArrayInstrumented that will be based on that class. It will allow you to gather statistics about the sorts.
The SortDriver…
View On WordPress
0 notes
arthurknopper · 6 years ago
Text
Pull to Refresh iOS Tutorial
A UIRefreshControl object provides a standard control that can be used to initiate the refreshing of a table view’s contents. When pulled,  a little wheel starts spinning at the top, until the refresh has completed.  At that time, the wheel disappears, and the view bounces back into place. In this tutorial a refresh control will be added to a table view. When the control is pulled the sorting order of the rows will be reversed. This tutorial is made with Xcode 10 and built for iOS 12.
Open Xcode and create a new Single View App.
For product name, use IOSPullToRefreshTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Go to the storyboard. Remove the View Controller from the Storyboard and drag a Navigation Controller to the Scene. This will also add the Table View Controller. Select the Navigation Controller and go to The Attribute inspector. In the View Controller section check the "Is Initial View Controller" checkbox.
Select the Table View Cell and go to the Attributes Inspector. In the Table View Cell section set the Identifier  to "Cell".
The storyboard will look like this.
Since the View Controller is removed from the Storyboard the ViewController.swift file can also be deleted from the project. Add a new file to the project, select iOS->Source->Cocoa Touch Class. Name it TableViewController and make it a subclass of UITableViewController.
The TableViewController class needs to be linked to The Table View Controller object in the Storyboard. Select it and go the Identity Inspector. In the Custom Class section change the class to TableViewController.
Go to TableViewController.swift and create a property containing an array of the first letters of the alphabet.
var alphabet = ["A","B","C","D","E","F","G","H","I"]
The TableViewController class contains some boilerplate code. Change the following delegate methods
override func numberOfSections(in tableView: UITableView) -> Int { // 1 return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 2 return alphabet.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 3 let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = alphabet[indexPath.row] return cell }
There is only one section in the Table View so 1 needs to be returned in the numberOfSections(in:) method.
The number of rows is equal to the number of items in the array so the count property of the array class is used.
The letter of the alphabet at the current index of the apps array is assigned to the text property of the textLabel property of the current cell.
Build and Run the project.
Now that some rows are filled let's get going with the refresh control. If the pull to refresh is initiated the rows sort in descending/ascending order. First a Boolean is needed to switch the sort order. Add the following property in the interface section.
var isAscending = true
Change the viewDidLoad method.
override func viewDidLoad() { super.viewDidLoad() let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(sortArray), for: .valueChanged) self.refreshControl = refreshControl }
Every time the refresh control is pulled the UIControlEvent.ValueChanged event is triggered, which will call the sortArray method. Let's implement this method.
@objc func sortArray() { let sortedAlphabet = alphabet.reversed() for (index, element) in sortedAlphabet.enumerated() { alphabet[index] = element } tableView.reloadData() refreshControl?.endRefreshing() }
First the array is reversed with the reverse function. Then enumerate through the reversed array will be enumerated, where the reversed array will be loaded into the original alphabet array. The Table View is reloaded to update the contents and the RefreshControl animation is ended.
Build and Run, Pull-refresh a few times and the sorting order of the rows in the table view will be reversed.
You can download the source code of the IOSPullToRefreshTutorial at the ioscreator repository on Github
0 notes
beautywithcodes · 5 years ago
Video
youtube
Title How to sort an array || competitive programming
0 notes
myprogrammingsolver · 3 years ago
Text
cs Lab 10 Advanced Sorts Solution
cs Lab 10 Advanced Sorts Solution
Goal In this lab you will build on Quick Sort to write an efficient algorithm for computing order statistics (e.g., median) without sorting the array. Resources Chapter 8: An Introduction to Sorting Chapter 9: Faster Sorting Methods Java Files CheckKth.java SortArray.java The basic and advanced sorts have been implemented in the SortArray class. The class CheckKth will generate some arrays,…
Tumblr media
View On WordPress
0 notes
programmingsolver · 5 years ago
Text
Lab 10 Advanced Sorts Solution
Lab 10 Advanced Sorts Solution
Goal
In this lab you will build on Quick Sort to write an efficient algorithm for computing order statistics (e.g., median) without sorting the array.
Resources
Chapter 8: An Introduction to Sorting
Chapter 9: Faster Sorting Methods
Java Files
CheckKth.java
SortArray.java
The basic and advanced sorts have been implemented in the SortArray class. The class CheckKth will generate some…
View On WordPress
0 notes
myprogrammingsolver · 5 years ago
Text
Lab 10 Advanced Sorts Solution
Lab 10 Advanced Sorts Solution
Goal
In this lab you will build on Quick Sort to write an efficient algorithm for computing order statistics (e.g., median) without sorting the array.
Resources
Chapter 8: An Introduction to Sorting
Chapter 9: Faster Sorting Methods
Java Files
CheckKth.java
SortArray.java
The basic and advanced sorts have been implemented in the SortArray class. The class CheckKth will generate some…
View On WordPress
0 notes
myprogrammingsolver · 5 years ago
Text
Lab 9 Sorting Solution
Lab 9 Sorting Solution
Goal
In this lab the performance of basic sorting algorithms will be explored.
Resources
Chapter 8: An Introduction to Sorting
Java Files
SortArray.java
SortDriver.java
The basic sorts have already been implemented in the SortArray class. You will make a new class
SortArrayInstrumented that will be based on that class. It will allow you to gather statistics about the sorts.
The SortDriver…
View On WordPress
0 notes
myprogrammingsolver · 5 years ago
Text
Lab 10 Advanced Sorts Solution
Goal
In this lab you will build on Quick Sort to write an efficient algorithm for computing order statistics (e.g., median) without sorting the array.
Resources
Chapter 8: An Introduction to Sorting
Chapter 9: Faster Sorting Methods
Java Files
CheckKth.java
SortArray.java
The basic and advanced sorts have been implemented in the SortArray class. The class CheckKth will generate some…
View On WordPress
0 notes
myprogrammingsolver · 5 years ago
Text
Lab 9 Sorting Solution
Goal
In this lab the performance of basic sorting algorithms will be explored.
Resources
Chapter 8: An Introduction to Sorting
Java Files
SortArray.java
SortDriver.java
The basic sorts have already been implemented in the SortArray class. You will make a new class
SortArrayInstrumented that will be based on that class. It will allow you to gather statistics about the sorts.
The SortDriver…
View On WordPress
0 notes
arthurknopper · 8 years ago
Text
Add Pull to Refresh iOS Tutorial
A UIRefreshControl object provides a standard control that can be used to initiate the refreshing of a table view’s contents. When pulled,  a little wheel starts spinning at the top, until the refresh has completed.  At that time, the wheel disappears, and the view bounces back into place. In this tutorial a refresh control will be added to a table view. When the control is pulled the sorting order of the rows will be reversed. This tutorial is made with Xcode 9 and built for iOS 11.
Open Xcode and create a new Single View App.
For product name, use IOS11PullToRefreshTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Go to the storyboard. Remove the View Controller from the Storyboard and drag a Navigation Controller to the Scene. This will also add the Table View Controller. Select the Navigation Controller and go to The Attribute inspector. In the View Controller section check the "Is Initial View Controller" checkbox.
Select the Table View Cell and go to the Attributes Inspector. In the Table View Cell section set the Identifier  to "Cell".
The storyboard will look like this.
Since the View Controller is removed from the Storyboard the ViewController.swift file can also be deleted from the project. Add a new file to the project, select iOS->Source->Cocoa Touch Class. Name it TableViewController and make it a subclass of UITableViewController.
The TableViewController class needs to be linked to The Table View Controller object in the Storyboard. Select it and go the Identity Inspector. In the Custom Class section change the class to TableViewController.
Go to TableViewController.swift and create a property containing an array of the first letters of the alphabet.
var alphabet = ["A","B","C","D","E","F","G","H","I"]
The TableViewController class contains some boilerplate code. Change the following delegate methods
override func numberOfSections(in tableView: UITableView) -> Int { // 1 return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // 2 return alphabet.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 3 let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = alphabet[indexPath.row] return cell }
There is only one section in the Table View so 1 needs to be returned  in the numberOfSections(in:) method.
The number of rows is equal to the number of items in the array so the count property of the array class is used.
The letter of the alphabet at the current index of the apps array is assigned to the text property of the textLabel property of the current cell.
Build and Run the project.
Now that some rows are filled let's get going with the refresh control. If the pull to refresh is initiated the rows sort in descending/ascending order. First a Boolean is needed to switch the sort order. Add the following property in the interface section.
var isAscending = true
Change the viewDidLoad method.
override func viewDidLoad() { super.viewDidLoad() let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(sortArray), for: UIControlEvents.valueChanged) self.refreshControl = refreshControl }
Every time the refresh control is pulled the UIControlEvent.ValueChanged event is triggered, which will call the sortArray method. Let's implement this method.
@objc func sortArray() { let sortedAlphabet = alphabet.reversed() for (index, element) in sortedAlphabet.enumerated() { alphabet[index] = element } tableView.reloadData() refreshControl?.endRefreshing() }
First the array is reversed with the reverse function. Then enumerate through the reversed array will be enumerated, where the reversed array will be loaded into the original alphabet array. The Table View is reloaded to update the contents and the RefreshControl animation is ended.
Build and Run, Pull-refresh a few times and the sorting order of the rows in the table view will be reversed.
You can download the source code of the IOS11PullToRefreshTutorial at the ioscreator repository on Github
0 notes