cpu – What subfields in computer sciences may one study without learning Object Oriented Programming?

Object Oriented Programming is a type of programming paradigm.

A Computer Science degree is mostly theoretical (not only machine learning and applied statistics! Believe me there is so much more), so you wont see any of this in most courses, however, in a Software Engineering degree I suppose you do learn more about OOP.

Anyways, OOP is always good to know. Its not as complicated as you would think from its fancy name, and it gives a nice way to write organized code, and most programming languages support that kind of programming.

However, there are some programming languages that use a different type of programming paradigm called “functional programming”. I recommend you to take a look at it too.

If you are wondering about what kinds of things there are in a CS degree, feel free to ask me!

BTW: This Stack Exchange site is for theoretical computer science, so questions about theoretical computer science problems are seen here all of the time.

procedural programming – Trouble using For to create multiple graphs of increasing complexity

I was doing some math research, and I was investigating certain functional graphs involving modular arithmetic. I was trying to create multiple graphs at once using the For function (f(x) has been altered for the sake of confidentiality):

For(n=1,n<10,n++,
f(x_):=Mod(x,n);
Graph(Table(x->f(x),{x,0,n-1}), VertexLabels ->"Name"))

but I don’t get any output when I run the code. However, whenever I was running this without For, it worked perfectly.

I’ve tried taking away Graph, but running the code with just Table doesn’t work either. I tried using Print while keeping the top 2 lines, and that worked. I believe the issue is something to do with looping Table, but I could be wrong. Can anyone help?

functional programming – What’s the value of IO Monad?

When I’m writing code in the form of IO Monad, I wonder what’s real value of it.For example I have a function as def something(in: In): IO(Out); my function is a pure function that **returns an impure recepie(just another function) which could be composed with other receipes, and finally triggered.

Is postponing the side-effects the best I get? In other words, what’s the difference in the value between a function with side-effects, and a pure function which return an impure function? In my eyes both approches could be testable, trackable, debugable (the IO version could be harder, as stacktraces are not as helpful as simple stack-calls).

Where does one find programming books that assume you are already a programmer?

Software engineering books like Code Complete and Working Effectively with Legacy Code obviously already assume you can program, but books to introduce you to a technology or teach a certain kind of software to build, like an O’Reilly book like NLP in Python, will usually have redundant tutorial cruft at the initial parts that weigh down the book. Beuken’s Game Programming in C/C++ does a good job of not teaching C/C++. How do you find more of these books? Do any publishers devote themselves to intermediate/advanced books? Is there a list of such books somewhere?

programming languages – An expression in the first line of the control flow statement

Is there a term or some short wording to refer to an expression in the “first” line of the control flow statement?

func() {
  if (a == b) {
    var = 1 + 1
    return True
  } else {
    var = 5 + 5
    return False
  }
}
if ((a == b)
 && (c == d)) {
  ...
}

In the first example, the term/wording should “match” a == b, True, and False. It should not match 1 + 1 and 5 + 5.

In the second example, it should match (a == b) && (c == d).

I used to use “control flow statement expression”, but I do not think this term is accurate.

programming challenge – C++, sort integers using knowledge of entire vector

I am solving the “Sort” problem on Kattis.

Mirko is a great code breaker. He knows any cipher in the world can be broken by frequency analysis. He has completely the wrong idea what frequency analysis is, however.
He intercepted an enemy message. The message consists of N
numbers, smaller than or equal to C.
Mirko belives freqency analysis consists of sorting this sequence so that more frequent numbers appear before less frequent ones.
Formally, the sequence must be sorted so that given any two numbers X
and Y, X appears before Y if the number of times X appears in the original sequence is larger than the number of time Y does. If the number of appearances is equal, the number whose value appears sooner in the input should appear sooner in the sorted sequence.
Help Mirko by creating a “frequency sorter”.
Input
First line of input contains two integers, N (1≤N≤1000), the length of the message, and C (1≤C≤1000000000), the number from the task description above.
The next line contains N positive integers smaller than or equal to C, the message itself.

Basically, the problem is as follows. Let xs be a nonempty vector of positive integers. There are only few integers in this vector, but they have a big range. (The maximum value c is given in the problem, but my code does not use the information.) Sort the integers according to the following criteria.

  1. For any two elements x and y of xs, if x occurs more often than y, then x appears first; if y appears more often, y appears first.
  2. If x and y appear equally often, then x occurs first if the very first occurrence of x is earlier than that of y.

