beginner – Printing a number from memory in assembly

I’m trying to work up to being able to print the hailstone sequence in assembly. To do that though, I first needed to learn how to actually print a number out using the write system call.

After a few design iterations, I ended up using division to get each digit one at a time by using the remainder. Each remainder gets pushed onto the stack, then the address of the stack is given to the system call to print out.

What I’d like advice on:

  • In a couple places, I have math split out over multiple lines, like:

     sub edx, esp  ; Calculate how many were pushed
     dec edx
    

    It doesn’t seem like it’s possible to combine that into something like sub edx, esp - 0, but if there is a neater way, I’d like to know.

  • This is my first time using div. Is there anything wrong with how I’m using it? Also, is there a sane way of not using div altogether? Apparently it’s stupid slow and should be avoided if possible.

  • Anything else notable. I’m a super-beginner, and this code is quite verbose.

I’m using n to represent the number that I want to print out. In theory though, that number could come from anywhere. It’s just a placeholder for the exercise.

global _start

section .data
    n: dd 123456

section .text
    _start:
        mov ebp, esp  ; So we can tell how many were pushed

        mov ecx, [n]

        .loop:
            mov edx, 0  ; Zeroing out edx for div
            mov eax, ecx  ; Num to be divided
            mov ebx, 10  ; Divide by 10
            div ebx
            mov ecx, eax  ; Quotient

            add edx, '0'
            push edx  ; Remainder

            cmp ecx, 0
            jne .loop

        mov eax, 4  ; Write system call
        mov ebx, 1  ; STDOUT
        mov ecx, esp  ; The string on the stack
        mov edx, ebp
        sub edx, esp  ; Calculate how many were pushed
        dec edx
        int 0x80

        mov eax, 1
        mov ebx, 0
        int 0x80

Assembled and linked using:

nasm numprint2.asm -g -f elf32 -Wall -o numprint2.o
ld numprint2.o -m elf_i386 -o numprint2

beginner – Simple program to print from a buffer until a newline is found

For practice, I wrote a small program that goes through a string in the data section (although, it could be easily adapted to take user input), and print out the characters in the string until it finds a newline, then stops.

This is by far the most complicated assembly program I’ve ever written. It’s the first time I’ve ever used a jump and cmp. It’s simple, but there’s likely improvements I can make, so I thought I’d try to get feedback.

I decided to write it in 32-bit because the system calls are a little easier to wrap my head around. I’ll transition to x86-64 once I know what exactly my school is going to be using; because I’ve seen both so far in slides.

firstjmp.asm

global _start

section .data
    input: db `1234567890n`

section .text
    _start:
        mov esi, input  ; Current head of string

        .loop:
            mov eax, 4
            mov ebx, 1
            mov ecx, esi
            mov edx, 1
            int 0x80

            inc esi
            
            cmp BYTE (esi), 10
            jne .loop  ; Stop looping once we've found the newline

        mov eax, 1
        mov ebx, 0
        int 0x80

nasm firstjmp.asm -g -f elf32 -Wall -o firstjmp.o
ld firstjmp.o -m elf_i386 -o firstjmp

┌─(brendon@parrot)─(~/Desktop/Classes/CompArc/Lab4/asm)
└──╼ $./firstjmp 
1234567890┌─(brendon@parrot)─(~/Desktop/Classes/CompArc/Lab4/asm)

beginner – Is this the best code I can write to find the type of input?

I am making a fractions calculator that can calculate fractions, whole numbers and mixed fractions.

So there is a String fraction, which is the input.

Also, the user will enter the fraction in a specified format which is:

For normal fraction, “a/b” (a and b are integers)

For whole numbers, “c” (c is an integer)

For mixed fraction, “c a/b” (c is integer, a/b is the fraction separated by a space)

I want the program to check and find out which type of fraction the user has entered and then proceed. I’m using If-Else If-Else for this.

Here’s a code snip:

