<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Julien C. on Medium]]></title>
        <description><![CDATA[Stories by Julien C. on Medium]]></description>
        <link>https://medium.com/@julien-ctx?source=rss-8dc29ec18b8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ERETAaW_eaeQHFlKeBl8Nw.png</url>
            <title>Stories by Julien C. on Medium</title>
            <link>https://medium.com/@julien-ctx?source=rss-8dc29ec18b8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:15:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@julien-ctx/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SwiftUI: Creating a Smooth Button Scale Animation on Tap]]></title>
            <link>https://medium.com/@julien-ctx/swiftui-creating-a-smooth-button-scale-animation-on-tap-eee893495661?source=rss-8dc29ec18b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eee893495661</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Julien C.]]></dc:creator>
            <pubDate>Sat, 21 Dec 2024 16:22:19 GMT</pubDate>
            <atom:updated>2024-12-21T16:22:19.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="button scale animation swiftui" src="https://cdn-images-1.medium.com/max/450/1*iWAi2rQDJ8XuFneqhPkkPg.gif" /><figcaption>A smooth button scale animation in SwiftUI</figcaption></figure><p>Have you ever noticed how satisfying Instagram’s like animation is? Every time you press the <em>like button</em>, the small heart icon briefly scales up and down, while a larger heart appears on your screen.</p><p>This kind of user feedback is important to <strong>improve user experience</strong> and create a real link between the user and the app. It’s a good way to engage users into doing some kind of action.</p><p>In this article, we’ll focus on the <strong>button scale animation</strong>, as shown in the GIF above. You’ll learn <strong>two methods</strong> to achieve this using SwiftUI, and how to customize it according to your needs.</p><h3>The clean way to create a zoom animation when tapping a button</h3><p>I explored various methods to achieve this animation, and this is the cleanest and most reliable approach I found.</p><p>As many iOS developers are using <strong>MVVM</strong> or <strong>MV</strong> structure with SwiftUI, I created <em>LikeButtonView</em> along with <em>LikeButtonViewModel</em>. No data model has been created for this simple example.</p><pre>import SwiftUI<br><br>struct LikeButtonView: View {<br>    @ObservedObject private var viewModel: LikeButtonViewModel<br><br>    init(<br>        isLiked: Bool,<br>        toggleLike: @escaping () -&gt; Void<br>    ) {<br>        _viewModel = ObservedObject(<br>            wrappedValue: LikeButtonViewModel(<br>                isLiked: isLiked,<br>                toggleLike: toggleLike<br>            )<br>        )<br>    }<br>    <br>    var body: some View {<br>        Button {<br>            viewModel.toggleLikeWithAnimation()<br>        } label: {<br>            Image(systemName: viewModel.heartIcon)<br>                .foregroundStyle(viewModel.heartIconColor)<br>                .scaleEffect(viewModel.scale)<br>        }<br>    }<br>}</pre><p>As you can see, you have to use the view like this: LikeButtonView(isLiked: Bool, toggleLike: () -&gt; Void) .</p><ul><li>isLiked is an observable variable from the parent view model (marked with <em>Published</em> wrapper usually).</li><li>toggleLike is a closure which… toggles isLiked boolean in the parent view model.</li></ul><p>In fact, isLiked is not a mutable variable in our LikeButton component. The parent handles the changes and LikeButtonView is rerendered whenever isLiked property has changed in the view model of the calling view — that’s why the viewModel variable is marked with ObservedObject and not StateObject.</p><p>Here is the view model:</p><pre>import SwiftUI<br><br>class LikeButtonViewModel: ObservableObject {<br>    @Published var scale = 1.0<br>    <br>    let isLiked: Bool<br>    let toggleLike: () -&gt; Void<br>    <br>    var heartIcon: String {<br>        isLiked ? &quot;heart.fill&quot; : &quot;heart&quot;<br>    }<br>    <br>    var heartIconColor: Color {<br>        isLiked ? .red : .gray<br>    }<br>    <br>    func toggleLikeWithAnimation() {<br>        withAnimation(.linear(duration: 0.1)) {<br>            scale = 1.2<br>        }<br>        withAnimation(.linear(duration: 0.1).delay(0.1)) {<br>            scale = 1.0<br>        }<br>        toggleLike()<br>    }<br>    <br>    init(isLiked: Bool, toggleLike: @escaping () -&gt; Void) {<br>        self.isLiked = isLiked<br>        self.toggleLike = toggleLike<br>    }<br>}</pre><p>As demonstrated, the logic is managed in the view model, where we have computed properties for the color and icon based on the isLiked value.</p><p>The main animation behavior is also controlled by the view model. In the view, the button’s image is modified with the .scaleEffect(viewModel.scale) modifier.</p><p>The default value of scale is 1.0. Whenever you tap the button, viewModel.toggleLikeWithAnimation() is triggered. But what is the purpose of it?</p><pre>withAnimation(.linear(duration: 0.1)) {<br>  scale = 1.2<br>}<br>withAnimation(.linear(duration: 0.1).delay(0.1)) {<br>  scale = 1.0<br>}</pre><p>First, scale goes from default value <em>1.0</em> to <em>1.2</em> with a linear animation of 0.1 second. We also schedule another animation, 0.1 second later, which assigns scale value to <em>1.0</em>, from current value (<em>1.2</em> at the time).</p><p>It creates a quick <strong>scale-in</strong> and <strong>scale-out</strong> animation whenever the user taps the button.</p><h3>Another way to create a button with zoom animation</h3><p>Alternatively, you can also create a button style to achieve a similar <strong>bump effect</strong>.</p><pre>extension ButtonStyle where Self == ScaleButtonStyle {<br>    static var scaleButtonStyle: Self {<br>        Self()<br>    }<br>}<br><br>struct ScaleButtonStyle: ButtonStyle {<br>    func makeBody(configuration: Self.Configuration) -&gt; some View {<br>        configuration.label<br>            .scaleEffect(configuration.isPressed ? 1.2 : 1.0)<br>    }<br>}</pre><p>You can apply .buttonStyle(.scaleButtonStyle) modifier on every button you want to animate. It’s quite simple in the concept: pressing the button changes the scale of its label with .scaleEffect(configuration.isPressed ? 1.2 : 1.0) .</p><p>Here is the way to use it:</p><pre>Button {<br>  viewModel.toggleLike()<br>} label: {<br>  Image(systemName: viewModel.heartIcon)<br>    .foregroundStyle(viewModel.heartIconColor)<br>}<br>.buttonStyle(.scaleButtonStyle)</pre><p>However, you’ll notice that <strong>the animation isn’t as smooth</strong> as the previous solution. Additionally, I observed that if you tap the button on the edges of the touchable area, the animation sometimes doesn’t trigger at all.</p><p>This solution is relevant if you quickly want to implement a button which <strong>scales up and comes back to its original size</strong>. However, it may not be the most relevant in case you want to have control over animation type and duration.</p><p><em>Did you like this article? You can let me know by different ways:</em></p><ul><li><em>Clap the article.</em></li><li><em>Comment your thoughts on my story.</em></li><li><em>Subscribe to my account.</em></li><li><em>Follow me on </em><a href="https://github.com/julien-ctx"><em>GitHub</em></a><em>.</em></li></ul><p><em>You can also </em><a href="https://medium.com/@julien-ctx/subscribe"><em>subscribe to my newsletter</em></a><em> to receive my latest posts in your mailbox.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eee893495661" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating SQLite with React Native: A Beginner’s Tutorial]]></title>
            <link>https://medium.com/@julien-ctx/integrating-sqlite-with-react-native-a-beginners-tutorial-a74bbe34ac6a?source=rss-8dc29ec18b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a74bbe34ac6a</guid>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Julien C.]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 16:54:12 GMT</pubDate>
            <atom:updated>2023-11-12T16:54:12.018Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to seamlessly integrate SQLite into your React Native application, ensuring efficient and persistent data storage. This approach is perfect for offline-first mobile applications or projects without a backend.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lIQbCIkYfVJBv4RC" /><figcaption>Photo by <a href="https://unsplash.com/@alvarordesign?utm_source=medium&amp;utm_medium=referral">Alvaro Reyes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>SQLite is widely used to store data persistently in web and mobile applications. It’s <strong><em>lightweight</em></strong>, <strong><em>serverless</em></strong> and requires <strong><em>no configuration</em></strong>! That’s the reason why so many developers choose to use it.</p><p>If you want to store user preferences of simple data structures in your React Native app, it can be relevant to use SQLite. No server setup or extensive documentation needed — this article is a <strong>straight-to-the-point tutorial</strong>.</p><p>Here’s a quick overview of things you’ll learn today:</p><ul><li>Install and configure your SQLite database</li><li>Create tables and / or delete them</li><li>Read and update tables</li></ul><h3>Install and configure SQLite for React Native</h3><p>To make it easier, we’ll use <a href="https://github.com/andpor/react-native-sqlite-storage#react-native-sqlite-storage">react-native-sqlite-storage</a>, a great library that provides all the methods we need to store data with SQLite database engine.</p><p>You can install this package with one of the following commands:</p><ul><li>npm install --save react-native-sqlite-storage (with <em>npm</em>)</li><li>yarn add react-native-sqlite-storage (with <em>yarn</em>)</li></ul><p>There are additional steps to finish configuring this external library, but they depend on your version of React Native. Open your package.json file and look for the version you’re using.</p><h4>React Native version 0.60 or higher</h4><p>Use the following command at the root of the repository to configure the library for <strong>iOS</strong> as well: cd ios &amp;&amp; pod install &amp;&amp; cd .. . Nothing else is required!</p><h4>React Native version below 0.60</h4><p>For older versions, both iOS and Android projects need to be configured correctly in order to use the package. Look at the <a href="https://github.com/andpor/react-native-sqlite-storage#step-1-install-dependencies">official documentation</a> to know what you really need to know according to your application requirements.</p><h3>Open the SQLite database and create tables</h3><p>Now that react-native-sqlite-storage is installed in your project, you’re ready to create your first tables.</p><p>In this tutorial, we will create <strong>2 distinct tables</strong>.</p><ul><li>The first, named UserPreferences, will hold a single record. This record will be updated whenever there’s a change in the user preferences, ensuring that no new entries are added.</li><li>The second, named Contacts , will be used to insert or delete contacts in our app. Each contact contains several details like first name, name and phone number.</li></ul><p>Knowing this, you can go to the root of your project, then go to app folder, and create another folder called db . It’s going to be the folder which will contain all our methods to create, read, edit and delete data.</p><p>If you intend to create a lot of tables, it would be a good idea to create <strong>a file for each table</strong>. For example, in our case, we can create a file called userPreferences.ts and another one called contacts.ts in db folder. A last one, db.ts , will be used for general actions.</p><h4>Get access to the database</h4><blockquote>Before creating tables, you need to establish a connection with the SQLite database stored on the device.</blockquote><p>To do so, you can import the library we previously installed and use the following function:</p><pre>// app/db/db.ts<br><br>import {<br>  enablePromise,<br>  openDatabase,<br>} from &quot;react-native-sqlite-storage&quot;<br><br>// Enable promise for SQLite<br>enablePromise(true)<br><br>export const connectToDatabase = async () =&gt; {<br>  return openDatabase(<br>    { name: &quot;yourProjectName.db&quot;, location: &quot;default&quot; },<br>    () =&gt; {},<br>    (error) =&gt; {<br>      console.error(error)<br>      throw Error(&quot;Could not connect to database&quot;)<br>    }<br>  )<br>}</pre><p>Before carrying out any operations, it’s necessary to connect to the database using the function mentioned earlier. This allows you to save the return value in a variable, for example: const db = await connectToDatabase().</p><p>This variable, will be given as an argument to other functions we will create in this article.</p><p><em>NB: you can edit the project name, the location, the success callback (</em><em>() =&gt; {}) and the error callback according to your needs.</em></p><h4>Create data tables</h4><p>The SQLite statement I recommend to create tables is CREATE TABLE IF NOT EXISTS . It’s the best way to avoid any error because it checks if the table already exists before creating it.</p><p>Do you remember our function connectToDatabase ? It returns a SQLiteDatabase object which contains executeSql method. This is what we need to execute SQLite commands! Here is the function you can create to initialize your first tables:</p><pre>// app/db/db.ts<br><br>export const createTables = async (db: SQLiteDatabase) =&gt; {<br>  const userPreferencesQuery = `<br>    CREATE TABLE IF NOT EXISTS UserPreferences (<br>        id INTEGER DEFAULT 1,<br>        colorPreference TEXT,<br>        languagePreference TEXT,<br>        PRIMARY KEY(id)<br>    )<br>  `<br>  const contactsQuery = `<br>   CREATE TABLE IF NOT EXISTS Contacts (<br>      id INTEGER PRIMARY KEY AUTOINCREMENT,<br>      firstName TEXT,<br>      name TEXT,<br>      phoneNumber TEXT<br>   )<br>  `<br>  try {<br>    await db.executeSql(userPreferencesQuery)<br>    await db.executeSql(contactsQuery)<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(`Failed to create tables`)<br>  }<br>}</pre><p>As tables are created only once, createTables function can be used within a useEffect in App.tsx or App.js . In fact, it should be part of the app’s initialization process and should be called as soon as possible in the React Native code.</p><p>You can do something like this:</p><pre>// App.tsx or App.js<br><br>const loadData = useCallback(async () =&gt; {<br>  try {<br>    const db = await connectToDatabase()<br>    await createTables(db)<br>  } catch (error) {<br>    console.error(error)<br>  }<br>}, [])<br><br>useEffect(() =&gt; {<br>  loadData()<br>}, [loadData])</pre><h4>Display and delete tables</h4><p>When testing your mobile application, it’s essential to implement two more functions: one to <strong>delete tables</strong> and another to <strong>view the tables</strong> currently present in the SQLite database.</p><pre>// app/db/db.ts<br><br>export const getTableNames = async (db: SQLiteDatabase): Promise&lt;string[]&gt; =&gt; {<br>  try {<br>    const tableNames: string[] = []<br>    const results = await db.executeSql(<br>      &quot;SELECT name FROM sqlite_master WHERE type=&#39;table&#39; AND name NOT LIKE &#39;sqlite_%&#39;&quot;<br>    )<br>    results?.forEach((result) =&gt; {<br>      for (let index = 0; index &lt; result.rows.length; index++) {<br>        tableNames.push(result.rows.item(index).name)<br>      }<br>    })<br>    return tableNames<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(&quot;Failed to get table names from database&quot;)<br>  }<br>}<br><br>export const removeTable = async (db: SQLiteDatabase, tableName: Table) =&gt; {<br>  const query = `DROP TABLE IF EXISTS ${tableName}`<br>  try {<br>    await db.executeSql(query)<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(`Failed to drop table ${tableName}`)<br>  }<br>}</pre><p>You certainly noticed that I used Table type instead of string in removeTable function. This is a type containing all the table names you’re using in your app. It is important to specify it instead of string because otherwise it can lead to potential security issues.</p><p>In our case, Table looks like this: type Table = &quot;Contacts&quot; | &quot;UserPreferences&quot; . You can create your types in a .typing.ts file and export every type you create to reuse them later.</p><h3>CRUD operations with SQLite in React Native</h3><p>Now that our tables have been created, we are ready to handle <strong>Create, Read, Update and Delete operations</strong> and dive into the most interesting part of this tutorial.</p><h4>Insert data into a table</h4><p>The first thing you want to do when you have created your tables is adding data into it, right? Well, we can use SQLite INSERT INTO for that. For the Contacts table, is pretty straight-forward:</p><pre>// app/db/contacts.ts<br><br>export const addContact = async (db: SQLiteDatabase, contact: Contact) =&gt; {<br>  const insertQuery = `<br>   INSERT INTO Contacts (firstName, name, phoneNumber)<br>   VALUES (?, ?, ?)<br> `<br>  const values = [<br>    contact.firstName,<br>    contact.name,<br>    contact.phoneNumber,<br>  ]<br>  try {<br>    return db.executeSql(insertQuery, values)<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(&quot;Failed to add contact&quot;)<br>  }<br>}</pre><p>If you’re not familiar with SQLite command syntax, it’s important to know that ? placeholders are replaced by the values specified in the values array. The order of these values needs to be in accordance with the query, as they are taken exactly as provided.</p><p>The query creates a new row in the Contacts database, containing all the information of your new contact. It is very simple and this approach works for all array-like tables.</p><blockquote>However, we also have the take care of our userPreferences <strong>single-row table</strong>. What we want to do is inserting a new row containing the user preferences if it doesn’t exist, otherwise update the first row.</blockquote><p>Since 2018, SQLite provides INSERT...ON CONCLICT which is perfect to perform some actions when there is already a row containing user preferences. This command is available since <em>SQLite version 3.24.0</em> and it will be suitable for most <strong>modern iOS and Android devices</strong>.</p><p>In the following function, were are updating a single user preference, whether the <em>theme color</em> or the <em>language</em>. We are targeting the id = 1 because this is the <strong>primary key </strong>for our user preferences table row.</p><p>It first tries to insert into UserPreferences table a new row with id = 1 and the new user preference you’re trying to add. If there is no row with id = 1 , there is no conflict and the new data is inserted, otherwise it just updates the row with the new value.</p><p><em>NB: the conflict is triggered when we try to insert another row with the same </em><em>id as an existing one, because the table uses </em><em>id as the primary key. It means that each row should have a unique </em><em>id .</em></p><pre>// app/db/userPreferences.ts<br><br>type SingleUserPreference = &quot;colorPreference&quot; | &quot;languagePreference&quot;<br><br>// This function works for both inserting and updating one user preference<br>// It can be color preference or language preference<br>export const updateSingleUserPreference = async (<br>  db: SQLiteDatabase,<br>  singleUserPreference: SingleUserPreference,<br>  newValue: string<br>) =&gt; {<br>  const query = `<br>      INSERT INTO UserPreferences (id, ${singleUserPreference})<br>      VALUES (1, ?)<br>      ON CONFLICT(id) DO UPDATE SET ${singleUserPreference} = ?<br>  `<br>  try {<br>    return db.executeSql(query, [newValue, newValue])<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(`Failed to update ${singleUserPreference}`)<br>  }<br>}</pre><h4>Read data from the database</h4><p>Now that you can populate your tables with data, the next question is: <em>How do you access this data?</em> In a <strong>React Native</strong> app, reading from an <strong>SQLite database</strong> is accomplished using the SELECT keyword.</p><p>To get all rows of a table, you can use SELECT * FROM Table . That is what we’re going to use to get the full array of contacts in our app.</p><pre>// app/db/contacts.ts<br><br>export const getContacts = async (db: SQLiteDatabase): Promise&lt;Contact[]&gt; =&gt; {<br>  try {<br>    const contacts: Contact[] = []<br>    const results = await db.executeSql(&quot;SELECT * FROM Contacts&quot;)<br>    results?.forEach((result) =&gt; {<br>      for (let index = 0; index &lt; result.rows.length; index++) {<br>        contacts.push(result.rows.item(index))<br>      }<br>    })<br>    return contacts<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(&quot;Failed to get Contacts from database&quot;)<br>  }<br>}</pre><p>As demonstrated, we store each element of each row, which represents an individual contact, in an array. This allows us to return a TypeScript variable that can be utilized in our React Native app for <strong>displaying contact information</strong>.</p><p>For user preferences, the process is nearly identical, but it’s important to specify the id (which should be set to 1) to ensure accuracy and avoid any mistakes.</p><pre>// app/db/userPreferences.ts<br><br>export const getUserPreferences = async (<br>  db: SQLiteDatabase,<br>) =&gt; {<br>  const query = `SELECT * FROM UserPreferences WHERE id = 1`<br>  try {<br>    const results = await db.executeSql(query)<br>    if (results[0]?.rows?.length) {<br>      return results[0].rows.item(0)<br>    } else {<br>      return null<br>    }<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(&quot;Failed to get user preferences from database&quot;)<br>  }<br>}<br><br>// Here is another version if you need to retrieve only one user preference.<br><br>export const getSingleUserPreference = async (<br>  db: SQLiteDatabase,<br>  userPreference: SingleUserPreference<br>): Promise&lt;string | null&gt; =&gt; {<br>  const query = `SELECT ${userPreference} FROM UserPreferences WHERE id = 1`<br>  try {<br>    const results = await db.executeSql(query)<br>    if (results[0]?.rows?.length) {<br>      return results[0].rows.item(0)[userPreference]<br>    } else {<br>      return null<br>    }<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(`Failed to get ${userPreference} from database`)<br>  }<br>}</pre><p>Keep in mind that each row can contain multiple columns. That’s why we use item(0) in the functions mentioned earlier.</p><h4>Update rows in SQLite tables</h4><p>Now that you know how to store and access data in your React Native app, you may need to update it as well. Good news, UPDATE command does the job perfectly.</p><p>Returning to our examples of the phone contact list and user preferences, when you need to update a specific contact, it’s necessary to instruct <strong>SQLite</strong> which variable should be used to identify and access the contact’s information.</p><p>A common method for pinpointing the data to be edited is by using the WHERE keyword in conjunction with the primary key of the table. For instance, in our contact table, each row has a unique id. We can then use WHERE id = ? .</p><pre>// app/db/contacts.ts<br><br>export const updateContact = async (<br>  db: SQLiteDatabase,<br>  updatedContact: Contact<br>) =&gt; {<br>  const updateQuery = `<br>    UPDATE Contacts<br>    SET firstName = ?, name = ?, phoneNumber = ?<br>    WHERE id = ?<br>  `<br>  const values = [<br>    updatedContact.firstName,<br>    updatedContact.name,<br>    updatedContact.phoneNumber,<br>    updatedContact.id,<br>  ]<br>  try {<br>    return db.executeSql(updateQuery, values)<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(&quot;Failed to update contact&quot;)<br>  }<br>}</pre><p>You might have noticed that the function used for inserting a user preference is named updateSingleUserPreference. This name was chosen because the function is designed not only to insert the row initially but also to update it when it already exists. Consequently, there&#39;s no need to create an additional function for this purpose.</p><h4>Delete persistent data in the database</h4><p>The last operation you need to learn when you use SQLite with React Native is <strong>deleting</strong>. Again, there is a DML command for this purpose, and its name is DELETE .</p><p>Similar to the processes for <strong>reading and updating</strong>, when deleting data, you need to provide a specific condition for the database to match in order to delete the correct table row.</p><p>In the case of a contact list, this could be the phone number or any other relevant information that serves as a <strong>unique key</strong>.</p><pre>// app/db/contacts.ts<br><br>export const deleteContact = async (db: SQLiteDatabase, contact: Contact) =&gt; {<br>  const deleteQuery = `<br>    DELETE FROM Contacts<br>    WHERE id = ?<br>  `<br>  const values = [contact.id]<br>  try {<br>    return db.executeSql(deleteQuery, values)<br>  } catch (error) {<br>    console.error(error)<br>    throw Error(&quot;Failed to remove contact&quot;)<br>  }<br>}</pre><p>It does not make sense to remove the user preferences, as we always need to know the theme color to display, or the language to use in the app. That’s why I only show you how to delete a contact in the Contacts table.</p><p>That’s all you need to know to get started with <strong>SQLite data manipulation in React Native</strong>, and this tutorial will be enough for most cases. If you need help with a specific case, feel free to leave a comment!</p><p><em>Did you like this article? You can let me know by different ways:</em></p><ul><li><em>Clap the article.</em></li><li><em>Comment your thoughts on my story.</em></li><li><em>Subscribe to my account.</em></li><li><em>Follow me on </em><a href="https://github.com/julien-ctx"><em>GitHub</em></a><em>.</em></li></ul><p><em>You can also </em><a href="https://medium.com/@julien-ctx/subscribe"><em>subscribe to my newsletter</em></a><em> to receive my latest posts in your mailbox.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a74bbe34ac6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Clone, Build, and Run a React Native App from a GitHub Repository?]]></title>
            <link>https://medium.com/@julien-ctx/how-to-clone-build-and-run-a-react-native-app-from-a-github-repository-7ab781e52a14?source=rss-8dc29ec18b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ab781e52a14</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Julien C.]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 19:29:50 GMT</pubDate>
            <atom:updated>2023-11-07T19:31:54.231Z</atom:updated>
            <content:encoded><![CDATA[<h4>Over the past weeks, while developing a React Native app, I needed to transfer it to a different Git repository. In the process, I discovered that cloning the app from the original repo wasn’t enough to build and run it successfully. But what was missing?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UWNLcPZtpzWCCVVt" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=medium&amp;utm_medium=referral">Marvin Meyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Building without errors on iOS</h3><p>My React Native app has been developed in a bare workflow, without Expo and only a few external libs. In my mind, it was impossible to have build related issues when cloning the project from a remote repository… But I’ve had several!</p><h4>Common build errors</h4><p>After cloning the project, I immediately used yarn install to setup the environment and the dependencies. Then, I typed yarn ios and hit Enter, which executed the react-native run-ios command.</p><p>The latter command, provided by the React Native CLI does a bunch of things, including compiling the project with XCode and opening it in the iOS Simulator — <em>perfect, that’s what I want to do!</em></p><p>The XCode workspace was found and the emulator started as well, but I quickly had the following error:</p><pre>error Failed to build iOS project. We ran &quot;xcodebuild&quot; command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening project.xcworkspace.</pre><p>Even if I used yarn install to install modules on the Javascript side, I also had to install dependencies in the native iOS app. And the command we use for that purpose is pod install .</p><p>Therefore, all you need to do to fix the error above is cd ios &amp;&amp; pod install . You’ll see several green lines on the screen displaying the tasks performed by the command.</p><p>If you don’t see them, it seems that the issue is somewhere else 😱 But don’t worry, you can still try the commands I wrote a little further down in the article, in the <strong><em>Common runtime errors</em></strong> section.</p><blockquote>As a React Native developer, it’s easy to overlook the native components of a project, even though errors can arise outside of the JavaScript framework as well.</blockquote><p>Even if it may sound ridiculous, it took me a bit of time to figure out the origin of this error. So, hopefully, this tutorial can help you save time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vac8A0g6QIDeb_ch" /><figcaption>Photo by <a href="https://unsplash.com/@nublson?utm_source=medium&amp;utm_medium=referral">Nubelson Fernandes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Common runtime errors</h4><p>Another common error is No bundle URL present. . In this case, it is not a build error but rather a runtime one. Good news, there is a command that can help you fix it very quickly:</p><pre>rm -rf ios/build/; kill $(lsof -t -i:8081); react-native run-ios</pre><p>Sometimes, it is not enough, and you’ll need to wipe the data of the simulator as well. Fortunately, there is a simple command to do that too! All you have to do is close the simulator and run xcrun simctl erase all, followed by yarn ios to build and run again.</p><p>This command is well known in the React Native community because it solves a lot of problems. In fact, it resets the simulator and removes the residual configuration and storage.</p><p>If your problem is still not solved with the previous methods, here are two more commands you can try:</p><ul><li>rm -rf ~/Library/Developer/Xcode/DerivedData : remove all object files and intermediate build information of all projects. It prevents using corrupted or outdated data in the new builds.</li><li>rm -rf ios/build : it cleans the build ouput of the current project, ensuring that no previous build data is causing any conflict.</li></ul><p>After that, try to build again using yarn ios (or npm run ios if you use <strong>npm</strong>). If an error still occurs, don’t hesitate to leave a comment below, the community and I can help you!</p><h3>Building without errors on Android</h3><p>Whether you want to build on an Android virtual device or on a physical smartphone, some errors can arise. After using yarn install , if you use yarn android (react-native run-android), you might have the following error:</p><pre>Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain</pre><p>In that case, go to android/gradle/wrapper folder. Ensure you have a file called gradle-wrapper.jar . If not, then your .gitignore file may have ignored it. This file needs to be pushed on the remote repository to allow users to build and run the project successfully on Android.</p><p>If the repository is not yours, or even if its yours and you do not have the gradle-wrapper.jar file, you need to generate it. To do so, you can use brew to install gradle with the command brew install gradle .</p><blockquote>NB: if you use a Mac with a M1 chip, you need to check your architecture with arch command. If it doesn’t display arm64 , then use $env /usr/bin/arch -arm64 /bin/zsh ---login before installing gradle.</blockquote><p>After the installation, go to android folder, type gradle wrapper and press Enter. Then, verify that android/gradle/wrapper/gradle-wrapper.jar has been generated. If so, you can build and run your app just like you usually do!</p><p>If you encounter version conflicts, be sure to check the <a href="https://docs.gradle.org/current/userguide/gradle_wrapper.html">well-documented resources</a> that Gradle provides on its commands. It offers options that can be useful to specify the version you want to use.</p><p>In case you’re using libraries with native dependencies, additional steps are required to make the app work correctly. In fact, linking is necessary and you can do it with react-native link at the root of your project.</p><h3>Fixing Husky errors</h3><p>If, like me, you use <a href="https://github.com/typicode/husky">Husky</a> to automate tasks before committing, like <em>linting</em>, <em>testing</em>, or <em>formatting</em>, you may encounter difficulties when trying to commit after cloning a project from a Git repository.</p><p>For example, I personnally had the following error when I tried to commit from a recently cloned project:</p><pre>.husky/pre-commit: line 2: .husky/_/husky.sh: No such file or directory</pre><p>The common fix for this error is this command: npx husky-init . However, don’t forget to save the content of .husky/pre-commit file, because it will be overwritten by previous the command.</p><p>To make it simple, you can copy and paste .husky/pre-commit file to the root of your repository (and push it to your repo as well), and eventually add this to your package.json scripts:</p><pre>&quot;init-husky&quot;: &quot;npx husky-init &amp;&amp; rm .husky/pre-commit &amp;&amp; cp pre-commit .husky&quot;</pre><p>With this script, every time you clone the project, you can run yarn init-husky to configure it and make it usable.</p><p>Ultimately, to avoid all the issues I talked about in this article, you can even add a more global script which automates everything you need to successfully build and launch your mobile from a GitHub repo. Here is the one I use:</p><pre>&quot;setup&quot;: &quot;yarn install &amp;&amp; cd ios &amp;&amp; pod install &amp;&amp; cd .. &amp;&amp; npx husky-init &amp;&amp; rm .husky/pre-commit &amp;&amp; cp pre-commit .husky&quot;</pre><p>yarn setup is now enough to get your project build-ready! After the packages load, you can run yarn ios or yarn android to continue developing or testing your mobile application.</p><p><em>Did you like this article? You can let me know by different ways:</em></p><ul><li><em>Clap the article.</em></li><li><em>Comment your thoughts on my story.</em></li><li><em>Subscribe to my account.</em></li><li><em>Follow me on </em><a href="https://github.com/julien-ctx"><em>GitHub</em></a><em>.</em></li></ul><p><em>You can also </em><a href="https://medium.com/@julien-ctx/subscribe"><em>subscribe to my newsletter</em></a><em> to receive my latest posts in your mailbox.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab781e52a14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add Numbers Without Plus Sign (+) ?]]></title>
            <link>https://medium.com/@julien-ctx/how-to-add-numbers-without-plus-sign-d543b46c9aa4?source=rss-8dc29ec18b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d543b46c9aa4</guid>
            <category><![CDATA[binary]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[boolean]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Julien C.]]></dc:creator>
            <pubDate>Wed, 24 May 2023 15:13:10 GMT</pubDate>
            <atom:updated>2023-11-07T19:31:04.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Add Numbers Without Plus Sign (+) ?</h3><h4>Addition is a common mathematical operation, but do you really know what it represents in binary? You will discover it in this article.</h4><figure><img alt="adding numbers without plus sign" src="https://cdn-images-1.medium.com/max/1024/0*Nnl_wgsM8jzxSxTE" /><figcaption>Photo by <a href="https://unsplash.com/de/@profwicks?utm_source=medium&amp;utm_medium=referral">Ben Wicks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Contrary to what you might think, <strong>+ sign</strong> is not necessary to perform additions between integers. In fact, <strong>binary operators</strong> &lt;&lt;, &gt;&gt;, &amp;, | and ^ are sufficient to perform this mathematical operation, and I will show you how to use them.</p><p>To make the explanations as clear as possible, I will code a function called <em>adder</em> in <a href="https://www.rust-lang.org/tools/install">Rust</a>, which allows <strong>bitwise operations</strong> over integer types. But even if you don’t know Rust, you will have no trouble understanding the tutorial!</p><h3>Understanding 32-bit unsigned integer binary structure</h3><pre>fn adder(a: u32, b: u32) -&gt; u32;</pre><p>As you can see in the function’s prototype above, we want to add 32-bit unsigned integers and return the same type. Therefore, each decimal number is composed of 32 bits (1 or 0), representing a <strong>power of 2</strong>.</p><p>For example, 1011(2) is <em>1 * 2⁰ + 1 * 2¹ + 0 * 2² + 1 * 2³ = 1 + 2 + 0 + 8</em> = <strong>11</strong>. We start from the <strong>rightmost bit</strong>, and we then add the successive results to get the final value in decimal. This concept will be useful for the tutorial.</p><figure><img alt="add numbers without plus sign" src="https://cdn-images-1.medium.com/max/1024/1*FYNlJAtQJCNcQ7OpatzUww.png" /><figcaption>Conversion from binary to decimal.</figcaption></figure><h3>Implementing the binary addition system</h3><p>Let’s take <em>29</em> and <em>9</em>. Their binary representations are 011101(2) and 001001(2). Now, we want to add them, but <strong>without + operator</strong>!</p><p>To do so, we have to perform a <strong>bitwise addition</strong>, but that kind of mathematical operation follows specific rules that are a bit different than decimal addition rules.</p><figure><img alt="binary addition rules" src="https://cdn-images-1.medium.com/max/1024/1*XcecpyRkDApyQJVzebNZYg.png" /><figcaption>Binary addition rules.</figcaption></figure><p>To understand how to use it more easily, let’s put the 2 binary numbers one above the other, like this:</p><figure><img alt="add 2 bits" src="https://cdn-images-1.medium.com/max/806/1*9PezRw0u6qy2wGQ-HNuJ6A.png" /></figure><p><em>Result</em> is the binary notation of the addition we want to perform — i.e 38. To compute it, we have to make <strong>bitwise additions</strong>, starting from the rightmost bits, using the rules I gave you previously.</p><p>But remember, <strong>we cannot use + sign!</strong> Therefore, we have to find a way to get the same <em>result</em> as the binary addition table, only with <strong>bitwise operators</strong>.</p><h4>Formula to get the binary result</h4><p>To get the result, we will use ^ operator (<strong>XOR</strong>, or eXclusive OR). <em>a ^ b</em> returns 1 if only one of the 2 variables is equal to 1. Otherwise, it returns 0. But in our case, we have an additional variable to take into account: the <strong>carry over bit</strong>.</p><blockquote>The carry over bit is a bit set to 0 at the beginning. Each time the addition of the 2 integers bits and the carry over bit is greater or equal to 2, the carry over bit is set to 1. It will then be used for the next bit addition.</blockquote><p>Therefore, the formula to get the resulting bit value for each bitwise addition is the following one: <strong>binary_result = a_bit ^ b_bit ^ carry_over</strong>. It gives the same output as in the binary addition table.</p><p>To implement this in Rust, we have to create a loop to apply the XOR operations between each of the <strong>32 bits</strong>. Here is the following code equivalent:</p><pre>fn adder(a: u32, b: u32) -&gt; u32 {<br>    let mut result = 0;<br>    let mut carry_over = 0;<br><br>    for i in 0..32 {<br>        // Formula to get the i-th bit of the first number, from the right.<br>        let a_bit = a &gt;&gt; i &amp; 1;<br>        // Formula to get the i-th bit of the second number, from the right.<br>        let b_bit = b &gt;&gt; i &amp; 1;<br>        // Binary result that will be stored in the total number called result<br>        let binary_result = a_bit ^ b_bit ^ carry_over;<br>    }<br>}</pre><h4>Formula to get the carry over</h4><p>As you can understand with the binary addition rules, the carry over will be 1 only if at least 2 bits among the 3 (first number bit, second number bit and current carry over bit) are equal to 1.</p><p>We can easily represent the situation with the use of <strong>| operator</strong> (OR). This operator returns 1 if at least one of the variables is 1. Otherwise, it returns 0. Here is the implementation:</p><pre>carry_over = (a_bit &amp; b_bit) | (a_bit &amp; carry_over) | (b_bit &amp; carry_over);</pre><p>Now, we have everything we need to calculate the binary digits of the number we want to calculate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*tJmYWQlKasUrmhEFVcUBkw.png" /></figure><p>The final result is 100110(2), which is 38. And 29 + 9 is indeed 38!</p><h4>Setting bits of the result variable</h4><p>Calculating the carry over and the result by hand is very easy. But how to set the bits of the <em>result</em> variable at each iteration, in our code ?</p><p>One more time, bitwise operators will help us to solve this problem. The OR operator (|) is perfect to set bits to a specific value. In fact, no matter what bit value is already stored in <em>result</em>, the <strong>correct new value will be assigned</strong>.</p><p>In fact, 1 remains 1 in all cases, and 0 becomes 1 if the second operand is 1, otherwise it remains 0:</p><ul><li>0 | 0 = 0</li><li>1 | 0 = 1, 0 | 1 = 1, 1 | 1 = 1</li></ul><p>Finally, to be sure to set the correct bit among the 32 available in the result variable, we can use <strong>bit shifting</strong> with <strong>&lt;&lt; i</strong>. It will place the calculated value at the correct place according the iteration index.</p><p>Here’s the full function so that you can have an overview of the <strong>addition implementation</strong>:</p><pre>fn adder(a: u32, b: u32) -&gt; u32 {<br>    let mut result = 0;<br>    let mut carry_over = 0;<br><br>    for i in 0..32 {<br>        // Formula to get the i-th bit of the first number, from the right.<br>        let a_bit = a &gt;&gt; i &amp; 1;<br>        // Formula to get the i-th bit of the second number, from the right.<br>        let b_bit = b &gt;&gt; i &amp; 1;<br>        // Binary result that will be stored in the total number called result<br>        let binary_result = a_bit ^ b_bit ^ carry_over;<br><br>        carry_over = (a_bit &amp; b_bit) | (a_bit &amp; carry_over) | (b_bit &amp; carry_over);<br>        // If binary_pos is 0, it doesn&#39;t do anything. Otherwise, it set the correct bit to 1.<br>        result |= binary_result &lt;&lt; i;<br>    }<br>    result<br>}</pre><p>This is a clear and short solution to <strong>add integers without using Plus sign</strong>. It’s convenient to understand the concept of bitwise addition without any difficulty.</p><p>However, there are other ways to do it, and certainly <em>better implementations</em> for performance and memory efficiency. Don’t hesitate to do your own researches if it’s what you are looking for! 😃</p><p>Also, if you know other methods, you can leave a comment down below to help people improve their knowledge.</p><p><em>Did you like this article? You can let me know by different ways:</em></p><ul><li><em>Clap the article.</em></li><li><em>Comment your thoughts on my story.</em></li><li><em>Subscribe to my account.</em></li><li><em>Follow me on </em><a href="https://github.com/julien-ctx"><em>GitHub</em></a><em>.</em></li></ul><p><em>You can also </em><a href="https://medium.com/@julien-ctx/subscribe"><em>subscribe to my newsletter</em></a><em> to receive my latest posts in your mailbox.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d543b46c9aa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Push_Swap: An Easy and Efficient Sorting Algorithm]]></title>
            <link>https://medium.com/@julien-ctx/push-swap-an-easy-and-efficient-algorithm-to-sort-numbers-4b7049c2639a?source=rss-8dc29ec18b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b7049c2639a</guid>
            <category><![CDATA[programming-tutorials]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Julien C.]]></dc:creator>
            <pubDate>Sat, 20 May 2023 16:25:16 GMT</pubDate>
            <atom:updated>2023-11-07T19:31:33.404Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s discover how to implement a powerful sorting algorithm in C using 2 stacks, and a limited number of movements.</h4><figure><img alt="push swap tutorial" src="https://cdn-images-1.medium.com/max/960/1*seqvx_xvkEoxInWVEo3oqw.gif" /><figcaption>An overview of my algorithm’s performance for 100 integers.</figcaption></figure><p><strong>Push_swap</strong> is the first algorithmic project of <a href="https://42.fr/en/homepage/">42 School</a>. We are free to implement any algorithm to sort the numbers, but the best ones get a better grade.</p><p>I tried 3 different algorithms to solve push_swap’s problem: <strong>radix sort</strong>, <strong>quicksort</strong>, and finally the <strong>home-made algorithm</strong> that I will show you today.</p><p>This algorithm allowed me to get the <strong>highest grade</strong> on the project, and you will see that it is <em>very easy to understand</em>!</p><h3>Understanding push_swap</h3><p>Numbers are given as arguments of the C program, and we have to convert them using <em>atoi</em> function.</p><p>After that, we have to store those numbers, ideally in a <strong>linked list</strong> to avoid freeing and allocating arrays. Here is the structure I used to store my numbers:</p><pre>typedef struct node<br>{<br>  int   nb;<br>  struct node *next;<br>  struct node *prev;<br>} t_node;</pre><ul><li><em>nb</em> is an integer in our stack.</li><li><em>next</em> is the next structure element in our doubly linked list.</li><li><em>prev</em> is the previous structure element in our doubly linked list.</li></ul><p>To sort the numbers, we can use <strong>2 stacks</strong> (<em>stack A</em> and <em>stack B</em> as shown below). The linked list represents stack A, and we can create another linked list for stack B and assign it <em>NULL</em> because it is empty.</p><p>We also have several movements available, and that’s what makes the projet a bit harder! Those movements are counted and the final count determines our grade.</p><ul><li><strong>sa</strong>: swap the first two elements of stack A.</li><li><strong>sb</strong>: swap the first two elements of the stack B.</li><li><strong>ra</strong>: the first element of the stack A becomes the last one.</li><li><strong>rb</strong>: the first element of stack B becomes the last one.</li><li><strong>rr</strong>: rotate stack A and B (ra and rb).</li><li><strong>rra</strong>: the last element of stack A becomes the first one.</li><li><strong>rrb</strong>: the last element of stack B becomes the first one.</li><li><strong>rrr</strong>: reverse rotate A and B (rra and rrb).</li><li><strong>pa</strong>: push in stack A.</li><li><strong>pb</strong>: push in stack B.</li></ul><figure><img alt="push swap 42" src="https://cdn-images-1.medium.com/max/1024/1*q7PpPErimGAKpdUhBy-bbg.png" /><figcaption>Basic explanation push_swap’s moves.</figcaption></figure><p>Each movement has to be displayed in <strong>stdout</strong> and the sorted numbers have to be stored in stack A, at the end of the program. Stack B is just a temporary stack to help us sort <strong>smaller ranges of numbers</strong>.</p><h3>Sorting 3 numbers</h3><p>A little part of the code is dedicated to handling 3 numbers. You’ll see that it will be very useful for the <strong>algorithm used to sort 5 numbers</strong>.</p><p>You only have 3 numbers to sort, so <em>3! = 3 * 2 * 1 = 6</em> combination possibilities. It’s very easy to implement and you are capable of doing it alone, but don’t forget that you should never use <strong>more than 3 moves</strong> for it.</p><h3>Sorting 5 numbers</h3><p><strong>Sorting 5 numbers</strong> in ascending order can be a little more tricky and I advice you to handle it separately as well.</p><p>A common way to do it is to <strong>push the first 2 numbers in stack B</strong>, and then reuse the code you wrote before to sort the 3 remaining numbers in stack A. After that, all you need to do is pushing back the numbers from stack B to stack A.</p><figure><img alt="push swap 5 numbers" src="https://cdn-images-1.medium.com/max/1024/1*iPmQsvC2B4gpzlGRld2VZQ.png" /><figcaption>My technique to sort 5 numbers in ascending order.</figcaption></figure><p>Depending on how you do it, you can <strong>exceed 12 moves</strong>, which is the maximum allowed by <strong>42 School</strong> for 5 numbers.</p><p>Don’t worry, you can use <a href="https://github.com/julien-ctx/push-swap-tester">my tester</a> to be sure you won’t exceed 12 numbers. It checks for all combinations of 5 numbers (5! = 120 combinations), so that <strong>you won’t have any surprise</strong> during the evaluation.</p><h3>Algorithm for large stacks (100–500 numbers)</h3><p>To sort a large number of integers with my method, you need a <strong>third stack</strong>. Don’t worry, it’s not complicated and you’ll understand its purpose very soon!</p><p>This stack, called <em>stack C</em>, doesn’t display any message and the <em>checker</em> doesn’t know about it — it’s like an internal linked list that we will use for a specific purpose.</p><blockquote>Push_swap is not an introduction to time complexity. Instead, it’s an algorithm that has to bend to the subject’s requirements in the most efficient way: <strong>make the least possible movements</strong> between the stacks.</blockquote><p>Knowing this, our stack C will allow us to sort our numbers for the first time without displaying the movements. The idea is to <strong>get the final position of each number when they have been sorted</strong>.</p><p>To do so, you have to clone stack A numbers with the following function. Note that the type of stack C is <em>int * </em>and not <em>t_node *</em>, because we are just using the integers and not performing any movement.</p><pre>int *stack_dup(t_node *stack)<br>{<br>  int  i;<br>  t_node *node;<br>  int *array;<br>  <br>  i = 0;<br>  node = stack;<br>  array = malloc(sizeof(int) * stack_size(stack));<br>  if (!array)<br>    return (NULL);<br>  while (node-&gt;next != stack)<br>  {<br>    array[i++] = node-&gt;nb;<br>    node = node-&gt;next;<br>  }<br>  array[i] = node-&gt;nb;<br>  return (array);<br>}</pre><p>This function acknowledges that you use a <strong>circular doubly linked list</strong> like I did. Feel free to edit it according to your code structure.</p><p>Once you have your array of integers, you can implement a simple algorithm such as <strong>quicksort</strong> to sort the numbers. Here is my implementation:</p><pre>void    swap(int *a, int *b)<br>{<br>    int tmp;<br>    <br>    tmp = *a;<br>    *a = *b;<br>    *b = tmp;<br>}<br><br>int partition(int *array, int start, int end)<br>{<br>    int pivot;<br>    int i;<br>    int j;<br><br>    pivot = array[end];<br>    i = start - 1;<br>    j = start;<br>    while (j &lt;= end - 1) <br>    {<br>        if (array[j] &lt; pivot)<br>        {<br>            i++;<br>            swap(&amp;array[i], &amp;array[j]);<br>        }<br>        j++;<br>    }<br>    swap(&amp;array[i + 1], &amp;array[end]);<br>    return (i + 1);<br>}<br><br>void    quicksort(int *array, int start, int end)<br>{<br>    int pivot_index;<br><br>    if (start &lt; end)<br>    {<br>        pivot_index = partition(array, start, end);<br>        quicksort(array, start, pivot_index - 1);<br>        quicksort(array, pivot_index + 1, end);<br>    }<br>}</pre><p>Now, we know the <strong>exact position</strong> of each number in the final linked list, even before printing a single movement. Thanks to stack C (the integer array), we can now assign to each element in stack A an integer representing its position in the sorted array. Let’s call it <em>index</em>.</p><pre>typedef struct node<br>{<br> int   nb;<br> int   index; // Position in the sorted array.<br> struct node *next;<br> struct node *prev;<br>} t_node;</pre><p>At this point, we just have to write the <strong>core of the algorithm</strong>. But before that, let me explain you how it works!</p><p>Knowing that we already have the final position of each element in stack A, we can <strong>push all the numbers in stack B</strong> (with <em>pb</em>). We are therefore able to calculate, for each element in stack B, how many moves it will take to place it in the right place in stack A.</p><figure><img alt="push swap quicksort" src="https://cdn-images-1.medium.com/max/1024/1*sIw5OmpF8qtBQTYt9q5SYw.png" /></figure><p>As you can see in the picture, we will choose to handle <em>6</em> first, because it is the one that <strong>makes the least movements</strong> to be placed correctly in stack A<strong>. </strong>We can now execute the correct movements to move 6 in the good position.</p><p>We just have to perform the following steps in a loop, until all numbers are stored back into stack A:</p><ul><li>Calculate for each element in stack B how many moves it will take to move it at its sorted position in stack A.</li><li>Choose to push back in stack A the number that requires the least number of moves.</li><li>Repeat until stack B is empty.</li></ul><p>To remember the movements throughout your calculations, I advise you to add integers in your structure to use them to <strong>find the best node to push back in stack A</strong>, like this<strong>:</strong></p><pre>typedef struct node<br>{<br>   int   nb;<br>   int   index;<br>   struct node *next;<br>   struct node *prev;<br>   int   value;<br>   int   sa;<br>   int   sb;<br>   int   ra;<br>   int   rb;<br>   int   rra;<br>   int   rrb;<br>} t_node;</pre><p>At the end of the loop, it happens that the stack A is sorted but the minimum is <strong>not in the first position</strong>, as you can see on the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*96Mj3CD6RhaOFtN02hZ5PA.png" /></figure><p>To fix this problem, you have to find the <strong>index of the minimum value</strong> in stack A, and then perform the correct number of <strong>ra</strong> or <strong>rra</strong> (use ra <em>if index &lt; stack_a_size</em> or use rra <em>if index ≥ stack_a_size</em>) to respect a valid ascending order.</p><blockquote>You can find the full code of my push_swap algorithm on my GitHub account: <a href="https://github.com/julien-ctx/push-swap">https://github.com/julien-ctx/push-swap</a></blockquote><h3>Optimizing push_swap to have the maximum grade</h3><p>Here are a few more things you MUST do to enhance the performance of your algorithm and have <strong>100/100</strong>:</p><ul><li>When choosing the best number to push back in stack A, whenever you have ra and rb at the same time, or rra and rrb at the same time, don’t forget to use <strong>rr</strong> or <strong>rrr</strong>. They will help you to have the maximum grade at <strong>push_swap’s project</strong>.</li><li>Instead of pushing everything into stack B at the beginning of the program, you can find the <strong>longest sequence of numbers that are already sorted</strong> in the order in which they will be sorted at the end. You should only keep the sorted sequence if it has the same order in stack C, not the numbers which are only arranged in ascending order!</li></ul><h3>Testing your sorting algorithm</h3><p>Like all algorithmic projects, knowing if your program works can be a daunting task. So you can use a <a href="https://github.com/julien-ctx/push-swap-tester">push_swap tester</a> to make sure your program works.</p><p>This tester was made by myself and allows you to check <strong>both your parsing and your algorithm</strong> on several sequences of numbers (3, 4, 5, 100, 500 numbers). The integers are randomly generated to avoid any bias in the tests.</p><p>You can use a simple <strong>Bash command</strong> to launch the tester:</p><ul><li>For Mac:</li></ul><pre>git clone git@github.com:julien-ctx/push-swap-tester.git &amp;&amp; mv push-swap-tester/tester.py . &amp;&amp; mv push-swap-tester/checker_Mac . &amp;&amp; rm -rf push-swap-tester &amp;&amp; chmod 777 checker_Mac &amp;&amp; make &amp;&amp; python3 tester.py</pre><ul><li>For Linux:</li></ul><pre>git clone git@github.com:julien-ctx/push-swap-tester.git &amp;&amp; mv push-swap-tester/tester.py . &amp;&amp; mv push-swap-tester/checker_linux . &amp;&amp; rm -rf push-swap-tester &amp;&amp; chmod 777 checker_linux &amp;&amp; sed -i -- &#39;s/checker_Mac/checker_linux/g&#39; tester.py &amp;&amp; make &amp;&amp; python3 tester.py</pre><p><em>Did you like this article? You can let me know by different ways:</em></p><ul><li><em>Clap the article.</em></li><li><em>Comment your thoughts on my story.</em></li><li><em>Subscribe to my account.</em></li><li><em>Follow me on </em><a href="https://github.com/julien-ctx"><em>GitHub</em></a><em>.</em></li></ul><p><em>You can also </em><a href="https://medium.com/@julien-ctx/subscribe"><em>subscribe to my newsletter</em></a><em> to receive my latest posts in your mailbox.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b7049c2639a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>