I use a comparison sort (provided by the C++ runtime) with a smart comparator. This comparator knows the frequency and the index of the first appearance of every element. This information is not inherent to the integers. Rather, it depends entirely on their location within the vector. This contextual information is generated when a comparator is created for a given vector. Upon application on elements x and y, it returns true if x must appear before y.

I have used custom comparators before, but never have I used anything that contains state. In the disassembly with -Os I see many copy and move constructors called under sort(vector<unsigned> &). The code passes all tests, and it’s not slow.

But I wonder why the disassembly reveals so many copy and move calls, and whether this pattern of using heavy comparators is discouraged in C++. If this looks like a known pattern, I want to know its name. I appreciate general comments and insights.

#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <iostream>

typedef std::vector<unsigned> vector;

/// Comparison based on knowledge of the entire vector
struct compare {
    std::multiset<unsigned> bag;
    std::map<unsigned, size_t> indices;

    /// Extract frequency and initial index of every element.
    explicit compare(vector const &xs) {
        for (size_t i = 0u; i < xs.size(); ++i) {
            unsigned const x = xs(i);
            bag.insert(x);
            if (!indices.count(x)) {
                indices(x) = i;
            }
        }
    }

    /// True if `x` must go before `y`.
    ((nodiscard)) bool operator()(unsigned x, unsigned y) const {
        return bag.count(x) > bag.count(y)
               || (bag.count(x) == bag.count(y) && indices.at(x) < indices.at(y));
    }
};

static void sort(vector &v) {
    compare c(v);
    std::sort(v.begin(), v.end(), c);
}

int main() {
    vector v;
    {
        // Get `n` unsigned integers from console.
        // Unused: `c` (upper bound for integers)
        unsigned n, c;
        std::cin >> n >> c;
        v.reserve(n);
        while (n--) {
            unsigned x;
            std::cin >> x;
            v.push_back(x);
        }
    }
    // Sort according to the problem description
    sort(v);
    // Print all
    for (unsigned const x : v) {
        std::cout << x << ' ';
    }
    return 0;
}

programming – How can I iteratelly add elements to a list

Basically I want to make a histogram with a list of dates by using DateHistogram(). However I have the data of the dates in nested list format, with elements like {2020,6,26}, and although I know how to convert it to a date by using DateObject({2020,6,26}) I can not construct a list of dates by iteration. I am trying the following:

For(i = 0, i < 5, i++, Insert(egunak, DateObject(watchdates((i))), 1))

where watchdates is the nested list of {2020,6,26} date elements and egunak is the list I want to create with the dates (I have tried it to define it before).

I have also tried using Append instead of Insert or by iterating with Do, but didn’t succeed. I am pretty new with the Wolfram language, sorry.

functional programming – JavaScript — Convert decimal to another base

Source code is maintained on GitHub and may be cloned via…

mkdir -vp ~/git/hub/javascript-utilities

cd ~/git/hub/javascript-utilities

git clone git@github.com:javascript-utilities/decimal-to-base.git

… and a Live demo is hosted thanks to GitHub Pages.

The build target is ECMAScript version 6, and so far both manual tests and automated JestJS tests show that the decimalToBase function functions as intended, both for Browser and NodeJS environments.

Aware of (_number_).toString(_radix_) for converting numbers to another base I am, however, the built-in Number.toString() method doesn’t seem to have options for prefixing Binary, Octal, or Heximal bases, among other features that I’m implementing.

Example Usage

decimalToBase(540, 16);
//> "0x21C"

I am concerned with improving the JavaScript, and TypeScript that builds the JavaScript; ie. the HTML and CSS are intended to be simple and functional.

Please direct suggestions, and point out any mistakes that I’ve made, in regards to JavaScript. If anyone has a clean way of handling floating point numbers that’d be super, because at this time the current implementation only handles integers.


"use strict";

/**
 * Converts decimal to another base, eg. hex, octal, or binary
 * @function decimalToBase
 * @param {number|string} decimal
 * @param {number|string} radix - default `16`
 * @param {boolean} verbose - default `false`
 * @param {string()} symbols_list - default `(...'0123456789abcdefghijklmnopqrstuvwxyz')`
 * @returns {string}
 * @throws {SyntaxError|RangeError}
 * @author S0AndS0
 * @license AGPL-3.0
 * @see {link} - https://github.com/javascript-utilities/decimal-to-base
 * @example
 * decimalToBase(540, 16);
 * //> "0x21C"
 */
