programming languages – Advice on learning how to create a game for beginner

First time posting here. I have been suggested from stackoverflow to post here. I notice some questions similar to this exist, like Can a beginner in programming start learning game development? and etc. If this question is off-topic, hopefully I can get advice on where I can post this (not sure whether I should post this on gaming SE or gamedev SE instead). I would like to ask advice on learning programming.

I have a strong desire to create a music/rhythm mobile game similar to Guitar Hero or Piano Tiles, but with some twists and flavours of my own. Here is my situation that may be considered.

  1. I am weak in programming language. I do not know Java (where many told me this is the language to go for my purpose). I mean, I have been introduced to some basics of Pascal, C, C++, or done some coding with Matlab, in high school or undergraduate study, but never have I learnt or truly dedicated myself in programming.

  2. Part of the reason is because I focused a lot on mathematics (bachelor and master degree). My bachelor thesis used some coding in Matlab (I actually loved doing pure math but the topic really interested me, so I learnt Matlab instead), while the master one got me back to pure math in discrete math. Now, I finally have the time to do this.

  3. Therefore, I honestly have a clear and detailed picture of the algorithm I want to create, and I can write them down too since I did that quite often in math. However, I am pretty sure the journey is still far because I eventually need to learn the language.

Here are some questions that hopefully can be addressed:

A. Considering the above, how long/how hard realistically would it be to reach the above goal, assuming 4 hours of work/learning a day? I know this is very opinion-based, but that is actually the point and hopefully it can help.

B. I wonder about this too, but do there exist any community or service that help creating a program for you upon your request? If so, how do they work? I mean like, the price, the method, etc.

I appreciate the advice a lot. Thank you in advance.

EDIT: I posted the link as an example, where I thought this would be allowed since there are some responses in that question too. Hence, I tried putting my intention in the first paragraph above too. Thanks for pointing it out.

algorithms – GPU Programming question

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.

functional programming – Node.js ws server: global or local functions?

I’m working on a Node.js chat app project using the ws library. I have it up and running but I’m still making improvements and adding stuff like authentication, etc. Before I get too far, I am wondering what the best functional approach to handling messages (and other events) is. For example, right now I have the following code to handle a message from the client (I cut out most of it, just keeping in one function to use as an example):