var result: List<Int> = listOf(0,1,0)
try {
            if ((fraction.contains('/') && fraction.indexOf('/') == fraction.lastIndexOf('/')) && !fraction.contains(" ")) {
                //input is a regular fraction
                
            } else if (fraction.isDigitsOnly()) {
                //input is a whole number
                
            } else if ((fraction.contains('/') && fraction.indexOf('/') == fraction.lastIndexOf('/')) && (fraction.contains(" ") && fraction.indexOf(' ') == fraction.lastIndexOf(' '))) {
                //input is mixed fraction
                
            }
            else {
                Toast.makeText(applicationContext,
                "The number you entered is not in a valid format.",
                Toast.LENGTH_LONG).show()
            }
            //simplifying input
            if (result(2) != 0){
                numerator += whole_number * denominator
                result = listOf(numerator, denominator, 0)
            }
            return result
        }
        catch (e: Exception){
            Toast.makeText(applicationContext,
                "The number you entered is not in a valid format.",
                Toast.LENGTH_LONG).show()
            return result
        }

Is this the best way I can do that or is there more cleaner and efficient code I can make (personally I think this is too messy and can be made more efficient)? Please guide me.

beginner – Using locals in Forth to avoid stack manipulation

I’m doing Project Euler problems as a learning platform for Forth.

Problem 8 (*) involves a 1000-long string, which I entered directly in the source code.

My code is

: e008-multNdigits ( a n -- p )
    1 swap 0 do swap dup i + c@ (char) 0 - rot * loop nip ;

: euler008
    0 13 locals| length maxproduct |
    s" 731671765313306249192...450"
    ( a 1000 )
    length - 0 do
        dup i + length e008-multNdigits
        dup maxproduct > if to maxproduct else drop then
    loop maxproduct . ;

See my github

My questions are:

  1. What options are common for dealing with input?
  2. If I put the locals on the stack, won’t that make the loop too full of (otherwise unneeded) stack manipulation words?
  3. Suggestions, criticism, nitpicks are welcome…

(*) Project Euler Problem 8: find the maximum product of 13 consecutive digits in a 1000-long string.

beginner – Tic-Tac-Toe in Java

I am currently learning Java; I could really use some help from more experienced programmers.

How can I clean up my Tic-Tac-Toe code? What mistakes have I made? Can I use more exception handling? I tried to use exception handling, in isValidStepCheck and takenFieldCheck, but I don’t think I used it efficiently.

public class TicTacToe {
    public static String() bpos = {" 1 ", " 2 ", " 3 ", " 4 ", " 5 ", " 6 ", " 7 ", " 8 ", " 9 "};
    public static int turn = 0;
    public static int num;
    public static String numS;
    public static String winner = "n";
    public static int r = 0;

    public static void main(String() args) {
        System.out.println("Welcome to the Tic-Tac-Toe game.");
        Board();
        System.out.println("X has the first step, enter a number.");
        try{TicTacToeGame();}
        catch (Exception e){
            System.out.println("Something went wrong. Are you sure you entered a number?");
        }
    }


    static boolean isValidStepCheck() {
        while (true) {
            Scanner sc = new Scanner(System.in);
            num = sc.nextInt();
            numToString();
            if (num < 1 || num > 9) {
                System.out.println("You have to enter a number between 1 and 9!");
            } else {
                return true;
            }
        }
    }

    static void isValidMove() {
        while (true) {
            if (isValidStepCheck() && !takenFieldCheck()) {
                if (turn % 2 == 0) {
                    turn++;
                    bpos(num - 1) = " x ";
                    Board();
                    break;
                } else if (turn % 2 == 1) {
                    turn++;
                    bpos(num - 1) = " o ";
                    Board();
                    break;
                }
            } else if (takenFieldCheck()) {
                System.out.println("This field is already taken!");
            }

        }
    }