const decimalToBase = (decimal, radix = 16, verbose = false, symbols_list = (...'0123456789abcdefghijklmnopqrstuvwxyz')) => {
    decimal = Number(decimal);
    radix = Number(radix);
    const max_base = symbols_list.length;
    if (isNaN(decimal)) {
        throw new SyntaxError('First argument is Not a Number');
    }
    else if (isNaN(radix)) {
        throw new SyntaxError('radix is Not a Number');
    }
    else if (radix > max_base) {
        throw new RangeError(`radix must be less than max base -> ${max_base}`);
    }
    else if (radix < 2) {
        throw new RangeError(`radix must be greater than 2`);
    }

    let prefix = '';
    switch (radix) {
        case 16: // Hexadecimal
            prefix = '0x';
            break;
        case 8: // Octal
            prefix = '0o';
            break;
        case 2: // Binary
            prefix = '0b';
            break;
    }

    if (radix >= 10 && decimal < 10) {
        return `${prefix}${symbols_list(decimal)}`;
    }

    let converted = '';
    let dividend = decimal;
    while (dividend > 0) {
        const remainder = dividend % radix;
        const quotient = (dividend - remainder) / radix;
        /* istanbul ignore next */
        if (verbose) {
            console.log(`dividend -> ${dividend}`, `remainder -> ${remainder}`, `quotient -> ${quotient}`);
        }
        converted = `${symbols_list(remainder)}${converted}`;
        dividend = quotient;
    }

    return `${prefix}${converted.toUpperCase()}`;
};

/* istanbul ignore next */
if (typeof module !== 'undefined') {
    module.exports = decimalToBase;
}
*, *::before, *::after {
  box-sizing: border-box;
}

.container {
  max-width: 50%;
  position: relative;
}

.row {
  padding-top: 1rem;
}

.row::after {
  content: '';
  position: absolute;
  left: 0;
  background-color: lightgrey;
  height: 0.2rem;
  width: 100%;
}

.label {
  font-weight: bold;
  font-size: 1.2rem;
  width: 19%;
  padding-right: 1%;
}

