{"pageProps":{"posts":[{"content":"\n## Introduction\n\nWhenever I work with Firebase, I always seem to run into small issues that can be very annoying (yet simple) to solve. When I tried to connect my Flutter application to a Firebase backend for one of my personal projects, I ran into some small issues that set me back some time. Because of this, I decided to write a simple and straightforward article showing you how to connect your Flutter application to a firebase backend for both IOS and Android. After this tutorial, you will be all set to add authentication, cloud Firestore, or any other Firebase feature you might want.\n\n## Pre Reqs\n\nTo keep this tutorial short, I expect that you have the following:\n\n1. You have Flutter installed on your machine\n2. You have a Flutter project started already and are ready to connect it with Firebase\n\nIf you don’t have those 2 things yet, you can read my last article where I go over how to do just that.\n\n## Creating a Firebase Project\n\nBefore we start working in Flutter, we need to create a Firebase project.\n\n1. Navigate to [Firebase console](https://console.firebase.google.com/)\n\n2. Click on **Add Project**\n\n3. Enter a project name\n\n4. Choose if you want Google Analytics to be enabled (I recommend this). You can always enable this later on.\n\n5. Choose what account you want this project to be associated with\n\n6. Click **create project**\n\nAfter a minute or two, your project will finish creating and you will be brought to the overview page.\n\n## Add Firebase to Android\n\nNext, we will add Firebase to our Android version. We will need to do IOS and Android separately although the process is similar.\n\n![Firebase Console](/images/connect-flutter-to-firebase/console.png)\n\n1. Click on the Android Icon from the overview page\n\n2. Complete the Register App step.\n\nFor Android package name use the format: com.[your name or business name].[project name]. For app nickname, use whatever name you’d like.\n\n![Firebase Console](/images/connect-flutter-to-firebase/add.png)\n\nStep 2\n\n3. Download the config file and place it in the app level (in the app folder).\n\n![Firebase Console](/images/connect-flutter-to-firebase/app-level.png)\n\n4. In the project level build.gradle, add the following:\n\n![Firebase Console](/images/connect-flutter-to-firebase/build.gradle.png)\n\n5. In the app level build.gradle add the following:\n\n![Firebase Console](/images/connect-flutter-to-firebase/app-level-build.gradle.png)\n\n6. Lastly, in the app level build.gradle file (same file as above), find the applicationId and change it to the name you chose in step 2. In my case I used com.benjamincarlson.medium_tutorial.\n\n![Firebase Console](/images/connect-flutter-to-firebase/name.png)\n\nAt this point we are done. Run the app with an android emulator and make sure everything works. You should see the following image below if everything works as expected.\n\n![Firebase Console](/images/connect-flutter-to-firebase/working-android.png)\n\n## Add Firebase to IOS\n\nLike I said earlier, this is similar to what we did for Android.\n\nClick on the IOS Icon from the overview page\n\nEnter the IOS bundle ID. This can be found by opening your project in Xcode -> click on runner (top right) -> general tab -> Identity\n\n![Firebase Console](/images/connect-flutter-to-firebase/bundle-id.png)\n\nI changed mine from com.example.mediumTutorial to com.benjamincarlson.mediumTutorial.\n\n3. Enter an app nickname and app store ID (both optional)\n\n4. Download the config file. Add the file in the project root by opening Xcode, right clicking on runner, and clicking “add files to runner”. You need to add the file directly through Xcode otherwise you will get an error and the app won’t run.\n\n5. Skip the next 2 steps firebase tells you to do\n\n6. Run the IOS app and make sure everything is working correctly\n\n## Finishing Up\n\nThe last thing you want to do is open up pubspec.yaml and add the following under dependencies:\n\n```dart:pubspec.yaml\nfirebase_auth: ^0.14.0+5\ncloud_firestore: ^0.12.9+4\n```\n\nAny other firebase tools you want to use will be added here as well.\n\nThat’s it guys! I hope you found this article useful and that you are able to successfully connect your Flutter app to firebase!","data":{"title":"Add A Firebase Backend To Your Flutter App Fast!","publishedAt":"2020-06-27","summary":"Learn how to integrate Google's Firebase into your Flutter App."},"filePath":"connect-flutter-to-firebase.mdx"},{"content":"\n## Introduction\n\nA few weeks ago I wrote an article detailing how you can quickly create a cross platform mobile app with React Native and run it on your device. Since that article got a lot of traction, I have decided to write a similar article with Flutter!\n\n> Rather watch a video than read? Watch this article in video format on YouTube: https://youtu.be/0eAqiyIr-_Y\n\n## What Is Flutter?\n\nFlutter, built by Google, is a UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop. Flutter apps are built using the dart programming language.\n\nThe first step is to download the Flutter SDK from flutter’s website. Be sure to download the right one for your machine.\n\nNext we need to unzip this folder and move it to somewhere more permanent. Find the zipped file in your downloads folder and double click it to unzip it.\n\nNext, create a folder named Developer right under your main user. Inside that folder place the unzipped flutter folder. Here is my folder structure:\n\n```bash\n/Users/bjcarlson/Developer/flutter\n```\n\nInstead of bjcarlson you should see your username. This is for a mac but windows should be similar.\n\nThe final step is to tell our machine where to find these files whenever we want to use them! For this, open up a terminal window and write:\n\n```bash\nvim .bash_profile\n```\n\nInside here we will write:\n\n```bash\nexport PATH=\"$PATH:/Users/bjcarlson/Developer/flutter/bin\"\n```\n\nOf course, replace my username for yours. To exit and save write:\n\n```bash\n:wq!\n```\n\nAfter this quit and restart terminal.\n\nTo make sure everything works, open up terminal again and write:\n\n```bash\nflutter --version\n```\n\nIf you get the following output, you have done it correctly.\n\n![Python](/images/create-a-flutter-app-fast/1.png)\n\nNow we can create an app.\n\nNavigate to where you want to place this app and run ```flutter create my_awesome_app```\n\nMove into the folder and run the run command.\n\n```bash\ncd my_awesome_app\nflutter run\n```\n\nThat’s it! Your app will now start on an actual device if you have one connected, or a simulator if you set that up. For info on that see flutters docs.\n\nHappy coding!","data":{"title":"Create a Cross Platform Mobile App With Flutter in Under 5 Minutes!","publishedAt":"2020-04-29","summary":"Learn how to create a cross platform android and IOS mobile app using dart and Flutter."},"filePath":"create-a-cross-platform-app-with-flutter.mdx"},{"content":"\n## Introduction\n\nRecently I make two YouTube videos detailing how to use Python and Selenium to code an Instagram Bot. Today, I am taking those videos and putting them into article format so you can follow along and copy/paste code! Just like the videos, I will be splitting these articles into 2 parts. You can watch the first video here:\n\n> Remember, this is for educational purposes only. I do not recommend using this outside testing and exploring purposes because Instagram does not allow bots!\n\n## Prerequisites\n\nThe following are items you need installed before you begin.\n\n### Python\n\n- Navigate to https://www.python.org/downloads/ and download the latest version.\n\n### Virtualenv\n\n- Run the following command:\n\n```bash\npip install virtualenv\n```\n\n(Note: you need pip installed to run the command)\n\n### Selenium\n\n- Navigate to https://www.selenium.dev/downloads/ and download the latest version\n\n### WebDriver for Chrome\n\n- Navigate to https://chromedriver.chromium.org/downloads and under Current Releases download the version for your Chrome Browser (81, 80, or 79)\n\n- Unzip the file\n\n- Run the following command:\n\n```bash\nmv ~Downloads/chromedriver /usr/local/bin\n```\n\n(Note: There is a space after …chromedriver and /usr…)\n\nAfter you have those three things, we are ready to start!\n\n## Setting Up The Environment\n\nWe will be using a Python virtual environment to keep this project and its dependancies separate from other projects on your machine.\n\nMake a new folder where you want to store this project, move into that folder, and then create a new virtual environment.\n\n```bash\nmkdir \ncd \nvirtualenv -p python3 \n```\n\nNext, activate the virtual environment.\n\n```bash\nsource /bin/activate\n```\n\nNext, let’s install Selenium. Selenium is our one dependency for this project and it allows us to automate web browsers.\n\n```bash\npip install selenium\n```\n\nFinally, open those files in a code editor of your choice.\n\n## Time To Code!\n\nI mentioned that we are going to be making an Instagram bot. More specifically, we will be writing code to automate logging in to Instagram, searching a hashtag from the explore page, and liking and commenting on each picture.\n\nCreate a file named bot.py at the same level as your vitualenv.\n\nInside this file, write the following code:\n\n```python\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver.common.keys import Keys\nfrom random import randint\n```\n\nWe will use each of these imports and discuss what they each do when we use them.\n\nNext, let’s declare some standard Python boilerplate code:\n\n```python\nclass Bot(): \n def __init__(self):\n self.login('benscstutorials')\n \n def login(self, username):\n print('hi')\ndef main():\n my_bot = Bot()\nif __name__ == '__main__':\n main()\n```\n\nThe above code will print ```hi``` if you run it.\n\nNext, lets declare an instance of our webdriver. The following code will all be written in the login def.\n\n```python\nself.driver = webdriver.Chrome()\n```\n\nWe can now user driver to call various methods that webdriver gives us access to. First, we need to open instagram. We can do that with the get method.\n\n```python\nself.driver.get('https://www.instagram.com/')\n```\n\nIf we run this with python -i bot.py, you will see an automated webbrowser window open up and navigate to Instagram.\n\nPretty cool, right!\n\nNext, we need to wait for Instagram to open. This is where sleep comes in. We can use sleep to make our code go idle for a specified number of seconds.\n\n```python\nsleep(5)\n```\n\nNow, we need to insert our username and password into the form and hit login. To do this we can get each element by xpath, and use the send_keys() method to send text!\n\nTo get the element xpath, right click on the element and click inspect. This will bring you to the source code. Next, right click on the source code for that element. Towards the bottom you will see copy, copy xpath.\n\n![Python](/images/python-automation-with-selenium/2.png)\n\nDo this for both username and password. Then, in your editor write the following code in the login method:\n\n```python\nusername_input = self.driver.find_element_by_xpath(\"//input[@name='username']\")\nusername_input.send_keys(username)\npassword_input = self.driver.find_element_by_xpath(\"//input[@name='password']\")\npassword_input.send_keys(pw)\n```\n\nYou will notice that i am sending the variable pw instead of my actual password. This is for security reasons. Make a new file called ```secrets.py``` and inside it, declare your password as such:\n\n```python:secrets.py\npw = 'XXXXXX'\n```\n\nThen, at the top of bot.py write\n\n```python:bot.py\nfrom secrets import pw\n```\n\nThe next step is to click login.\n\nTo do this, copy the xpath of the submit button and use the click() method.\n\n```python\nsubmit_btn = self.driver.find_element_by_xpath(“//button[@type=’submit’]”)\nsubmit_btn.click()\n```\n\nThis should log us in!\n\n\nYou will notice that a popup appears when you log in asking you if you want to turn on notifications.\n\n![Python](/images/python-automation-with-selenium/3.png)\n\nWe want to hit not now. Again copy the xpath and use the click() method.\n\n```python\nsleep(5)\nnot_now_btn = self.driver.find_element_by_xpath(‘/html/body/div[4]/div/div/div[3]/button[2]’)\nnot_now_btn.click()\n```\n\nBe sure to add ```sleep(5)```. If you don’t instagram will not be loaded fully and your code will fail!\n\nYour final code should look like such:\n\n```javascript\nfrom selenium import webdriver\nfrom time import sleep\nfrom secrets import pw\nfrom selenium.webdriver.common.keys import Keys\nfrom random import randint\nclass Bot():\n def __init__(self):\n self.login('benscstutorials')\n \n def login(self, username):\n self.driver = webdriver.Chrome() \n self.driver.get('https://www.instagram.com/')\n sleep(5)\n username_input = self.driver.find_element_by_xpath(\n \"//input[@name='username']\")\n username_input.send_keys(username)\n password_input = self.driver.find_element_by_xpath(\n \"//input[@name='password']\")\n password_input.send_keys(pw)\n submit_btn = self.driver.find_element_by_xpath(\n \"//button[@type='submit']\")\n submit_btn.click()\n sleep(5)\n not_now_btn = self.driver.find_element_by_xpath(\n '/html/body/div[4]/div/div/div[3]/button[2]')\n not_now_btn.click()\ndef main():\n my_bot = Bot()\nif __name__ == '__main__':\n main()\n```\n\n## Conclusion\n\nThat’s it! In the next post I will continue this and discuss how to like and comment on posts by hashtag.\n\n> Update: there is no next post but feel free to watch the video tutorial on YouTube!","data":{"title":"Python Automation With Selenium","publishedAt":"2020-04-29","summary":"Create a Python bot to automate following, commenting, and liking on Instagram!","image":"/images/python-automation-with-selenium/1.jpeg"},"filePath":"python-automation-with-selenium.mdx"},{"content":"\n## Introduction\n\nReact Native is a JavaScript framework for building cross platform mobile apps. In this tutorial, I’ll show you how to quickly set up a React Native project and run your app on your actual device! The code for this tutorial can be found on my GitHub.\n\n## Expo\n\nIn this tutorial, we will be using expo with React Native. Expo acts as a container around the React Native framework that allows us to develop applications more quickly and easily compared to if we were using bare bones React Native. The first thing we need to do is install the Expo CLI command line utility. Open your terminal and run the following command:\n\n```shell\nnpm install -g expo-cli\n```\n\nNow we can create a new React Native project. I will call my project ExampleProject but you can call it whatever you like.\n\n```shell\nexpo init ExampleProject\n```\n\nExpo will prompt you with the following message:\n\n![react native](/images/react-native-starter/2.png)\n\nFor this tutorial, I will select blank but I encourage you to do some research and select the best option for your project.\n\n## Running Our App\n\nBelieve it or not, our app is ready to be run! To start our app we must move into the folder which contains our app and then run the start command.\n\n```shell\ncd AwesomeProject\nnpm start\n```\n\nWhen you run ‘npm start’, a new browser window will open at your local host. You will notice a barcode in the lower left hand corner.\n\n![react native](/images/react-native-starter/3.png)\n\nWe can scan this barcode in the expo app to run our app on a device. Go to either the Apple App Store or the Google Play Store and search for ‘expo client’. See the image below.\n\n![react native](/images/react-native-starter/4.png)\n\nOnce you download and open the app, you will see an option to “Scan QR Code”. Tap this and scan your code. After the JavaScript loads, you should be able to see the app on your device. If you see “Open up App.js to start working on your app!” you have done it correctly.\n\n## Conclusion\n\nNow go out and start building the app of your dreams! If you want the exact code I used in this tutorial, it can be found on my GitHub and this post and more can be found on my website. Happy coding!","data":{"title":"Create an IOS and Android app in Under 5 Minutes With React Native!","publishedAt":"2020-04-01","summary":"Learn how to create a cross platform android and IOS app with React Native!","image":"/images/react-native-starter/1.png"},"filePath":"react-native-starter.mdx"},{"content":"\n## Introduction\n\nAs a computer science student, I am always looking for another cool side project to keep me busy. These ideas for side projects can come from anywhere; sometimes from the places you least expect.\n\nThe other day I was scrolling through TikTok when I can across this video. Basically, it’s about how there are people in this world born on the same day and were in the same hospital are you were. Neat, right? I then looked at the comments and multiple users were saying there should be a website for this. Immediately I knew what I had to do. In this post, I will talk about how I was able to build and deploy this site in only a few hours completely for free by using various popular coding technologies.\n\n### The Idea\n\nBefore I talk about the technology, I want to quickly discuss what I am trying to build. Essentially, it is a website where users can create an account and input their information like their name, birthday, hospital name, and snapchat username (for a way to contact). After they do this, they can see a table of every other user who has inputted their information. They can then (hopefully) find others with the same birthday and hospital!\n\nOver time I plan to add new features (because right now this is essentially an Excel spreadsheet clone), but for the moment that is the idea.\n\n### The Technology\n\nNow for the interesting part. Let’s look at the technology I used to build this.\n\n### Next.js\n\nRight off the bat I knew I was going to build this in Next.js. I had just finished uploading a tutorial series on YouTube about it and I built my personal website using it so I was confident I could quickly and easily get this site up and running with Next.js.\n\nNext.js gives you the best developer experience with all the features you need for production: hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching, and more. No config needed.\n\n### Firebase\n\nMy next challenge was deciding how and where to store the data. For this, I turned to Google’s Firebase. I had worked with Firebase before in various forms, including with Flutter and Vanilla JavaScript, but not yet with Next.js. No problem though, because Next.js has amazing documentation and example projects. I was able to clone this firebase auth repo and get on my way. As seen by the repo name, Firebase also helped in another way; providing a means of authentication.\n\n> Firebase helps mobile and web app teams succeed\n\n### Bootstrap + react-bootstrap-table-next + HTML/CSS\n\nTo quickly build a UI for this site, I turned to Bootstrap, specifically react bootstrap. Using it, I was able to code the Nav bar and the Modals quickly. Then, I used npm package “react-bootstrap-table-next” to build the table for the data. This allowed be to dynamically generate the data and add a search bar easily (see code below). Both of these technologies accounted for 99% of my UI.\n\nI also used HTML and CSS for some basic markup because, let’s face it, you can’t build a website without them.","data":{"title":"How TikTok Gave Me the Perfect Coding Side Project","publishedAt":"2020-09-01","summary":"I got an idea for a weekend coding project from Tik Tok. In this post I'll go over my tech stack.","image":"/images/tik-tok/emile-perron-xrVDYZRGdw4-unsplash.jpg"},"filePath":"tik-tok-coding-idea.mdx"},{"content":"\n## Introduction\n\nThe Rubiks cube is a popular puzzle in which the goal is to solve a 3x3 cube by matching the colors on each side. In order to solve the cube, you first need to scramble it. There are rules for how to do this but in general a scramble consists of 20 random moves performed in sequence. In this post, I will show you how to implement a scramble in JavaScript. The code for this tutorial can be found on my GitHub.\n\n## What's A Scramble?\n\nA scramble is a sequence of 20 moves that are performed on a solved cube. These 20 moves are picked randomly from the following set of moves:\n\n![Scramble moves](/images/using-javascript-to-scramble-cube-1/2.png)\n\nEach of the above letters are rotations of the cube. They stand for:\n\n- F — Front\n- R — Right\n- U — Upper\n- B — Back\n- D — Bottom (Down)\n\nA single letter means you rotate that face of the cube clockwise. If there is a ' (single quote) after the letter, you move that face counterclockwise. Likewise, if there is a 2 after the letter, you move that face on the cube twice.\n\nFor example, F2 means you turn the front of the cube clockwise 2 times. B’ means you rotate the back of the cube counterclockwise one time.\n\nHere is a great visual I found on ruwix.com to help you understand this better.\n\n![Scramble moves](/images/using-javascript-to-scramble-cube-1/1.png)\n\n## Example Scrambles\n\nHere are some example scrambles of the cube. This is what we will be writing JavaScript to do for us.\n\n![Scramble moves](/images/using-javascript-to-scramble-cube-1/3.png) \n\n## JavaScript Scrambler\n\nNow let’s start writing JavaScript code to scramble the cube for us.\n\nFirst, I will declare a function named makeScramble().\n\n```javascript:main.js\nfunction makeScramble() {\n // function code here\n}\n```\n\nNext, we need to declare 2 arrays. The first array will have all of the options I listed above in it. This array will be where we pick the moves from. The second array will be empty. This is where the scramble will go.\n\n```javascript\nvar options = [\"F\", \"R\", \"U\", \"B\", \"L\", \"D\", \"F2\", \"R2\", \"U2\", \"B2\", \"L2\", \"D2\", \"F'\", \"R'\", \"U'\", \"B'\", \"L'\", \"D'\"]\nvar scramble = []\n```\n\nLet’s step back and think about how we want to approach this next part. We need to randomly select one element in the first array and put it into the second array. We then need to repeat this 19 more times so we have a scramble with 20 elements.\n\nLet’s tackle the first part. To randomly select an element in the firrst array, we need can generate a random number from 1 to 18 and then put whatever move at that index into the new scramble. Luckily for us, there is a JavaScript Math library that can help us do this.\n\n```javascript\nfunction getRandomInt(max) {\n return Math.floor(Math.random() * Math.floor(max));\n}\n```\n\nThe above code is doing a few things. First, it is declaring a function called getRandomInt. This functions accepts a value max. In our case this value will be 18 because we want to generate a random number from 1 to 18. The inner line of the function is returning that random number for us.\n\n## Push And Pop\n\nNow that we have a way to randomly get an element in the first array, we need to put it into the second array. JavaScript, like other languages, has built in methods for doing common tasks. One of these methods is called push. This method works on arrays and allows us to push one item onto the array. In our case, we will be pushing one string move onto the array.\n\n```javascript\nscramble.push(options[getRandomInt(18)])\n```\n\nThe above code gets a random int from 1 to 18 using the getRandomInt method, gets the corresponding cube rotation at that index in array options, and pushes it onto the new array, scramble.\n\nIf you run this code, only one move will be in the new array. To push 20 moves into the array, we can use a for loop.\n\n```javascript\nfor (var i = 0; i < 20; i++) {\n scramble.push(options[getRandomInt(18)])\n}\n```\n\nIf you run this code, you will see that the array named scramble now has 20 random moves in it.\n\npop is similar to push except instead of adding an element to the array, it removes the last element. We do not use that here, but I brought it up because it is the opposite of push and is very useful.\n\n## Conclusion\n\nI hope you enjoyed and learned something from this post! To recap, we went over a Basic Rubik’s cube notation and terminology, talked about two JavaScript concepts: functions and arrays, and finally looked at array’s built in methods, push and pop, and implemented push with a for loop.","data":{"title":"Using JavaScript To Scramble A Rubik’s Cube","publishedAt":"2020-03-29","summary":"I am making a web app that required me to make a rubiks cube scramble. I will show you how to implement this algorithm in JavaScript.","image":"/images/using-javascript-to-scramble-cube-1/cube.jpeg"},"filePath":"using-javascript-to-scramble-a-rubiks-cube-1.mdx"},{"content":"\n## Introduction\n\nThis is a follow up post to the post I wrote just the other day on scrambling a Rubik’s Cube with JavaScript. If you haven’t read that post yet be sure to check it out here and then come back to this post. In this post, I will improve the JavaScript scrambler. To do that, we will unfortunately have to rewrite most of the code, but the fundamental design stays the same. Let’s get to it!\n\n## What’s a Scramble\n\nYou should already know what a Rubik’s cube scramble is (assuming you read the first post), however, here is a quick refresher just in case. A scramble is a sequence of 20 moves that are performed on a solved cube. These 20 moves are picked randomly from the following set of moves:\n\nF, R, U, B, L, D, F2, R2, U2, B2, L2, D2, F', R', U', B', L', D'\n\nHere are some example scrambles:\n\nB2 R F' L2 R B L2 F' D' L2 F L2 R' U B D' F D' U2 R' \n\nB' D U2 F' L U' R2 L' D B D' R2 B' F' R2 B2 D2 R B D2 \n\nL' R2 U2 F U' B' D2 B D B' F2 U R2 F2 U' L2 B2 R2 L U'\n\n## The Problem\n\nThe problem with the last post was that our scrambling algorithm doesn’t account for the possibility of 2 of the same move being next to each other. For example, we might get a scrambles that look like these:\n\nB2 R F' L2 R B L2 F' L' L2 F L2 R' U B D' F D' U2 R' \n\nB' D U2 F' L U' R2 R2 D B D' R2 B' F' R2 B2 D2 R B D2 \n\nL' R2 U2 F U' B' D2 B D B' F2 U R2 D D L2 B2 R2 L U'\n\nAt first these scrambles might not look like an issue, however if you look closer, you will see that the first scramble has a L’ and a L2 directly next to each other. The last scramble has two D moves next to each other. This makes no sense. Take the last scramble for example. It’s the one with two D moves next to each other. That is the same as saying D2. Essentially, that scramble is now 19 moves, not 20. This is a problem, especially when we get 3 or 4 moves like this in our scrambles\n\nAdditionally, having a R followed by an R’ makes no sense because they just cancel each other out! All we did was move the cube twice to get to the same spot. When this happens multiple times in a scramble, our scrambles could be 15 or less moves instead of 20!\n\n## The Fix\n\nThis may seem like a simple fix but it is not quite that easy. It is hard to check if 2 adjacent moves are the same type. We need to think about solving this in a different way than we did last time. Let’s take a look at the options for each scramble again.\n\nF, R, U, B, L, D, F2, R2, U2, B2, L2, D2, F', R', U', B', L', D'\n\nWe can see that there are 6 different moves by letter. There is F, R, U, B, L, and D. Furthermore, there are 3 different moves for each of these. A single clockwise move (F), a double move (F2), and single counter clockwise move (F’). These make up our 18 possible moves (6 x 3 = 18).\n\nWe can use numbers to represent the scramble. We will assign F to 0, B to 1, and so on. Then at the end, we can substitute the letters back in and can be sure that no of the same letters will be next to each other.\n\n## Coding the Solution in JavaScript\n\nWe can now approach this problem using this knowledge. Let’s start off by giving each of the 6 possibilities a number 0 through 6 and store them in an array. We will call this array numOptions.\n\n```javascript\nvar numOptions = [0,1,2,3,4,5]\n```\n\nNow, we can randomly add these numbers to another array named scramble until we have 20 random letters in the array. Remember, a Rubik’s cube scramble is 20 moves.\n\n```javascript\nvar scramble = [] // initialize to empty\n\n\n for (var i = 0; i < 20; i++ ) {\n scramble.push(numOptions[getRandomInt(6)])\n }\n\n // random int code from last tutorial\n function getRandomInt(max) {\n // returns up to max - 1\n return Math.floor(Math.random() * Math.floor(max))\n }\n```\n\nNow, we have an array of 20 random numbers from 0 to 5! Now, some of you are thinking, we still have the same problem as last time. If that’s you, you’re absolutely right. We still have the possibility for a two 3’s to be next to each other or two 1’s. However, since we are using numbers (as opposed to letters), it is super easy to loop through the array and check this. We can now write code to generate an array of 20 numbers, loop though and check to see if any of the same number are next to each other, and if they are, generate the array again.\n\n```javascript\nvar bad = true\n\n while (bad) {\n scramble = []\n for (var i = 0; i < length; i++) {\n scramble.push(numOptions[getRandomInt(6)])\n }\n // check if moves directly next to each other are the same letter\n for (var i = 0; i < length - 1; i++) {\n if (scramble[i] == scramble[i + 1]) {\n bad = true\n break\n } else {\n bad = false\n }\n }\n }\n```\n\nTo briefly explain the code above: we declare a boolean bad and set it to true. The next block of code we already saw. Then, we check the scramble by looping through the array. It compares the value at index 0 to the value at index 1. If they are not equal it moves on and checks the rest of the array in the same fashion. If at any point two numbers are equal, it breaks, regenerates the scramble, and checks again.\n\n## Adding the Letters\n\nThe final step is to substitute letters for the numbers. We will do this by declaring an array of all possible options and then writing a switch statement nested inside a for loop to substitute the right letters for each number.\n\nEx. If the number is 3, we will place either a B, B2, or B’ (randomly of course).\n\n```javascript\nvar options = [\"F\", \"F2\", \"F'\", \"R\", \"R2\", \"R'\", \"U\", \"U2\", \"U'\", \"B\", \"B2\", \"B'\", \"L\", \"L2\", \"L'\", \"D\", \"D2\", \"D'\"]\nvar move\n\nfor (var i = 0; i < 20; i++) {\n switch (scramble[i]) {\n case 0:\n move = options[getRandomInt(3)] // 0,1,2\n scrambleMoves.push(move)\n break\n case 1:\n move = options[getRandomIntBetween(3, 6)] // 3,4,5\n scrambleMoves.push(move)\n break\n case 2:\n move = options[getRandomIntBetween(6, 9)] // 6,7,8\n scrambleMoves.push(move)\n break\n case 3:\n move = options[getRandomIntBetween(9, 12)] // 9,10,11\n scrambleMoves.push(move)\n break\n case 4:\n move = options[getRandomIntBetween(12, 15)] // 12,13,14\n scrambleMoves.push(move)\n break\n case 5:\n move = options[getRandomIntBetween(15, 18)] // 15,16,17\n scrambleMoves.push(move)\n break\n }\n }\n \nfunction getRandomIntBetween(min, max) { // return a number from min to max - 1. Ex. 3, 9 returns 3 - 8\n return Math.floor(Math.random() * (max - min) + min)\n}\n```\n\nYou will notice we have another function that gets a random number between 2 numbers called getRandomIntBetween. I added this because we need to be able to get a random number between 2 numbers and our current randNum function only allowed us to get a random number from 0 to a specified number.\n\n## Conclusion\n\nAfter seeing how I solved this problem, can you solve it better? I would love to see if there is a better solution! If you give it a try, let me know in the comments. You can get the code for this tutorial on my GitHub.","data":{"title":"Using JavaScript To Scramble A Rubik’s Cube: An Improved Algorithm","publishedAt":"2020-04-04","summary":"I am making a web app that required me to make a rubiks cube scramble. I will show you how to implement this algorithm in JavaScript.","image":"/images/using-javascript-to-scramble-cube-2/1.jpeg"},"filePath":"using-javascript-to-scramble-a-rubiks-cube-2.mdx"},{"content":"\n## Introduction\n\nReact hooks allow you to perform side effects in function components. In this post, we will take a look at ```useEffect``` and give examples\nof how to use in in [next.js](https://nextjs.org/).\n\n## Using useEffect In Next.JS\n\nLet's take a look at an example. We will use ```useEffect``` to add an event listener\nto handle when a user scrolls. We will then log to the console the scrollY value. This is how this website dynamically adds\nthe css to the nav bar on scroll!\n\nFirst, we will import ```useEffect``` from react.\n\n```javascript\nimport React, { useState, useEffect } from 'react'\n```\n\nNext, call the method:\n\n```javascript\nuseEffect(() => {\n \n })\n```\n\nWe can add anything we want in here. Let's add our event listeners:\n\n```javascript\nuseEffect(() => {\n window.addEventListener('scroll', handleScroll);\n return () => {\n window.removeEventListener('scroll', handleScroll)\n }\n })\n```\n\nFinally, create the handle scroll method and log the scrollY value to the console:\n\n```javascript\nconst handleScroll = () => {\n console.log(scrollY)\n }\n```\n\nAnd that's it! Check out my [YouTube channel](https://youtube.com/benjamincarlson) for more coding tutorials!","data":{"title":"UseEffect In Next.JS - React Hooks","publishedAt":"2021-03-14","summary":"Learn what useEffect is learn how to use useEffect in Next.JS."},"filePath":"using-react-useeffect.mdx"}]},"__N_SSG":true}