    static void Board() {
        System.out.println(" ___________ ");
        System.out.println("|" + bpos(0) + "|" + bpos(1) + "|" + bpos(2) + "|");
        System.out.println("|-----------|");
        System.out.println("|" + bpos(3) + "|" + bpos(4) + "|" + bpos(5) + "|");
        System.out.println("|-----------|");
        System.out.println("|" + bpos(6) + "|" + bpos(7) + "|" + bpos(8) + "|");
        System.out.println(" ----------- ");
    }

    static boolean takenFieldCheck() {
        if (bpos(num - 1).equals(numS)) {
            return false;
        } else {
            return true;
        }
    }

    static void numToString() {
        switch (num) {
            case 1:
                numS = " 1 ";
                break;
            case 2:
                numS = " 2 ";
                break;
            case 3:
                numS = " 3 ";
                break;
            case 4:
                numS = " 4 ";
                break;
            case 5:
                numS = " 5 ";
                break;
            case 6:
                numS = " 6 ";
                break;
            case 7:
                numS = " 7 ";
                break;
            case 8:
                numS = " 8 ";
                break;
            case 9:
                numS = " 9 ";
                break;
        }
    }

    static void isWon() {
        String line = null;
        if (winner.equals("n")) {
            for (int i = 0; i < 8; i++) {
                switch (i) {
                    case 0:
                        line = bpos(0) + bpos(1) + bpos(2);
                        break;
                    case 1:
                        line = bpos(3) + bpos(4) + bpos(5);
                        break;
                    case 2:
                        line = bpos(6) + bpos(7) + bpos(8);
                        break;
                    case 3:
                        line = bpos(0) + bpos(3) + bpos(6);
                        break;
                    case 4:
                        line = bpos(1) + bpos(4) + bpos(7);
                        break;
                    case 5:
                        line = bpos(2) + bpos(5) + bpos(8);
                        break;
                    case 6:
                        line = bpos(0) + bpos(4) + bpos(8);
                        break;
                    case 7:
                        line = bpos(2) + bpos(4) + bpos(6);
                        break;
                }
                if (line.equals(" x  x  x ")) {
                    winner = "x";
                } else if (line.equals(" o  o  o ")) {
                    winner = "o";
                }
            }

        } else {
            winner = "n";
        }
    }