.text_input {
  float: right;
  width: 79%;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Tests Decimal to Base</title>

    <!-- <link rel="stylesheet" href="https://codereview.stackexchange.com/assets/css/main.css"> -->

    <!-- <script type="text/javascript" src="assets/js/modules/decimal-to-base/decimal-to-base.js"></script> -->
    <script type="text/javascript">
      function updateOutput(_event) {
        const decimal = document.getElementById('decimal').value;
        const radix = document.getElementById('radix').value;
        const output_element = document.getElementById('output');

        let output_value = 'NaN';
        try {
          output_value = decimalToBase(decimal, radix)
        } catch (e) {
          if (e instanceof SyntaxError) {
            console.error(e);
          } else if (e instanceof RangeError) {
            console.error(e);
          } else {
            throw e;
          }
        }

        output_element.value = output_value;
      }

      window.addEventListener('load', (_event) => {
        document.getElementById('decimal').addEventListener('input', updateOutput);
        document.getElementById('radix').addEventListener('input', updateOutput);
      });
    </script>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <span class="label">Radix: </span>
        <input type="text" class="text_input" id="radix" value="16">
      </div>
      <br>

      <div class="row">
        <span class="label">Input: </span>
        <input type="text" class="text_input" id="decimal">
      </div>
      <br>

      <div class="row">
        <span class="label">Output: </span>
        <input type="text" class="text_input" id="output" readonly>
      </div>
    </div>
  </body>
</html>

For completeness here are the JestJS tests…

"use strict";
/**
 * @author S0AndS0
 * @copyright AGPL-3.0
 * @example <caption>Jest Tests for decimalToBase</caption>
 * // Initialize new class instance and run tests
 * const test_decimalToBase = new decimalToBase_Test();
 * test_decimalToBase.runTests();
 */
class decimalToBase_Test {
    constructor() {
        this.decimalToBase = require('../decimal-to-base.js');
        this.decimal_limits = { min: 1, max: 16 };
        this.base_configs = (
            {
                base: 2,
                name: 'Binary'
            },
            {
                base: 3,
                name: 'Trinary'
            },
            {
                base: 4,
                name: 'Quaternary'
            },
            {
                base: 5,
                name: 'Quinary AKA Pental'
            },
            {
                base: 6,
                name: 'Senary AKA Heximal or Seximal'
            },
            {
                base: 7,
                name: 'Septenary'
            },
            {
                base: 8,
                name: 'Octal'
            },
            {
                base: 9,
                name: 'Nonary'
            },
            {
                base: 10,
                name: 'Decimal AKA Denary'
            },
            {
                base: 11,
                name: 'Undecimal'
            },
            {
                base: 12,
                name: 'Duodecimal AKA Dozenal or Uncial'
            },
            {
                base: 13,
                name: 'Tridecimal'
            },
            {
                base: 14,
                name: 'Tetradecimal'
            },
            {
                base: 15,
                name: 'Pentadecimal'
            },
            {
                base: 16,
                name: 'Hexadecimal'
            }
        );
    }

    /**
     * Runs all tests for this module
     */
    runTests() {
        this.testsErrors();
        this.testsConversion();
    }

    /**
     * Uses `(Number).toString()` to check conversions, note this will only work for radix between `2` though `36`, and default `symbols_list`
     */
    static doubleChecker(decimal, radix) {
        decimal = Number(decimal);
        radix = Number(radix);
        let prefix = '';
        switch (radix) {
            case 2:
                prefix = '0b';
                break;
            case 8:
                prefix = '0o';
                break;
            case 16:
                prefix = '0x';
                break;
        }
        return `${prefix}${(decimal).toString(radix).toUpperCase()}`;
    }

    /**
     * Tests available error states
     */
    testsErrors() {
        test('Is a `SyntaxError` thrown, when `decimal` parameter is not a number?', () => {
            expect(() => {
                this.decimalToBase('spam!', 10);
            }).toThrow(SyntaxError);
        });
        test('Is a `SyntaxError` thrown, when `radix` parameter is not a number?', () => {
            expect(() => {
                this.decimalToBase(42, 'ham');
            }).toThrow(SyntaxError);
        });
        test('Is a `RangeError` thrown, when `symbols_list` is not long enough?', () => {
            expect(() => {
                this.decimalToBase(42, 37);
            }).toThrow(RangeError);
        });
        test('Is a `RangeError` thrown, when `radix` parameter is less than `2`?', () => {
            expect(() => {
                this.decimalToBase(42, 1);
            }).toThrow(RangeError);
        });
    }

    /**
     * Loops through `this.base_configs` and tests decimal integers between `this.decimal_limits('min')` and `this.decimal_limits('max')`
     */
    testsConversion() {
        const min = this.decimal_limits('min');
        const max = this.decimal_limits('max');
        this.base_configs.forEach((config) => {
            const { base } = config;
            const { name } = config;
            for (let decimal = min; decimal <= max; decimal++) {
                const expected_value = this.constructor.doubleChecker(decimal, base);
                test(`Base ${base}, does ${decimal} equal "${expected_value}" in ${name}?`, () => {
                    expect(this.decimalToBase(decimal, base)).toEqual(expected_value);
                });
            }
        });
    }
}
const test_decimalToBase = new decimalToBase_Test();
test_decimalToBase.runTests();

Questions

  • Are there any mistakes?

  • Have I missed any test cases?

  • Any suggestions on expanding this implementation to handle floating point numbers?

  • Any suggestions on making the code more readable?

  • Are there any additional features that are wanted?

C language programming – Computer Science Stack Exchange

Thanks for contributing an answer to Computer Science 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.

programming practices – How do you delegate coding task efficiently as a project manager?

I appreciate that you do not down vote this question. I deliberately did not make the question very specific. I believe your answer will help project managers in software development.

I would like to know your opinion in delegating task efficiently, it can be how detailed are you, or how demanding are you.

Please read tl:dr to understand the purpose of this question.

tl:dr

I am new to software engineering and currently competing in getting a bootcamp scholarship. The instructor gave a task in written paragraph. The paragraph explains how the apps works in detail with logic flow specified.

The task is simple but because of the logic flow is specified, the task becomes tedious and in the end the code becomes a very long if else statement.

Then, this question struck me and I put it on practice. I refactored the code with different logic flow and the code becomes shorter.

In my opinion after refactored the code

The written task should only explains the purpose of the app, the input, the output, the check in literal code, and the deadline. The process / logic flow should be left to the software engineer.

Sincerely,

kidfrom