wss.on('connection', (ws, req) => {
    // Give them the funtions (uses local ws)
    function handleMessage(msgJSON) {
        let incMsg = {};
        try {
            incMsg = JSON.parse(msgJSON); // message from client
        } catch {
            console.error("Could not parse sent JSON");
            return;
        }
        switch (incMsg.type) {
            case "message":
                 ws.send("Message sent.");
                 // send the message to other clients:
                 wss.clients.forEach(client => {
                      // send message to all open clients but not this client
                      if (client !== ws && client.readyState === WebSocket.OPEN) {
                           client.send(`${client.username}: ${incMsg.message}`);
                      }
                 }
            // some more cases, like for "meta"
        }
    }

    // more functions ...

    ws.on('message', message => {
        handleMessage(message);
    });
}

This strategy takes advantage of having the ws variable inside the inner function, but this makes the wss.on('connection') handler full of a lot of functions. Is it better practice to use this approach or to make a global sort of function that you then pass the client into? My alternate idea looks like this:

function handleMessage(msgJSON, ws) { // accepts the current client
    let incMsg = {};
    try {
        incMsg = JSON.parse(msgJSON); // message from client
    } catch {
        console.error("Could not parse sent JSON");
        return;
    }
    switch (incMsg.type) {
        case "message":
             ws.send("Message sent.");
             // send the message to other clients:
             wss.clients.forEach(client => {
                  // send message to all open clients but not this client
                  if (client !== ws && client.readyState === WebSocket.OPEN) {
                       client.send(`${client.username}: ${incMsg.message}`);
                  }
             }
             break;
        // some more cases, like for "meta" ...
    }
}

// more functions ...

wss.on('connection', (ws, req) => {
    ws.on('message', message => {
        handleMessage(message, ws); // pass along the ws client
    });
}
```

programming languages – How to prove that replacing a character in a string in both C and JavaScript is equivalent?

I would like to try some different proofs, specifically in proving equivalence of the implementation of some feature in two different programming languages (C and JS in this question).

This is about proving that replacing one character in a string is equivalent in C and JS.

In JS, for example, strings are immutable, while in C, strings are mutable. So in JS you might have to do this:

functioni replaceAt(string, index, replacement) {
  return string.substr(0, index) + replacement + string.substr(index + replacement.length)
}

While in C you might just do something like this:

#include<stdio.h>

int
main() {
  char string(11) = "hello world";
  string(1) = 'i';
  printf("%s", string);
  return 0;
}

Basically, I am trying to come up with an example where, the perceived effect or desired outcome is for all intents and purposes the same. That is, the end result is that the character was replaced at a specific position (the same position in each language). Even though in one language the string was mutable, while in the other, it was immutable. What needs to be taken into account here to make a proof saying these are equivalent? How do we capture the notion of “partial equivalence” or “perceived equivalence”? (By that I mean, the outcome is roughly the same, so we want to make a proof statement that these are the same with regard to some spec).

functional programming – My implementation of Clojure’s assoc-in

This is my implementation of Clojure’s assoc-in function. I am looking for tips on making it more idiomatic and in general, better.

(defn my-assoc-in
  (m (& ks) v)
  (let (sorted-keys (reverse ks))
    (loop (curr-key (first sorted-keys)
           rem-keys (rest sorted-keys)
           curr-map (get-in m (reverse rem-keys))
           acc-val  (assoc curr-map curr-key v))
      (if (empty? rem-keys)
        acc-val
        (let (next-key (first rem-keys)
              next-rem (rest rem-keys)
              next-map (get-in m next-rem)
              next-val (assoc next-map next-key acc-val))
          (recur next-key next-rem next-map next-val))))))

algorithms – What to do if you are stuck with programming exercises as a beginner? [Programming: Principles and Practice using C++]

it’s me again,

recently I posted some questions about my programming problems while working through my lecture adressed in the title of this question. I am currently in a very frustrating situation where I am getting stuck with almost every exercise/problem I get. I’ve tried to get help with single questions but this doesn’t really seem to work for me. So instead, I try to get some general advice by some experienced Stack users. To avoid being blamed, I can say: I tried for myself, for hours and days! I can’t wrap my head around for writing simple algorithms such as the sieve of eratosthenes or finding all prime numbers and all this kind of things, pretty simple problems, right? I did a lot of research in the internet and I saw the same things over and over again, that I should split up my problems, write pseudo code, make sketches on paper or simply use comments in code. I tried them all, and I don’t see a difference. I wrote down problems step by step and tried to solve them but I simply don’t know how to translate ideas into code yet. I am giving myself ~4 hours a day while having other responsibilities such as school and keeping myself fit while sitting at home during quarantine. My book says that I shouldn’t skip exercises and doing everything but if I don’t see any progress, my motivation for doing this hobby will break slowly… I could, of course, look for solutions on the internet but I think it isn’t the best way to proceed because it is other people’s work and I want and need to develop my own programming style and learn problem solving. I am really looking forward for some advice by experienced people who went through a similar situation or simply try to motivate me. My goals for the far future are jumping into graphics and VR development but it is pretty far away and if I am not able to utilise the basic tools, I can’t do the advanced stuff. I have used learning resources such as learncpp.com on the internet as well but I recognized that it doesn’t really help me at all so I ordered this book which many people recommended to me for making myself familiar with the basic concepts of the basic tools. Also, I have the problem that I don’t have any friends or relatives who are interested in programming in any manner. I have actually nobody to discuss as people suggest this pretty often as well to just make it clear. Thank you for reading this long text, I hope this question is worthy for Stack and please be gentle to me.

functional programming – Proving injectivity for an algorithm computing a function between sets of different types of partitions

I am attempting to solve the following problem:

Let $A$ be the set of partitions of $n$ with elements $(a_1, dots, a_s)$ such that $a_i > a_{i+1}+a_{i+2}$ for all $i < s,$ taking $a_{s+1} = 0.$ Define $g_n = F_{n+2}-1$ and let $B$ be the set of partitions of $n$ as $b_1 ge dots ge b_s$ such that $b_i in {g_n}$ for all $i,$ and if $b_1 = g_k$ for some $k,$ then $g_1, dots, g_k$ all appear as some $b_i.$ Prove $|A|=|B|.$

Attempt: Let $e_i$ be the vector with $1$ at position $i$ and $0$ elsewhere. If $b_1 = g_k,$ let $c=(c_k, dots, c_1)$ count how many times $g_i$ appears. We calculate $f: B to A$ as follows:

Let $c=(c_k,dots,c_1), a=(0,dots,0).$ While $c ne 0,$ let $d_1 > dots > d_k$ be the indices such that $c_{d_i} ne 0.$ Replace $c, a$ with $c-(e_{d_1}+dots+e_{d_k}), a+(g_{d_1} e_1 + dots + g_{d_k} e_k)$ respectively. After the while loop ends, let $f(b)=a.$

Let $sum a, sum b, sum c$ be the sum of the components of $a, b, c$ respectively. Since $sum c$ decreases after every loop, the algorithm terminates and $f(b)$ is well-defined. Since $c_k g_k + dots + c_1 g_1 + sum a$ does not change after every iteration, is $sum b$ at the start and $sum a$ at the end, we have $sum f(b) = sum b = n,$ so $f(b)$ is also a partition of $n.$ Now $a = (g_k, dots, g_1)$ after the first loop, which satisfies the condition $g_i > g_{i-1}+g_{i-2}$ since $g_i = F_{n+2}-1 = (F_{n+1}-1)+(F_n-1)+1 > g_{i-1}+g_{i-2}.$ Furthermore, after every iteration of the loop, the difference $a_i – (a_{i-1}+a_{i-2})$ changes by $0, g_{d_j}-g_{d_{j-1}} > 0,$ or $g_{d_j}-(g_{d_{j-1}}+g_{d_{j-2}}) > 0,$ so we have $a_i > a_{i-1} + a_{i-2}$ at the end and hence $f(b) in A.$ Thus, $f: B to A$ is well-defined.

In order to prove the injectivity of $f,$ it suffices to prove each loop iteration as a mapping $(c,a) to (c’,a’)$ is injective, which would imply the mapping $(c,0) to (0,a)$ that the while loop creates is injective. Indeed, if $f(b_1) = f(b_2) = a$ with $(c_1, 0), (c_2, 0)$ being sent to $(0, f(b_1)) = (0,a), (0, f(b_2)) = (0,a)$ respectively, then we have $(c_1, 0) = (c_2, 0) Rightarrow c_1 = c_2 Rightarrow b_1 = b_2.$

Suppose $d_1 > dots > d_i, f_1 > dots > f_j$ are the non-zero indices of $c_1, c_2$ respectively and $c_1 – (e_{d_1}+dots+e_{d_i}) = c_2 – (e_{f_1}+dots+e_{f_j}), a_1+g_{d_1}e_1 + dots+ g_{d_i} e_i = a_2 + g_{f_1} e_1 + dots + g_{f_j} e_j.$ If $x ge 2$ is an entry of $c_1,$ it decreases by $1,$ so the corresponding entry in $c_2$ after $c_2$ is modified is also $x-1,$ which means it must’ve been $(x-1)+1 = x$ before since $x-1>0.$ Thus, if the values of two positions of $c_1, c_2$ differ, one is $1$ and the other is $0.$ However, if $c_1 = (1,0), a_1 = (3,1), c_2 = (0,1), a_2 = (4,1),$ then $(a_1, c_1), (a_2, c_2)$ both get sent to $((5,1), (0,0)).$ I can rule out this specific example by arguing that one of the pairs is illegal and could not have come from any choice of initial $c,$ but I have no idea on how to do this in general.

What should I do next in order to show $f$ is injective? Furthermore, since the problem I’m trying to prove is correct, injectivity would imply $f$ is secretly a bijection. But I have no clue on how to even start on the surjectivity of $f,$ so I just constructed a similar algorithm for $g: A to B$ in the hopes of proving $g$ is injective too. If I can show $f$ is injective I will probably know how to show $g$ is.

Here is an example of $f, g$ in practice:

Let $n = 41, b = (12, 7, 7, 4, 4, 2, 2, 2, 1) Rightarrow c = (1, 2, 2, 3, 1).$

$$((1, 2, 2, 3, 1), (0,0,0,0,0)) to ((0, 1, 1, 2, 0), (12, 7, 4, 2, 1)) to ((0, 0, 0, 1, 0), (19,11,6,2,1)) to ((21,11,6,2,1),(0,0,0,0,0)),$$ so $f(b) = (21,11,6,2,1).$

Let $a = (21, 11, 6, 2, 1).$

$$((21,11,6,2,1),(0,0,0,0,0)) to ((9,4,2,0,0), (1,1,1,1,1)) to ((2,0,0,0,0),(1,2,2,2,1)) to ((0,0,0,0,0),(1,2,2,3,1)),$$ so $g(a) = (12, 7, 7, 4, 4, 2, 2, 2, 1).$

programming languages – Suitable way to round results returned by any function of a class

Assume there is a abstract class Shape. The class has two functions area() and perimeter().

Let’s say Circle and Square inherit from Shape and override these methods. Obviously the results are going to be fractional.

What is the best way to set a precision value for the results. Say the user says PRECISION=2 or PRECISION=3 and the results returned by the functions of Circle and Square class are returned accordingly. Where should I define this functionality? I was wondering how do libraries like numpy handle this situation.

One approach can be to add an optional parameter to these functions and round the results accordingly.

getArea(radius, prec=2) {

}
```

programming – Including a two functions within a function

I am uncertain of how to correctly add a two functions into a function of multiple variables. I know that the answer should be around 13 yet I am returning an answer that is far from that. Have I incorrectly coded in the functions? Here is my code if you have time to help, thank you.

(*Constants*)

p0 = 1

g = 1000

m0 = 1

mw = 18.015268

y0 = 6.141500*(10^-1)

y1 = 4.825133*(10^4)

y2 = -6.770793*(10^4)

y3 = 1.010210*(10^7)

n = 6

a0 = -0.864671

a1 = 8659.19

a2 = -22786.2

b0 = 0.642044

b1 = -56.8534

b2 = -0.375754

(*Functions*)

pkg(t_) := y0 + (y1*(t^-1)) + (y2*(t^-2)) + (y3*(t^-3))

q(p_, t_) := ((p/p0)*Exp(a0 + (a1*t^-1) + (a2*p^(2/3)*t^-2)))

pkw(p_, t_) := -2*
   n*(Log(1 + q(p, t)) - ((q(p, t)/(q(p, t) + 1))*
       p*(b0 + (b1*t^-1) + b2*p))) + pkg(t) + (2*Log((m0*mw)/g))

If t=300 and p=1, pkw should equal 13.

dynamic programming – Asymptotic complexity of Combination sum problem vs Coin change problem

I’ve been looking at the following combination sum problem:

Given a set of candidate numbers (candidates) (without duplicates) and a target number 
(target), find all unique combinations in candidates where the candidate numbers sums to 
target.

The same repeated number may be chosen from candidates unlimited number of times.

Input: candidates = (2,3,5), target = 8,
A solution set is:
(
  (2,2,2,2),
  (2,3,3),
  (3,5)
)

Most of the solutions I encountered for this problem were some variant of the following backtracking solution:-

public List<List<Integer>> combinationSum(int() nums, int target) {
    List<List<Integer>> list = new ArrayList<>();
    backtrack(list, new ArrayList<>(), nums, target, 0);
    return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int () nums, int 
remain, int start){
    if(remain < 0) return;
    else if(remain == 0) list.add(new ArrayList<>(tempList));
    else{ 
        for(int i = start; i < nums.length; i++){
            tempList.add(nums(i));
            backtrack(list, tempList, nums, remain - nums(i), i); // not i + 1 because we can reuse same elements
            tempList.remove(tempList.size() - 1);
        }
    }
}

Most of the comments of these solutions implied an asymptotic complexity of O(2^N) due to this code potentially building up all subsets in the worst case.

However, this problem statement seems very similar (if not identical) to the Coin change problem

You are given coins of different denominations and a total amount of money. Write a function 
to compute the number of combinations that make up that amount. You may assume that you have 
infinite number of each kind of coin.

Input: amount = 5, coins = (1, 2, 5)
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

The most common solution I’ve found to this problem is the following O(N*amount) dynamic programming solution:

class Solution {
  public int change(int amount, int() coins) {
    int() dp = new int(amount + 1);
    dp(0) = 1;

    for (int coin : coins) {
      for (int x = coin; x < amount + 1; ++x) {
        dp(x) += dp(x - coin);
      }
    }
    return dp(amount);
  }
}

It seems to me that the first solution is just the top down variant of this algorithm.

I can’t seem to figure out why the first solution is exponential and the second one is not.
Where have I gone wrong in my understanding?

Is it actually printing the subsets vs counting that makes the difference here?

Is there any way print all combinations whilst preserving polynomial time?