    static void TicTacToeGame() {
        while (true) {
            isValidMove();
            isWon();
            r++;
            if (winner.equals("x")) {
                System.out.println("Congrats to X, you won!");
                break;
            } else if (winner.equals("o")) {
                System.out.println("Congrats to O, you won!");
                break;
            }
            else {
                if(r==9){
                    System.out.println("Its a draw!");
                    break;
                }
            }
        }
    }
} 
```

calculus – Calc Beginner Question

Thanks for contributing an answer to Mathematics Stack Exchange!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.

To learn more, see our tips on writing great answers.

beginner – LeetCode 76: Minimum Window Substring [C++]

I’m posting an sliding window problem of LeetCode (Minimum Window Substring) with C++. If you have time and would like to review the code, please do so, I appreciate that.

On LeetCode, we are only allowed to change the variable names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).

Problem

Given a string base_string and a string target, find the minimum window
in base_string which will contain all the characters in target in
complexity O(n).

Example:

Input: base_string = “ADOBECODEBANC”, target = “ABC” Output: “BANC”
Note:

If there is no such window in base_string that covers all characters in
target, return the empty string “”. If there is such window, you are
guaranteed that there will always be only one unique minimum window in
base_string.

C++

class Solution {
public:
    string minWindow(string base_string, string target) {
        vector<int> count_map(128, 0);

        for (auto character : target)
            count_map(character)++;

        int left = 0, right = 0;
        int min_left = 0, min_right = INT_MAX;
        int target_length = target.size();

        while (right < base_string.size()) {
            if (count_map(base_string(right++))-- > 0)
                target_length--;

            while (target_length == 0) {
                if (right - left < min_right)
                    min_right = right - (min_left = left);

                if (count_map(base_string(left++))++ == 0)
                    target_length++;

            }
        }

        return min_right == INT_MAX ? "" : base_string.substr(min_left, min_right);
    }
};

Reference

beginner – A pretty simple Rock, Paper, Scissor game on C++

I’ve decided to learn more about C++ with the time that I have right now through Udemy courses. To test out the stuff that I’ve learned up until now, I decided to try and code with some of the knowledge I’ve gained. I wanted try out object oriented features since I’ve been doing stuff through procedural programming instead. This is just a simple program utilising a few bits of OOP. I’m not sure if my use of it is appropriate (seeing as it is very minimal in use throughout the program). I would love some feedback and some tips to improve. Please keep feedback simple since I’m new to programming in general, and I don’t know all of the technical jargon. Thanks.

// SIMPLE ROCK PAPER SCISSOR GAME w/ some OOP features
#include <cstdlib>
#include <vector>
#include <ctime>
#include <string>
#include <iostream>
using namespace std;

class Player {      //stores player/enemy points
private:
    int score;
public:
    int getScore() {
        return score;
    }
    
    void incrementScore() {
        score++;
    }
    //constructor
    Player(int points);
};

//constructor
Player::Player(int points)
    : score {points} {
}

int convertToInt(string pChoice) {      //converts player input into integers
    if (pChoice == "Rock" || pChoice == "rock") {
        return 0;
    }
    else if (pChoice == "Paper" || pChoice == "paper") {
        return 1;
    }
    else if (pChoice == "Scissor" || pChoice == "scissor") {
        return 2;
    }
    
    return 0;
}

bool inputValidation(const vector <string> choices, string pChoice) {      //validates player input
    bool boolean {};
    for (const string choice : choices) {     //checks vector that contains a list of all possible options
        if (choice == pChoice) {        
            boolean = true;
            break;
        }
        else {
            boolean = false;
        }
    }
    return boolean;
}

void printEnemyChoice(unsigned int &enemyRand, string &enemyChoice) {   //prints enemy choice
//remember that 0, 1 and 2 correspond to rock, paper and scissor respectively
    switch (enemyRand) {
        case 0: {
            enemyChoice = "Rock";
            cout << "Enemy picked: " << enemyChoice << endl;
            break;
        }
        case 1: {
            enemyChoice = "Paper";
            cout << "Enemy picked: " << enemyChoice << endl;
            break;
        }
        case 2: {
            enemyChoice = "Scissors";
            cout << "Enemy picked: " << enemyChoice << endl;
            break;
        }
    }
}

void checkResult(Player &playerScore, Player &enemyScore, unsigned int &playerIChoice, unsigned int &enemyRand) {   //determines the winner
/* a 2D array is used to compared playerIChoice (the player's choice) and the enemy's choice (randomly generated)
 * 0 represents draw
 * 1 represents player's win
 * 2 represents enemy's win
 * remember that 0, 1, 2 is also Rock, Paper and Scissor respectively.. bit confusing. Hope theres a better way to name this properly.
 * for eg. if playerIChoice = 2 (Scissors) and enemyRand = 1 (Paper), this points to "1" on the 2D array (3rd row, column 2)
 * since it points to a "1", therefore the player wins (Scissors beats Paper). 
 * 1 is assigned to result, which is used in a switch statement to print out the winner on case 1 and increments the playerScore.score attribute.
 */ 

    int resultArray(3)(3) {
        {0, 2, 1},  
        {1, 0, 2},
        {2, 1, 0}
    };
        
    int result = resultArray(playerIChoice)(enemyRand);
    switch (result) {
        case 0: {
            cout << "Result is: Draw" << endl;
            break;
        }
        case 1: {
            cout << "Result is: You win!" << endl;
            playerScore.incrementScore();
            break;
        }
        case 2: {
            cout << "Result is: You lose!" << endl;
            enemyScore.incrementScore();
            break;
        }
    }
}

int main() {
    Player playerScore {0};
    Player enemyScore {0};
    bool gameLoop {true};
    const vector <string> choices {"Rock", "rock", "Paper", "paper", "Scissor", "scissor", "Q", "q"};
    string playerChoice {};
    string enemyChoice {};
    unsigned int playerIChoice {};
    unsigned int enemyRand {};
    
    cout << "======================================" << endl;
    cout << "Rock, Paper, Scissor! - CLI w/ Objects" << endl;
    cout << "======================================" << endl;
    
    while (gameLoop) {
        cout << "nChoose rock, paper, or scissor: " << endl;
        cout << "Press Q to quit the game." << endl;
        cin >> playerChoice;
        
        if (playerChoice == "Q" || playerChoice == "q") {
            cout << "Thanks for playing." << endl;
            gameLoop = false;
            break;
        }
        
        if (inputValidation(choices, playerChoice) == false) {      //passes vector with valid input and player's input to compare
            cout << "Invalid input, try again!" << endl;
            continue;
        }
        
        cout << "You picked: " << playerChoice << endl;
        playerIChoice = convertToInt(playerChoice);         //converts valid input into integers to compare with enemy's choice
        
        srand (time(NULL));
        enemyRand = rand() % 3;     //generates random number from 0-2
        
        printEnemyChoice(enemyRand, enemyChoice);
        checkResult(playerScore, enemyScore, playerIChoice, enemyRand);
        
        cout << "nYour score is: " << playerScore.getScore() << endl;
        cout << "Enemy score is: " << enemyScore.getScore() << endl;
    }
    
    return 0;
}

beginner – LeetCode 560: Subarray Sum Equals K [Python]

According to LeetCode, the following question is one of the most frequent interview questions asked by companies such as Facebook and Google. In this post, I’m adding Python solution, if you’d like to review, please do so.

Thank you!

Given an array of integers and an integer target (K), you need to find the
total number of continuous subarrays whose sum equals to target.

Example 1:

Input:nums = (1,1,1), target = 2 Output: 2

Constraints:

The length of the array is in range (1, 20,000).
The range of numbers in the array is (-1000, 1000) and the range of the integer target is (-1e7,
1e7).

Python


from typing import List


class Solution:
    def subarraySum(self, nums: List(int), target: int) -> int:
        subarrays = 0
        cur_sum = 0
        memo = {0: 1}
        for index, num in enumerate(nums):
            cur_sum += num
            subarrays += memo.get(cur_sum - target, 0)
            memo(cur_sum) = -~memo.get(cur_sum, 0)
        return subarrays

Reference

beginner – Very simple semantic implementation of the structure of a web page with three elements: header, main, and footer, using Flexbox

I’m new to web development, and currently learning the basics of HTML and CSS. Many web pages follow the structural pattern of header, main, and footer; so I figured it’d be a good idea to try and implement this structure to see how things are carved.

This is my attempt:

body {
  display: flex;
  flex-direction: column;
  font-family: sans-serif;
  margin: 0;
  min-height: 100vh;
}

header,
footer {
  background-color: dodgerblue;
  color: white;
  text-align: center;
}

main {
  background-color: snow;
  flex: 1;
  padding: 1rem;
}

footer {
  margin-top: auto;
}
<!DOCTYPE html>

<html lang="en">

<head>
  <title>Test</title>
  <link rel="stylesheet" href="main.css">
  <meta charset="UTF-8">
</head>

<body>
  <header>
    <h1>Header</h1>
  </header>

  <main>
    <h2>Main content</h2>
  </main>

  <footer>
    <h3>Footer</h3>
  </footer>
</body>

</html>

I’m looking for all kinds of feedback, from style, to anti-patterns, ways to do things more concisely, and whatever other observation you can find useful. I do have some specific questions:

  1. Are the semantic HTML elements used correctly? There’s no need for an article element inside the main element, right?
  2. In the CSS I selected both header and footer for stuff that they have in common, is this good practice? Or should I keep a single header and a single footer selectors, separately? Could be more maintainable that way?
  3. Is this normally handled using Flexbox? Or is Grid display a better tool for this?
  4. What things would you do differently?

Thanks for your time!