Determine if a function is bijective Concise Problem Specification

Given an integer \$n\$ and a function \$f : X \to X \$ where \$X = \{1,2,3,..,n\}\$ Determine whether the given function is a bijective function or not.

Definition:

According to Wikipedia:

  In mathematics, a bijection, bijective function or one-to-one correspondence is a function between the elements of two sets, where each element of one set is paired with exactly one element of the other set, and each element of the other set is paired with exactly one element of the first set.

Constraints

\$1\le n \le 20 \$

Input format

There are  lines in the input.
The first line contains a single positive integer \$n\$.
The second line contains  space separated integers, the values of \$f(1)\$ , \$f(2)\$ ... ,  \$f(n)\$, respectively.

Output Format

On a single line, output "YES" if  is bijective. Otherwise, output "NO".

Solution

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Solution {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int n = in.nextInt();

        Set<Integer> codomain = new HashSet<Integer>();

        for (int i = 0; i < n; i++) {
            int y = in.nextInt();
            codomain.add(y);
        }

        System.out.println(codomain.size() == n ? "YES" : "NO");

        in.close();

    }

}

Comments

I am still relatively new to Java and would appreciate any comments on the above regarding improvements to my code.

Your code looks nice. The only suggestion I have is to separate the bijection check out of the main, and make it, say, a static method. All in all, I had this in mind:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class FunctionUtils {

    public static boolean isBijection(final Map<Integer, Integer> function) {
        final Set<Integer> domain = new HashSet<>(function.keySet());
        final Set<Integer> range  = new HashSet<>(function.values());
        return range.equals(domain);
    }

    public static void main(String[] args) {
        final Map<Integer, Integer> function = new HashMap<>();

        try (final Scanner in = new Scanner(System.in)) {
            final int n = in.nextInt();

            for (int i = 1; i <= n; i++) {
                function.put(i, in.nextInt());
            }

            System.out.println("Bijection: " + isBijection(function));
        }
    }
}

Hope that helps.

Edit

Validating general bijections \$f \colon X \to Y\$ is not any harder:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;

public class FunctionUtils {

    public static <E> boolean isBijection(final Map<E, E> function) {
        return function.size() == new HashSet<>(function.values()).size();
    }

    public static void main(String[] args) {
        final Map<Integer, Integer> function = new HashMap<>();

        try (final Scanner in = new Scanner(System.in)) {
            final int n = in.nextInt();

            for (int i = 1; i <= n; i++) {
                function.put(i, in.nextInt());
            }

            System.out.println("Function:  " + function);
            System.out.println("Bijection: " + isBijection(function));
        }
    }
}


Writing and reading code from a text file Using file stream object, write a program to read an external text file ("myCourse.txt") which contains all the course name and numbers you are taking this semester, and to generate an analysis (total number of courses) into an external file ("myCourseSummay.txt").

This is a past question my teacher has been hinting at us to practice, so my friend and I made this and wanted to know if would be acceptable. Personally, I think we messed the writing to the .txt file.

#include <iostream>
#include <fstream>
#include<string>
using namespace std;

int intro()
{
    cout << "Hello World!";
    return 0;
}

int main()
{
    ofstream myCourse;
    myCourse.open("myCourse.txt");
    char course1[20], course2[20], course3[20], course4[20];

    cout << "Enter number of courses. max of 4" << endl;
    cout << "Enter 1st course: ";
    cin >> course1;
    myCourse << course1 << endl;
    cout << "Enter 2nd course: ";
    cin >> course2;
    myCourse << course2 << endl;
    cout << "Enter 3rd course: ";
    cin >> course3;
    myCourse << course3 << endl;
    cout << "Enter 4th course: ";
    cin >> course4;
    myCourse << course4 << endl;

    myCourse.close();

    ifstream myCourseSummary;
    string word;
    int count = 0;
    myCourseSummary.open("myCourseSummary.txt");

    while(!myCourseSummary.eof())
    {
        myCourseSummary >> word;
        count++;
    }

    cout << "Total number if courses is(are) " << count << "!";
    myCourseSummary.close();

    cin.get();
    return 0;
}

eof inside a loop condition

See why is eof inside a loop condition considered wrong? You do not want to do:

while (!myCourseSummary.eof())
{
    myCourseSummary >> word;
    count++;
}

You do want to do:

while (myCourseSummary >> word)
{
    count++;
}

Arbitrary length course names

You are reading coureses into a char[20]. What if I have a 25-character course name? What about 50? What if it has a space in it? You need to handle all of these conditions, so you should prefer to std::getline a std::string.

Actually solve the problem

The problem statement is:

  read an external text file (“myCourse.txt”) which contains all the course name and numbers you are taking this semester

But you are prompting the user for course names and writing them to a file. You should read the file directly.

Also:

  generate an analysis (total number of courses) into an external file (“myCourseSummay.txt”)

You are currently writing into "myCourse.txt" and reading from "myCouresSummary.txt". The question asks you to read from the first, and write a number into the latter. That is:

std::ifstream myCourse("myCourse.txt");
// do some reading
// come up with what count is

std::ofstream myCourseSummary("myCourseSummary.txt");
myCourseSummary >> count;

You should be able to handle any number of courses. Just read from the file until it's done.


Scheduling Algorithm : First Come First Serve I am practicing opearator overloading and to write copy constructor. I have written this program of scheduling algoritrhm. Please suggest me some improvements.

#include <iostream>
#include <vector>

class Scheduling
{
    int process;
    std::vector<int> burst_time;
    std::vector<int> waiting_time;

  public:
    Scheduling() : process(0) {}
    Scheduling(int n) : process(n)
    {
        for (int i = 0; i < n; i++)
        {
            std::cout << "Enter Burst time for process " << i+1 << " : ";
            int val;
            std::cin >> val;
            burst_time.push_back(val);
        }
    }

    //copy constructor
    Scheduling(const Scheduling &other)
    {
        process = other.process;
        int size = other.burst_time.size();

        for (int i = 0; i < size; i++)
        {
            burst_time.push_back(other.burst_time[i]);
        }
    }

    //copy assignment
    Scheduling &operator=(const Scheduling &other)
    {
        process = other.process;
        int size = other.burst_time.size();

        for (int i = 0; i < size; i++)
        {
            burst_time.push_back(other.burst_time[i]);
        }

        return *this;
    }

    std::vector<int> cal_waiting_time(std::vector<int>& burst_time)
    {
        waiting_time.push_back(0);

        for (int i = 0; i < burst_time.size() - 1; i++)
        {
            waiting_time.push_back(waiting_time[i] + burst_time[i]);
        }
        return waiting_time;
    }

    void print_table()
    {
        waiting_time = cal_waiting_time(burst_time);
        std::cout << "Process\t Burst Time\t Waiting Time\n";
        for (int i = 0; i < burst_time.size(); i++)
        {
            std::cout << i+1 << "\t\t " << burst_time[i] << "\t\t " << waiting_time[i] << "\n";
        }
    }
};

int main()
{
    int num;
    std::cout << "Enter number of process\n";
    std::cin >> num;
    Scheduling batch1(num);
    batch1.print_table();

    Scheduling batch2(batch1);
    batch2.print_table();
}

int process;

  public:
    Scheduling() : process(0) {}
    Scheduling(int n) : process(n) { /* ... */ }

When initializing constant values for member data, prefer in-class member initializers.

Use reasonably descriptive names. For new users, is process a count? An id? They have to dig through the code to understand that it represents the number of processes stored.  Do you need process? Can you get by with the size of burst_time?

    std::size_t process_count {0};

  public:
    Scheduling() = default;

    Scheduling(std::size_t number_of_processes)
    : process_count (number_of_processes)
    { /* ... */ }

    std::vector<int> burst_time;
    std::vector<int> waiting_time;

burst_time and waiting_time would benefit from stronger typing.  Prefer duration types over int.

        for (int i = 0; i < n; i++)
        {
            std::cout << "Enter Burst time for process " << i+1 << " : ";
            int val;
            std::cin >> val;
            burst_time.push_back(val);
        }

Compiling with warnings would have caught the signed/unsigned comparison mismatch.

You should check to see if reading from std::cin was successful.

    Scheduling(const Scheduling &other)
    {
        process = other.process;
        int size = other.burst_time.size();

        for (int i = 0; i < size; i++)
        {
            burst_time.push_back(other.burst_time[i]);
        }
    }

When you need to initialize a member variable with a non-constant value in a constructor, prefer initialization instead of assignment.

    Scheduling(const Scheduling &other)
    : process{other.process}
    , burst_time{other.burst_time}
    , waiting_time{other.waiting_time}
    {}

Since each member variable has a well-defined copy behavior, we can use the compiler-generated copy constructor.

    Scheduling(const Scheduling &) = default;

    Scheduling &operator=(const Scheduling &other)
    {
        process = other.process;
        int size = other.burst_time.size();

        for (int i = 0; i < size; i++)
        {
            burst_time.push_back(other.burst_time[i]);
        }

        return *this;
    }

Use const to define objects with values that do not change after it has been constructed.

        const int size = other.burst_time.size();

Your copy assignment is actually a copy append.  You forgot to clear the existing list before copying.

Obey the rule of five/zero.  In C++, there are six special member functions.  Ignoring the default constructor, the rules cover the following member functions:

Destructor
Copy Constructor
Move Constructor
Copy Assignment Operator
Move Assignment Operator

The rule of five is simple.  If you define, =default, or =delete any of these five special member functions, you should consider how the other special member functions operate in the class.

The rule of five defaults goes a step further.  If you define, =default, or =delete any of the five special member functions, then explicitly define, =default, or =delete them all.

    class Scheduling {
        ...
      public:
        Scheduling() = default;
        Scheduling(int);

        ~Scheduling() = default;
        Scheduling(Scheduling const&) { ... }
        Scheduling(Scheduling &&) = default;
        Scheduling& operator=(Scheduling const&) { ... }
        Scheduling& operator=(Scheduling &&) = default;

        void print_table() { ... }
        std::vector<int> cal_waiting_time(std::vector<int>) { ... }
    };

The rule of zero is just as simple.  If you can avoid defining all of the special members, then do so.  As it turns out, the compiler generated behavior of the copy, move, and destruct operations are well-defined for your member variables and consistent in their use. You do not need to define these operations yourself.

    class Scheduling {
        ...
      public:
        Scheduling() = default;
        Scheduling(int) { ... };

        void print_table() const { ... }
        std::vector<int> cal_waiting_time(std::vector<int>) { ... }
    };

    std::vector<int> cal_waiting_time(std::vector<int>& burst_time)
    {
        waiting_time.push_back(0);

        for (int i = 0; i < burst_time.size() - 1; i++)
        {
            waiting_time.push_back(waiting_time[i] + burst_time[i]);
        }
        return waiting_time;
    }

Know your algorithms.  See std::partial_sum.

On multiple calls, the new results do not overwrite the old results.  Instead, the new results are appended to the old results.

Did you intend for this function to be a part of the public api for this class?  Have you considered returning a cached waiting_time rather than recalculating the partial sum on each call?

    void print_table()
    {
        waiting_time = cal_waiting_time(burst_time);
        std::cout << "Process\t Burst Time\t Waiting Time\n";
        for (int i = 0; i < burst_time.size(); i++)
        {
            std::cout << i+1 << "\t\t " << burst_time[i] << "\t\t " << waiting_time[i] << "\n";
        }
    }

This function isn't being truthful in what it does.  It recalculates the waiting_time on every call which means its doing more than "print".  Consider an alternative design, such as calculating the partial sum on construction.


Karatsuba Algorithm in Python I implemented a Karatsuba algorithm in Python but it doesn't give me the exact answer.

def karatsuba(x, y):
    if x < 10 or y < 10:
        return x*y

    #making the two numbers strings here
    str_x = str(x)
    str_y = str(y)

    #finding the mid point for each number here
    n = max(len(str(x)), len(str(y)))
    n_2 = int(n / 2)

    #higher bits of each number
    x_h = int(str_x[:n_2])
    y_h = int(str_y[:n_2])

    #lower bits for each number here
    x_l = int(str_x[n_2:])
    y_l = int(str_y[n_2:])

    a = karatsuba(x_h, y_h)
    d = karatsuba(x_l, y_l)
    e = karatsuba(x_h + x_l, y_h + y_l) - a - d

    return a*10**len(str_x) + e*10**(len(str_x) // 2) + d

result = karatsuba(1234, 8765)
print(result)

I think its because I am taking integer values and ignore decimals of floating point values.

When I run the above program my answer is 10,402,010 whereas the actual answer is 10,816,010

How can I improve this?

Errors in the code:

When you split str_x[:n_2] and str_y[:n_2] you're taking the same number of digits from the most significant part of each number. You need to instead take the same number of digits from the least significant part of each number.

For example, the cross multiplication step of karatsuba(12 + 34, 87 + 65) goes wrong:

You get x = 46 and y = 152 so n_2 = 1 and str_x[:n_2] = '4' and str_y[:n_2] = '1'. These are not offset by the same amount!

Instead you could set

#higher bits of each number
x_h = int(str_x[:-n_2])
y_h = int(str_y[:-n_2])

#lower bits for each number here
x_l = int(str_x[-n_2:])
y_l = int(str_y[-n_2:])

Negative indices count from the end, and this is just what you want so that you pull out the same number of powers of ten from each. Then str_x[:-n_2] = str_x[:-1] = all but the last n_2 = 1 digit of x which is 4, and str_y[:-n_2] = str_x[:-1] = all but the last n_2 = 1 digit of x which is 15. This works the way it should

With or without the above fix, your code will crash when both numbers > 10 and one of them is twice (or more) as many digits as the other. Then one of the slices will be the empty string, and int('') throws an error as opposed to (as you would want) returning 0.

A quick fix to this would be to make the higher part and lower part each a function, and check for the empty string. Alternatively, you could have a special case in karatsuba when n_2 >= min(...)

Finally, there's a bug in the return computation. Instead of len(str_x) you want 2 * n_2 and instead of len(str_x) // 2 you want n_2.

Some quick comments on issues other than the errors

Using str(x) is not very efficient, and does a lot of extra work in what is supposed to be an implementation of an efficient way to multiply. For getting the basic ideas of the algorithm down, though, it's fine for a start and I won't complain too much.

But you should at least be aware that a better way would be to split the number into two pieces in base 2 and use bit string operations. This would be a good follow-up exercise. Specifically x >> n is the same as x // 2**n and x << n is the same as x * 2**n and these are much more efficient than base 10 operations.


Bisection Method Implementation I'm working on a program to program the bisection method:
https://www.calculushowto.com/bisection-method/
I know there's questions similar to this one but I want to see if my own one works.
double func(double x) {
    return x * x - 3 * x - 1;
}

double bisect(double (*f)(double), double a, double b, double e) {
    double mid = (a + b) / 2;
    while (abs(mid) > e) {
        if (f(mid) < 0) {
            mid = a;
        } else {
            mid = b;
        }
    }

    return mid;
}

func() is the function I'm using to test the bisection method. In the other function, a is the left point, b is the right point and e is the error bound.
Any mistakes that I didn't catch?

You seem to assume that there is a root between a and b. If it is not the case, bisect will never terminate. Assuming that f is well-behaving, it would be prudent to test that f(a) and f(b) have different signs before proceeding.
Also, consider the case f(a) > 0 && f(b) < 0

bisect doesn't find the approximation of the root. It finds an argument at which f is reasonably small. It could be quite far from the root. A prudent termination condition is b - a < e.

a + b may overflow, and then all bets are off. Consider mid = a + (b - a)/2.


Represent integer as binary in C To practice my C, I've written a small function in C to display an integer as an 8-bit binary number. Please let me know how to improve this function, and other C-style coding conventions. Thanks!
/**
 * Converts an integer to binary.
 *
 * @param num Integer to convert.
 *
 * @return c-string.
**/
const char* to_binary(int num) {

    static char binary[10];
    binary[0] = '0';
    binary[1] = 'b';

    int value = 128;
    int number = num;

    for (int i = 2; i < 10; i++) {
        if (number - value >= 0) {
            binary[i] = '1';
            number = number - value;
        } else {
            binary[i] = '0';
        }
        value = value / 2;
    }

    return binary;

}

And here's how you call it:
int main() {

    const char* result = to_binary(146);

    printf("%s\n", result);

}

More specific types are available for an eight bit number, such as uint8_t
static keyword is dangerous (when used as an output buffer) and results in weird behaviour if your method is called twice
The arithmetic can be replaced with a more simple & (bitwise AND)

void to_binary(uint8_t x, char *output) {
    *output++ = '0';
    *output++ = 'b';
    for (int mask = 1<<CHAR_BIT-1; mask!=0 ; mask>>=1) {
        *output++ = x & mask ? '1':'0';
    }
    *output = 0; // null terminate the string
}


F# Array with tuples or Map I have a sample code and some question.

Simple type property

member val CabinetNetworkState : uint8 = 0uy with get, set
member this.CabinetNetworkStateAsValues : (CabinetNetworkStateHosts * uint8) array =
        let cabinetNetworkStateMap = new ResizeArray<(CabinetNetworkStateHosts * uint8)> ()

        let extNetworkState = (this.CabinetNetworkState >>> 0) &&& uint8 2
        match Enum.IsDefined(typeof<CabinetNetworkState>, extNetworkState) with
        | true ->  cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.EXT, extNetworkState)
        | false -> cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.EXT, 0uy)

        let canNetworkState = (this.CabinetNetworkState >>> 3) &&& uint8 2
        match Enum.IsDefined(typeof<CabinetNetworkState>, canNetworkState) with
        | true ->  cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, canNetworkState)
        | false -> cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, 0uy)

        let net1NetworkState = (this.CabinetNetworkState >>> 5) &&& uint8 2
        match Enum.IsDefined(typeof<CabinetNetworkState>, net1NetworkState) with
        | true ->  cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.NET1, net1NetworkState)
        | false -> cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.NET1, 0uy)

        let net2NetworkState = (this.CabinetNetworkState >>> 7) &&& uint8 2
        match Enum.IsDefined(typeof<CabinetNetworkState>, net2NetworkState) with
        | true ->  cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, net2NetworkState)
        | false -> cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, 0uy)

        cabinetNetworkStateMap.ToArray()

What it does it converts a value into array of bit value and enum that value represents
My question is should I use Map instead of tuple array, or it does not matter?

A Map would have a roughly constant time lookup on keys but if there only going to be 4 entries then checking each item in an array will probably be quicker anyway.

I think a much bigger issue is the repetition in the code and use of a ResizeArray to write in an imperative style when that can be easily avoided. Both of those issues are covered in this refactor (note that the names I used are quite arbitrary and you can probably come up with better ones):

member this.CabinetNetworkStateAsValues : (CabinetNetworkStateHosts * uint8) array =
    let makeStatePair state stateType =
        let networkState = (this.CabinetNetworkState >>> state) &&& 2uy
        if Enum.IsDefined(typeof<CabinetNetworkState>, networkState)
        then stateType, networkState
        else stateType, 0uy
    [|
        makeStatePair 0 CabinetNetworkStateHosts.EXT
        makeStatePair 3 CabinetNetworkStateHosts.CAN
        makeStatePair 5 CabinetNetworkStateHosts.NET1
        makeStatePair 7 CabinetNetworkStateHosts.CAN
    |]


Project Euler Problem 37 in Python Project Euler Problem 37 asks:

  The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

  Find the sum of the only eleven primes that are both truncatable from left to right and right to left.

  NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

My approach can generate first 8 numbers "fairly" quickly and it relies on pregenerated list of primes created using sieve of eratosthenes. I've tried with active prime generation but it was slower, any way to optimize this code ?

from algorithms import *

primes = [i for i in gen_primes(10000000)]

def is_truncatable_right(n):
    a = True
    if n > 10:
        for x in range(len(str(n))):
            if int(n) not in primes:
                a = False
            n = str(n)[:-1]
        return a
    else:
        return False

def is_truncatable_left(n):
    a = True
    if n > 10:
        for x in range(len(str(n))):
            if int(n) not in primes:
                a = False
            n = str(n)[1:]
        return a
    else:
        return False

def main():
    n = []
    a = 11
    while len(n) != 11:
        if is_truncatable_left(a) and is_truncatable_right(a):
            n.append(a)
        a += 1
    return n, sum(n)

print(main())

Use the right data structure for the job. If you have

            if int(n) not in primes:

called more than a small constant number of times then primes should not be a list. If you change

primes = [i for i in gen_primes(10000000)]

to

primes = set(i for i in gen_primes(10000000))

you will see a significant speedup.

The algorithm could also be improved. I don't want to go into too much detail here because that's not in keeping with the ethos of Project Euler, but I think I can give you a couple of hints:

The problem statement says that there are only eleven primes matching the criterion. What property of primes with the criterion allowed them to prove that? How can you apply that property to generate them faster?

   If you have found all of the truncatable primes of length n, do you need to loop over all truncations of a candidate number of length n+1?


Revealing and hiding a playlist Is there a better way of writing this? I feel like there's a lot of lines for such a small thing.  Can it be optimized?

$j('#hideShowBtn').toggle(function() {
     $j('.playlist-bar-tray').slideUp();
     $j(this).attr("title","Show Playlist");
     $j(this).children("div").html('Show Playlist');
     $j(this).children("span").html('&#9660;');
 }, function() {
     $j('.playlist-bar-tray').slideDown();
     $j(this).attr("title","Hide Playlist");
     $j(this).children("div").html('Hide Playlist');
     $j(this).children("span").html('&#9650;');
});

How about "cheating" a bit by creating two copies of those elements whose values should change and then just alternate between which element to show. Something like this:

    &#9660; Show playlist

    &#9650; Hide playlist

And then somewhere in your JavaScript you call the .toggle() function from the jQuery UI:

$(".toggleable").toggle();

Now it would look as though the texts changed, while actually you are hiding one element and displaying another.


Simulation of interacting particles I'm simulating a system of particles which interact with each other and move and rotate due to the interaction.  There are 2000 particles in total but each particle interacts with other particles and their image (I'm using a periodic boundary condition) if particles and their images have distances larger thanl0. I just consider image of particles in 8 near boxes to the main box.

y[N],x[N] are the position of points in the plane; dx[n] and dy[N] their changes in each time step. c shows different time steps. e_x and e_y shows x and y component of direction of each particle respect to x and y-axis.

int main()
{
  unsigned short int N, l0 , R0;
  double rho, v0, eta, dt, a, b, D;
  long c_equilib, c_prod, c_display;
     while (c < 1000000)
            {
         c++;
        for(unsigned short int i=0; i<2000; i++){
          double S_theta=0.0, S_x=0.0, S_y=0.0, S;
                    for(unsigned short int j=0; j<2000; j++)
                    {
                        if (j==i) continue;
                        for(int ky=-1; ky<=1; ky++)
                        {
                            for(int kx=-1; kx<=1; kx++)
                            {
                                double r_x_ij=x[i]-(x[j]+kx*L),
                                    r_y_ij=y[i]-(y[j]+ky*L),
                                r_ij=sqrt(pow(r_x_ij,2.0)+pow(r_y_ij,2.0));
                                if (r_ij >= l0)
                                {
                                    r_x_ij/=r_ij;
                                    r_y_ij/=r_ij;
                                    S_theta += (e_x[i]*e_x[j]+e_y[i]*e_y[j]) / pow(r_ij, 3) * ( 3.0* (r_x_ij*e_x[j]+r_y_ij*e_y[j]) *
                                                            pow(e_x[i]*r_y_ij - e_y[i]*r_x_ij, 2.0) -
                                                            e_x[i]*e_y[j] + e_y[i]*e_x[j] );

                                    S = ( 3.0* pow(r_x_ij*e_x[j]+r_y_ij*e_y[j], 2.0) -1.0 ) / pow(r_ij, 2.0);
                                    S_x += r_x_ij*S;
                                    S_y += r_y_ij*S;
                                }
                            }
                        }
                    }
        }
dx[i] += dt*a*S_x;
            dy[i] += dt*a*S_y;
        }
e_x[i]=cos(theta[i]);
e_y[i]=sin(theta[i]);
x[i]+=dx[i];
y[i]+=dy[i];
}
}

I'm looking to optimize the large loop of this C++ program.  This is one part of my simulation (I have ignored some calculations inside the loop to make the question simpler). This part is extremely time-consuming. How can I make it faster?

I don't know how fast you expect this to run, but you need to understand that the inner part of your nested loop runs 36 trillion (1000000 * 2000 * 2000 * 3 * 3) times. This means that small changes in the run time of the inner loop will have a large impact on the total run time of the code, turning 1 hour of runtime to years.

Without knowing anything about the domain of your simulation, I can only propose this:

Reduce the number of times the loops run
Parallelize the code, so that you can have multiple threads working on  different parts concurrently.
Optimize the inner loop as much as possible. Perhaps there is some approximation of the calculation you're running that's significantly faster? Is there any way that you can make better use of processor caches or avoid branch mispredictions? Have a look at this latency chart.


Hackerrank: Breaking the records I'm learning Clojure and am a rank n00b at it, trying to learn from books and online tutorials (but I'm sometimes concerned that I am picking up bad habits or at least not all the good habits). For exercise I did the Breaking the Records problem on Hackerrank.
TL;DR problem description:
For a list of scores (in historic order), count the number of times the previous best score was exceeded as well as the previous worst score was undercut.
In an iterative language it is quite easy to just iterate through the list; but Clojure does not do iteration and I decided to tackle this problem for exercise in constructing a (tail end) recursive solution. To make it easier for myself, I first did a recursive solution in Java, which I then translated. All in all, it's quite a simple recursive function without rocket surgery involved.
Obviously my code works, as shown by the included unit tests. My concerns are however as follows:

When put next to the Java code, the two look fairly similar. Did I follow "idiomatic" Clojure programming, or is it just a clumsy "word-for-word transliteration"?
Are there any areas that could have been more compact and/or easier to understand by using different Clojure constructs?

Your critical input will be highly appreciated - including regarding the unit testing, as that is arguably an important part of programming, which I want to learn and practice in parallel.
Code:
(ns hackerrank.breaking-records
  (:require [clojure.test :refer :all]))

(defrecord Record [min max countworse countbetter])

(defn recalc-record [rec newscore]
  (Record.
    (min newscore (:min rec))
    (max newscore (:max rec))
    (+ (:countworse rec) (if (> (:min rec) newscore) 1  0))
    (+ (:countbetter rec) (if (< (:max rec) newscore) 1  0))))

(defn accumulate [curr-record remaining-scores]
  (if (nil? (second remaining-scores))
    curr-record
    (recur (recalc-record curr-record (second remaining-scores)) (rest remaining-scores)))
)

(defn breaking-records [scores]
  (let [result (accumulate (Record. (first scores) (first scores) 0 0) scores)]
    (list (:countbetter result) (:countworse result))))

(deftest test-records
  (testing "edge cases"
    (is (= '(0 0) (breaking-records '())) "no games played yet")
    (is (= '(0 0) (breaking-records '(5))) "single game"))
  (testing "hackerrank examples"
    (is (= '(2 4) (breaking-records '(10 5 20 20 4 5 2 25 1))))
    (is (= '(4 0) (breaking-records '(3 4 21 36 10 28 35 5 24 42)))))
)

I re-wrote your solution to use more typical Clojure features.  When you are looping over data and need to keep track of accumulated state, it is hard to beat loop/recur.  A first example:
(ns tst.demo.core
  (:use clojure.test))

(defn breaking-records
  [scores]
  ; this loop has 5 variables. Init all of them
  (loop [low         (first scores)
         high        (first scores)
         nworse      0
         nbetter     0
         score-pairs (partition 2 1 scores)]
    (if (empty? score-pairs)
      {:nbetter nbetter :nworse nworse}
      (let [curr-score-pair (first score-pairs)
            new-score       (second curr-score-pair)]
        ; start the next iteration with modified versions of the 5 loop vars
        (recur
          (min new-score low)
          (max new-score high)
          (if (< new-score low)
            (inc nworse)
            nworse)
          (if (< high new-score)
            (inc nbetter)
            nbetter)
          (rest score-pairs))))))

and unit tests:
(deftest test-records
  (testing "edge cases"
    (is (= (breaking-records []) {:nbetter 0 :nworse 0}) "no games played yet")
    (is (= (breaking-records [5]) {:nbetter 0 :nworse 0}) "single game"))
  (testing "hackerrank examples"
    (is (= (breaking-records [10 5 20 20 4 5 2 25 1]) {:nbetter 2 :nworse 4}))
    (is (= (breaking-records [3 4 21 36 10 28 35 5 24 42]) {:nbetter 4 :nworse 0}))))

; ***** NOTE: it's much easier to use vectors like [1 2 3] instead of a quoted list `(1 2 3)

Please see this list of documentation, esp. the Clojure CheatSheet. Also, the template project as a whole shows how I like to structure things.  :)
The function that helps the most is partition.  See the docs.

Slight refactoring
You can simplify it a small amount and make it a bit more compact by using more specialized functions like reduce and cond->.  This version uses a map to hold state and reduce to perform the looping:
(defn breaking-records
  [scores]
  (let [state-init     {:low     (first scores)
                        :high    (first scores)
                        :nworse  0
                        :nbetter 0}
        accum-stats-fn (fn [state score-pair]
                         ; Use map destructuring to pull out the 4 state variables
                         (let [{:keys [low high nworse nbetter]} state
                               new-score (second score-pair)
                               state-new {:low     (min new-score low)
                                          :high    (max new-score high)
                                          :nworse  (cond-> nworse
                                                     (< new-score low) (inc))
                                          :nbetter (cond-> nbetter
                                                     (< high new-score) (inc))}]
                           state-new))
        state-final    (reduce accum-stats-fn
                         state-init
                         (partition 2 1 scores))
        result         (select-keys state-final [:nworse :nbetter])]
    result))


Reading a configuration file I have written the following C code to parse a configuration file for settings to my program. I denote comments with a # and blank lines are allowed. e.g.:

# Total bytes per line
TBPL 70

# bar minimum
NUMIN 10.
# bar maximum
NUMAX 30000.

# input filename
LLIST_NAME foo.txt

Is there anything badly wrong here? I'm used to Python so finding this a bit of a chore...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_CONFIG_VARIABLE_LEN 20
#define CONFIG_LINE_BUFFER_SIZE 100
#define MAX_LLIST_NAME_LEN 256
#define MAX_OUT_NAME_LEN 256

struct config_struct {
    int bytes_per_line;
    char llist_name[MAX_LLIST_NAME_LEN];
    double numin, numax;
} config;

int read_int_from_config_line(char* config_line) {
    char prm_name[MAX_CONFIG_VARIABLE_LEN];
    int val;
    sscanf(config_line, "%s %d\n", prm_name, &val);
    return val;
}
void read_double_from_config_line(char* config_line, double* val) {
    char prm_name[MAX_CONFIG_VARIABLE_LEN];
    sscanf(config_line, "%s %lf\n", prm_name, val);
}
void read_str_from_config_line(char* config_line, char* val) {
    char prm_name[MAX_CONFIG_VARIABLE_LEN];
    sscanf(config_line, "%s %s\n", prm_name, val);
}

void read_config_file(char* config_filename, struct config_struct config) {
    FILE *fp;
    char buf[CONFIG_LINE_BUFFER_SIZE];

    if ((fp=fopen(config_filename, "r")) == NULL) {
        fprintf(stderr, "Failed to open config file %s", config_filename);
        exit(EXIT_FAILURE);
    }
    while(! feof(fp)) {
        fgets(buf, CONFIG_LINE_BUFFER_SIZE, fp);
        if (buf[0] == '#' || strlen(buf) < 4) {
            continue;
        }
        if (strstr(buf, "TBPL ")) {
            config.bytes_per_line = read_int_from_config_line(buf);
        }
        if (strstr(buf, "NUMIN ")) {
            read_double_from_config_line(buf, &config.numin);
        }
        if (strstr(buf, "NUMAX ")) {
            read_double_from_config_line(buf, &config.numax);
        }
        if (strstr(buf, "LLIST_NAME ")) {
            read_str_from_config_line(buf, config.llist_name);
        }
    }
    printf("TBPL = %d\n", config.bytes_per_line);
    printf("NUMIN = %f\nNUMAX = %f\n", config.numin, config.numax);
    printf("LLIST_NAME = %s\n", config.llist_name);
}

int main(int argc, char *argv[]) {
    read_config_file(argv[1], config);
    return EXIT_SUCCESS;
}

Your parser will of course only be able to handle very specific input. For example leading whitespace in front of # or passing garbage values as numbers in your config file.

If you want to improve this, I would first start by not ignoring the return value of sscanf.It will return the number of items it could successfully parse. This could also be used to generate useful error messages.

The file that you are opening should be closed with

fclose(fp).

Your read_*_from_config_line methods have a potential buffer overflow issue when the variable length is longer than MAX_CONFIG_VARIABLE_LEN. In this case you can just increase the buffer size, as you know that the strings are not longer than CONFIG_LINE_BUFFER_SIZE but generally you should try to avoid using sscanf and the likes.


Comparing two vectors of arbitrary size, block by block I am trying to compare two vectors which are of size of multiple of 4. Each vector block has a unique number it e.g {0,0,0,0}, {0,0,0,1}, {0,0,0,2} or {0,0,0,0,0,0,0,1,0,0,0,2} and {0,0,0,2,0,0,0,1} so on. I first divide the vector in block of 4 and than compare it and save the block which is not present in another vector into a global vector. I wrote a small function which do the job but often shows segmentation error.

void comparing_vectors_by_block(std::vector<int> vector_A, std::vector<int>
vector_B)
{
int blockSize = 4;
std::vector<int>::iterator start_of_A = vector_A.begin();
std::vector<int>::iterator start_of_B = vector_B.begin();

std::vector<int> subList_A;
std::vector<int> subList_B;
std::cout << "size of the vector_A: " << vector_A.size() << std::endl;
std::cout << "size of the vector_B: " << vector_B.size() << std::endl;
for (auto i = 0; i < vector_A.size() / blockSize; i++)
{
    subList_A.assign(start_of_A, start_of_A + blockSize);
    for (auto i = 0; i < vector_B.size() / blockSize; i++)
    {
        subList_B.assign(start_of_B, start_of_B + blockSize);
        if (subList_A != subList_B)
        {

            hold_result.insert(hold_result.begin(), start_of_B, start_of_B + blockSize);
            start_of_B += blockSize;
        }
        else
        {
            start_of_B += blockSize;
            std::cout << "both vectors are not equal: " << std::endl;
        }
    }
    start_of_A += blockSize;
}

If at all possible, I'd start from a slightly different direction. I'd start by defining the group of 4 ints as a type:

static const int blocksize = 4;

class block {
    std::array<int, blocksize> data;

    bool operator<(block const &other) {
        for (int i=0; i<blocksize; i++)
            if (data[i] < other.data[i])
                return true;
            if (other.data[i] < data[i])
                return false;
        }
        return false;
    }
};

Having done that, you can use a standard algorithm to get the desired result:

std::vector<block> find_diff(std::vector<block> a, std::vector<block> b) {
    std::vector<block> difference; // where we'll put the result

    // set operations require sorted inputs
    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());

    std::set_difference(a.begin(), a.end(),
                        b.begin(), b.end(),
                        std::back_inserter(difference));
    return difference;
}


Random game code id generator in typescript Below is a simple typescript class used to generate a room code for an online lobby-based game (for example, https://jackbox.tv/ uses 4 digit codes to join rooms)
The goal of the class is to quickly generate unique 4-letter codes for game lobbies, and release them after the lobby is closed. Typically, less than 100 lobby codes will be used at once so using up all 26^4 codes will likely never happen.
Concerns:

Is the method for generating codes efficient? Currently it just picks a random code and keeps incrementing until an unused code is found
Is the method for encoding a number to an alphabet efficient? (converting a number to base 26)

const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

function randInt(min: number, max: number) {
  return Math.floor(Math.random() * (max - min)) + min;
}

export class RoomCodeManager {
  codeLength: number;
  usedCodes: Set<string>;
  // Generate 4-letter codes by default
  constructor(codeLength = 4) {
    this.codeLength = codeLength;
    this.usedCodes = new Set();
  }
  generateCode() {
    const min = 0;
    const max = Math.pow(ALPHABET.length, this.codeLength);
    let code = randInt(min, max);

    // If every code is already in use, just return a random code
    if (this.usedCodes.size >= max) {
      return this.encodeAlphabet(code);
    }

    // Keep incrementing by 1 until an unused code is found
    while (this.usedCodes.has(this.encodeAlphabet(code))) {
      code = (code + 1) % max;
    }
    this.usedCodes.add(this.encodeAlphabet(code));
    return this.encodeAlphabet(code);
  }
  encodeAlphabet(num: number) {
    let str = "";
    const len = ALPHABET.length;
    while (num > 0) {
      let radix = num % len;
      str = ALPHABET[radix] + str;
      num = Math.floor(num / len);
    }
    return str.padStart(this.codeLength, ALPHABET[0]);
  }
  releaseCode(code: string) {
    this.usedCodes.delete(code);
  }
}

One important consideration: should those who do not have the code for a room be able to guess it (or guess a random code) and enter a room they were never told the code for? If not, then 4 characters probably isn't quite enough:

If guesses and codes were random, the chance of guessing a lobby is on the order of magnitude of 100/450_000. Chances are low, but they're not astronomically low. To make it better, increase the number of characters in a code.
But long random character strings are difficult to remember. If you think that might be a problem for the UI, consider using random words instead - for example, have a dictionary of a large number of English words, and then to generate a code, put two or three of them together.

Is the method for generating codes efficient? Currently it just picks a random code and keeps incrementing until an unused code is found

If you really expect there to be less than 100 codes in use at a given time, then the chances of a collision are extremely low, so simply re-picking a random number in such rare cases sounds perfectly fine to me. If the app became more popular and collisions started happening on a regular basis, then it might be time to consider a different approach (such as hashing incremental numbers, or increasing the number of characters, or using a different algorithm entirely).

Is the method for encoding a number to an alphabet efficient? (converting a number to base 26)

When turning a number into a string, I'd prefer to use toString if possible. For example, if you're able to use numbers 0-9 in addition to letters, you could make encodeAlphabet much simpler and use:
  encodeAlphabet(num) {
    return num.toString(36);
  }

(though, for such an approach to be user-friendly, you might also want to remove all characters that might get confused with each other, like O and 0)
Another approach to consider - rather than generating a number and then turning it into a string, how about generating random characters and putting those into a string instead? No need to work with modulo and radix:
generateCode() {
  let code;
  do {
    code = this.getRandomCode();
  } while (this.usedCodes.has(code));
  this.usedCodes.add(code);
  return code;
}
getRandomCode() {
  return Array.from(
    { length: this.codeLength },
    () => String.fromCharCode(Math.floor(Math.random() * 26) + 65)
  ).join('');
}

const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

function randInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

class RoomCodeManager {
  // Generate 4-letter codes by default
  constructor(codeLength = 4) {
    this.codeLength = codeLength;
    this.usedCodes = new Set();
  }
  generateCode() {
    let code;
    do {
      code = this.getRandomCode();
    } while (this.usedCodes.has(code));
    this.usedCodes.add(code);
    return code;
  }
  getRandomCode() {
    return Array.from(
      { length: this.codeLength },
      () => String.fromCharCode(Math.floor(Math.random() * 26) + 65)
    ).join('');
  }
  releaseCode(code) {
    this.usedCodes.delete(code);
  }
}

const roomCodeManager = new RoomCodeManager();
console.log(roomCodeManager.generateCode());

Regarding
// If every code is already in use, just return a random code
if (this.usedCodes.size >= max) {
  return this.encodeAlphabet(code);
}

Maybe, in such a case, increment this.codeLength instead of returning a duplicate? (Though, this'll probably never happen)


Simple string joiner in modern C++ (See the next iteration.)

I have this small template function for convenient dumping a sequence into a string such that there is a delimeter between two consecutive elements, and no such after the last element:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::for_each;
using std::vector;

template<typename T>
std::string join(const T begin,
                 const T end,
                 std::string separator,
                 std::string concluder)
{
    const auto length = std::distance(begin, end);
    std::stringstream ss;
    size_t count = 0;

    for (T iter = begin; iter != end; ++iter, ++count)
    {
        ss << *iter;

        if (count < length - 1)
        {
            ss << separator;
        }
    }

    ss << concluder;
    return ss.str();
}

template<typename T>
std::string join(T begin, T end, std::string separator)
{
    return join(begin, end, separator, "");
}

template<typename T>
std::string join(T begin, T end)
{
    return join(begin, end, ", ");
}

int main() {
    vector<vector<int>> matrix = {
        { 1, 2, 3 },
        { 4, 5 },
        { },
        { 10, 26, 29 }
    };

    for_each(matrix.cbegin(),
             matrix.cend(),
             [](std::vector<int> a) {
                 cout << join(a.cbegin(), a.cend()) << endl;
             });
}

Any idea how to improve this?

Your code is fine, except for three small quirks

You don't need overloads if you provide default arguments
You don't need constant Ts
You don't need to check the length of your collection (except for begin == end).

template<typename InputIt>
std::string join(InputIt begin,
                 InputIt end,
                 const std::string & separator =", ",  // see 1.
                 const std::string & concluder ="")    // see 1.
{
    std::ostringstream ss;

    if(begin != end)
    {
        ss << *begin++; // see 3.
    }

    while(begin != end) // see 3.
    {
        ss << separator;
        ss << *begin++;
    }

    ss << concluder;
    return ss.str();
}

You only need to check whether you have an empty range. If you don't, you start with the first one, and then stream the separator before the next element:

(0 elements case) <concluder>
(1 element  case) <element> <concluder>
(2 elements case) <element> <separator> <element> <concluder>
(3 elements case) <element> <separator> <element> <separator> <element> <concluder>

As you can see, except for the first element, you will always get <separator> <element> for any other element. This adds a little bit more logic to the empty case, but you don't need to traverse your range twice, and this method makes your algorithm eligible for input iterators.

Other than that, the only other thing I would change is to use an ostringstream instead of an stringstream. This prevents you from accidentally using >>. And global using std::*** isn't my cup of tee either. You can, however, move that into your main.

But here's a little exercise: you can just use an <iterator>:

template<typename InputIt>
std::string join(InputIt begin,
                 InputIt end,
                 const std::string & separator =", ",  // see 1.
                 const std::string & concluder ="")    // see 1.
{
    std::ostringstream ss;

    using value_type = typename std::iterator_traits<InputIt>::value_type;

    std::copy(begin, end, std::ostream_iterator<value_type>(ss, separator.c_str()));

    ss << concluder;
    return ss.str();
}

However, as you've noted, it does not yield the same result as your variant. Here's the exercise, though: write an iterator that provides your behavior.


Grouping models without dictionary I want to group an array of structs only using arrays into an array of new structs. In this example I want to group the Person structs by Job and put them in new Department structs and put them in an array.

enum Job {
    case developer
    case programmer
    case coder
}

struct Person {
    let id: Int
    let job: Job
}

struct Department {
    let job: Job
    var staff: [Person]

    mutating func addStaff(_ person: Person) {
        staff.append(person)
    }
}

let initial = [
    Person(id: 0, job: .developer),
    Person(id: 1, job: .developer),
    Person(id: 2, job: .programmer),
    Person(id: 3, job: .programmer),
    Person(id: 4, job: .coder)
]

func combinator(accumulator: [Department], current: Person) -> [Department] {
    var accumulator = accumulator

    if let index = accumulator.index(where: { $0.job == current.job }) {

        var department = accumulator[index]
        department.staff.append(current)
        accumulator[index] = department
    } else {
        accumulator.append(Department(job: current.job, staff: [current]))
    }

    return accumulator
}

var departments: [Department] = initial.reduce([], combinator)

I feel like the if statement in the combinator(accumulator:current:) function is a bit clunky, is there a better way to write that part or any other part of this piece of code?

Swift 4

i would use the new swift 4 init(grouping:by:)

since you create always new Departments then the following code is possible.

if you have an existing [Department] then the code not fit your request.

enum Job {
    case developer
    case programmer
    case coder
}

struct Person {
    let id: Int
    let job: Job
}

struct Department {
    let job: Job
    var staff: [Person]

    mutating func addStaff(_ person: Person) {
        staff.append(person)
    }
}

let initial = [
    Person(id: 0, job: .developer),
    Person(id: 1, job: .developer),
    Person(id: 2, job: .programmer),
    Person(id: 3, job: .programmer),
    Person(id: 4, job: .coder)
]

let grouped = Dictionary(grouping: initial, by: { $0.job })
let departments = grouped.map{ key, value in Department( job: key, staff: value )}

( NOTE: i don't tested it in playground - just from head to the answer)

Swift 3

in Swift 3 you can use an extension to the array to resolve this grouping

public extension Sequence {
    func group<U: Hashable>(by key: (Iterator.Element) -> U) -> [U:[Iterator.Element]] {
        var categories: [U: [Iterator.Element]] = [:]
        for element in self {
            let key = key(element)
            if case nil = categories[key]?.append(element) {
                categories[key] = [element]
            }
        }
        return categories
    }
}

the extension is from here https://stackoverflow.com/a/31220067/1930509 and when you need a more performat grouping you can find it at the link


Delete (Reverse Backspace) Button I have built a delete button in Android, just like in Windows, which removes the string on the right hand side of the cursor (one by one). (Instead of the mainstream Backspace which removes the left side.)

Tell me if you have any better ideas.

package com.example.app;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView.BufferType;
import android.widget.Toast;

public class MainActivity extends Activity {
    public Toast t, t1,t2;
    Editable a, b, d, f, a1;
    String e;
    public int c, d1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText ed;

        Button dlt;

        dlt = (Button) findViewById(R.id.button1);

        ed = (EditText) findViewById(R.id.editText1);
        ed.clearFocus();

        dlt.setOnClickListener(new OnClickListener() {
            @SuppressLint("NewApi")
            public void onClick(View v) {

                InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                boolean check = mgr.isActive(ed);
                if(check==true){

                    Toast.makeText(getApplicationContext(), "Welcome", t2.LENGTH_SHORT)
                    .show();
                }
                a = ed.getEditableText();

                b = a;
                c = ed.getSelectionStart();

                String a11 = b.toString().substring(c);
                Toast.makeText(getApplicationContext(), a11, t1.LENGTH_SHORT)
                        .show();
                String a22 = b.toString().substring(0, c);

                boolean daj = b.toString().isEmpty();
                if (a11 != null && !a11.trim().equals("")) {

                    int strChar = a11.length();
                    String strcut = a11.substring(1, strChar);
                    e = a22.concat(strcut);

                    ed.setText(e, BufferType.EDITABLE);
                    b = ed.getEditableText();
                    ed.setSelection(c);
                } else {
                    Toast.makeText(getApplicationContext(), "Cool",
                            t.LENGTH_SHORT).show();
                }

            }

        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Name your variables and fields meaningfully. I have no idea what a,b,e, etc are.
Don't split your variable declaration and initalization. Instead of

final EditText ed;

Button dlt;

dlt = (Button) findViewById(R.id.button1);

ed = (EditText) findViewById(R.id.editText1);

do

final EditText ed = (EditText) findViewById(R.id.editText1);
final Button dlt = (Button) findViewById(R.id.button1);

And be consistent with your final usage. Either use it everywhere where appropriate or don't. Otherwise I start to wonder why ed is final and dlt is not.
There a TextUtils.isEmpty() method available on Android. Use it instead of

a11 != null && !a11.trim().equals("")

Use static field access. Instead of t1.LENGTH_SHORT use Toast.LENGTH_SHORT. All the fields t,t1 and t2 are unnecessary.
All your fields should be local variables.


What is the most pythonic way to solve a differential equation using the Euler method? For example, with this differential equation, how can I do it in a pythonic way?

dx/dt=f(x,t)

I have a way to do it, but I think this is not the most pythonic way:

import numpy as np
dt=0.01
N_iter=10./dt
def f(x,t):
    return x**2*t#insert your favorite function here
x=np.zeros(N_iter)
for i in range(N_iter-1):
    x[i+1]=x[i]+dt*f(x[i],i*dt)

Using a for loop is not an unpythonic way at all. Instead, an Euler method could be implemented with a recursive function, but it not necessary and less optimized in Python.

However, methods for vectorizing recursive sequences are discussed on the numpy-discussion mailing-list. I encourage you to use structures like for loops in such situations. You will minimize the risk of errors by writing simple and concise codes.


Implementation of a property and a corresponding animated setter There a various examples in UIKit where a class has a property and a corresponding method to set the property along with an animated property.

Examples include the progress and setProgress(_:animated:) of UIProgressView or the isEditing and setEditing(_:animated:) of UITableView.

In Objective-C you implement this by overriding the plain property setter to call the additional setter with the additional parameter:

- (void)setEditing:(BOOL)editing {
    [self setEditing:editing animated:NO];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    _editing = editing // set the instance variable

    // The rest of the code
}

The question is about doing this in Swift. The best I can come up requires using a private backing variable for the public computed property in addition to the corresponding animated setter.

private var _editing: Bool

public var isEditing: Bool {
    get { return _editing }
    set { setEditing(newValue, animated: false) }
}

public func setEditing(_ editing: Bool, animated: Bool) {
    _editing = editing

    // The rest of the code
}

Is there a better way to implement this pattern in Swift without the need to wrap a private property with a computed property à la Objective-C?

The alternative is:

public var isEditing: Bool {
    didSet {
        // do whatever you need when the property changes, e.g.
        updateView()
    }
}

// wrap the changing of `isEditing` in some animation

func setEditing(_ editing: Bool, animated: Bool) {
    if animated {
        someAnimation {
            isEditing = editing
        }
    } else {
        isEditing = editing
    }
}

This basically separates the “do what I need when isEditing changes” from the “by the way, animate that” and it eliminates a private backing stored property.

There are cases where you need to do the “exposed computed property with a private backing stored property” approach, but I generally avoid that pattern where I can.


Writing out a tree of Tnodes with words as values in alphabetical order I'm doing this:

  Consider:

struct Tnode {
    string word;
    int count;
    Tnode* left;
    Tnode* right;
};

  Write a function for entering new words into a tree of Tnodes. Write a
  function to write out a tree of Tnodes. Write a function to write out
  a tree of Tnodes with the words in alphabetical order. Modify Tnode so
  that it stores (only) a pointer to an arbitrarily long word stored as
  an array of characters on free store using new. Modify the functions
  to use the new definition of Tnode.

Source

Here is my code for the first part ("write a function to write out a tree of Tnodes with the words in alphabetical order"). Please review this.

Note: I know I only have to write a function, but I'm interested in creating a class. Now I'm not sure if this is good code.

struct Tnode {
    std::string word;
    int count; //I'm not sure what's this for. I assume it's for counting nodes.
    Tnode* left;
    Tnode* right;
};

class TreeNode {
    Tnode* node;

    Tnode* add(Tnode* n, const std::string& word) {
        if (n == nullptr) {
            n = new Tnode{word};
        } else if (word < n->word) {
            n->left = add(n->left, word);
        } else if (word > n->word) {
            n->right = add(n->right, word);
        } else {
            n->word = word;
        }
        //I have to always check for nullptr because I found out dereferencing a nullptr causes undefined behavior. And I have to asign n->count back to 1 because I notice it keeps adding.
        n->count = 1;
        if (n->left != nullptr) {
            n->count += n->left->count;
        }
        if (n->right != nullptr) {
            n->count += n->right->count;
        }
        return n;
    }

    void traverse(Tnode* t) { //for testing purposes
        if (t == nullptr) {
            return;
        }
        std::cout << t->word << '\n';
        traverse(t->left);
        traverse(t->right);
    }

    void destroy_all(Tnode* t) { //I can't think of a better way to destroy all Tnode objects
        if (t == nullptr) {
            return;
        }
        destroy_all(t->left);
        destroy_all(t->right);
        delete t;
    }

public:
    TreeNode() { node = nullptr; } //Is doing this fine? I don't know what default value I would use aside from nullptr because I didn't write a subscripting function to access the nodes
    TreeNode(const std::string& word) :node{new Tnode{word}} { }

    void add(const std::string& word) {
        node = add(node,word);
    }

    void traverse() { //for testing purposes
        traverse(node);
    }

    int get_count() {
        return node->count;
    }

    ~TreeNode() {
        destroy_all(node);
    }

};

How can I make this code better?

Improvements / details:

Your naming is a bit odd. Tnode is not a very descriptive name. TreeNode seems out of context, as the type is actually the tree itself, not a node.

I suggest renaming TreeNode to just Tree and Tnode to TreeNode instead.

That count parameter seem to be the child count of a given node. It can be used to determine the height of the tree. It is not implemented properly for this purpose though.

I prefer placing private methods and data at the end of the class declaration. Public data and methods should appear at the top, as this is what users of the interface care about when reading the file. Also, it is better to separate the class in declaration and definition. The declaration usually goes in a header file (.h/.hpp).

Wouldn't be a bad idea renaming the recursive helper methods of the tree to make the use of recursion more explicit. You could append _recursive to the name. E.g.: traverse() => traverse_recursive().

Tnode should have a formal constructor to properly initialize its data.

Refactored code:

I took the liberty of applying these changes to your code. Following is the result:

// tree.h:

struct TreeNode {

    std::string word;
    int numChildren;

    TreeNode* left;
    TreeNode* right;

    TreeNode(const std::string& word)
        : word(word), numChildren(0), left(nullptr), right(nullptr) { }
};

class Tree {

public:

    Tree();
    Tree(const std::string& word);

    void add(const std::string& word);
    void traverse();
    int get_num_nodes() const;

    ~Tree();

private:

    TreeNode* add_recursive(TreeNode* n, const std::string& word);
    void traverse_recursive(TreeNode* n);
    void destroy_recursive(TreeNode* n);

    TreeNode * root;
};

// tree.cpp:

Tree::Tree()
    : root(nullptr) { }

Tree::Tree(const std::string& word)
    : root(new TreeNode(word)) { }

void Tree::add(const std::string& word) {
    root = add_recursive(root, word);
}

void Tree::traverse() {
    traverse_recursive(root);
}

int Tree::get_num_nodes() const {
    return root->numChildren + 1; // +1 to count the root as a node
}

Tree::~Tree() {
    destroy_recursive(root);
}

TreeNode* Tree::add_recursive(TreeNode* n, const std::string& word) {
    if (n == nullptr) {
        n = new TreeNode(word);
    } else if (word < n->word) {
        n->left = add_recursive(n->left, word);
        n->numChildren++;
    } else if (word > n->word) {
        n->right = add_recursive(n->right, word);
        n->numChildren++;
    } else {
        n->word = word;
    }

    return n;
}

void Tree::traverse_recursive(TreeNode* n) {
    if (n == nullptr) {
        return;
    }

    // Extended printing to visualize more info:
    std::cout << "Node => " << n->word << ", numChildren: " << n->numChildren;
    if (n->left != nullptr) {
        std::cout << ", left: "  << n->left->word;
    }
    if (n->right != nullptr) {
        std::cout << ", right: " << n->right->word;
    }
    std::cout << "\n";

    traverse_recursive(n->left);
    traverse_recursive(n->right);
}

void Tree::destroy_recursive(TreeNode* n) {
    if (n == nullptr) {
        return;
    }
    destroy_recursive(n->left);
    destroy_recursive(n->right);
    delete n;
}

// main.cpp:

int main()
{
    Tree tree;

    tree.add("hello");
    tree.add("C++  ");
    tree.add("world");
    tree.add("foo  ");
    tree.add("bar  ");
    tree.add("baz  ");

    tree.traverse();

    std::cout << "num nodes: " << tree.get_num_nodes() << std::end; // prints "num nodes: 6"
}


A beginner's first Tic Tac Toe implementation I've been teaching myself Python and decided to make a Tic Tac Toe game for a bit of practice. Any criticisms or pointers are welcome!
class TicTacToe:
  """A class for playing tic tac toe"""

  def __init__(self):
    self.values = ["-", "-", "-",
                  "-", "-", "-",
                  "-", "-", "-"]
    self.player = "x"

  def show_board(self):
    print(f"{self.values[0]} | {self.values[1]} | {self.values[2]}")
    print(f"{self.values[3]} | {self.values[4]} | {self.values[5]}")
    print(f"{self.values[6]} | {self.values[7]} | {self.values[8]}")

  def play_game(self):
    # display initial board
    self.show_board()
    # play for 9 turns max
    for i in range(9):
      self.handle_turn(self.values)
      if self.check_tie() or self.winner():
        break

  def handle_turn(self, values):
    # get next move from a player
    try:
      turn = int(input(f"Player {self.player} pick a square (1-9) from left to right: "))
    except ValueError:
      self.handle_turn(self.values)
      return

    # change values to show the move made (check square empty)
    if self.values[turn-1] == "x" or self.values[turn-1] == "o":
      print("That square has been played already!")
      self.handle_turn(self.values)
    else:
      self.values[turn-1] = self.player
      self.show_board()
    # switch turns
    self.flip_player()

  def winner(self):
    # check all possible win methods
    self.row_winner = self.check_rows()
    self.column_winner = self.check_columns()
    self.diagonal_winner = self.check_diagonals()
    #declare a winner
    if self.row_winner:
      winner = self.check_rows()
      print(f"{winner} has won the game!")
      return True
    elif self.column_winner:
      winner = self.check_columns()
      print(f"{winner} has won the game!")
      return True
    elif self.diagonal_winner:
      winner = self.check_diagonals()
      print(f"{winner} has won the game!")
      return True

  def check_rows(self):
    # Check for a win in the rows
    row1 = self.values[0] == self.values[1] == self.values[2] != "-"
    row2 = self.values[3] == self.values[4] == self.values[5] != "-"
    row3 = self.values[6] == self.values[7] == self.values[8] != "-"
    # Return the player that has won
    if row1:
      return self.values[0]
    elif row2:
      return self.values[3]
    elif row3:
      return self.values[6]

  def check_columns(self):
    # Check for a win in the columns
    col1 = self.values[0] == self.values[3] == self.values[6] != "-"
    col2 = self.values[1] == self.values[4] == self.values[7] != "-"
    col3 = self.values[2] == self.values[5] == self.values[8] != "-"
    # Return the winning player
    if col1:
      return self.values[0]
    elif col2:
      return self.values[1]
    elif col3:
      return self.values[2]

  def check_diagonals(self):
    # Check for win in the diagonals
    dia1 = self.values[0] == self.values[4] == self.values[8] != "-"
    dia2 = self.values[2] == self.values[4] == self.values[6] != "-"
    # Return the player that has won
    if dia1:
      return self.values[0]
    elif dia2:
      return self.values[2]

  def check_tie(self):
    if "-" not in self.values:
      print("Game is a tie!")
      return True
    else:
      return False

  def flip_player(self):
    if self.player == "x":
      self.player = "o"
    else:
      self.player = "x"

if __name__ == "__main__":
  new_board = TicTacToe()
  new_board.play_game()

Visuals
You can try
self.values = [["-" for _ in range(3)] for _ in range(3)]

This will let you set up a 3x3 grid without having to draw the whole thing.
Now you can also do
    def show_board(self):
        board_str = "\n".join([ " | ".join(row) for row in grid ])
        print(board_str)

I would also suggest doing away with the show_board function altogether and instead use (for printing)
    def __str__(self):
        return "\n".join([ " | ".join(row) for row in grid ])

and/or (for printing in interactive console)
    def __repr__(self):
        return "\n".join([ " | ".join(row) for row in grid ])

Then you can directly do
xoxo = TicTacToe
print(xoxo)

and inside the class
print(self)

Data Representation and Input
I'm repeating myself here, but it doesn't make sense to have values be a 1-dimensional array. It's a tic-tac-toe board... it should be a 2D 3x3 grid or board. Also you should probably rename the variable values to grid or board.
This will mean taking 2 values as input from user in handle_turn(). I suggest not putting a large string inside input() as it's hard to read. Try instead
print("Enter space separated co-ordinates to pick a square")
print(f"Player {self.player} pick a square: "))
x = int(input())
y = int(input())

Ok, I'll admit this is a little annoying for the players.... maybe you could write the coordinates in the empty cells like
 X  | 1,2 |  O
2,1 |  X  | 1,3
3,1 | 3,2 |  O

(try to do this without writing out the whole starting grid manually, it should be possible using ",".join(), str() and list comprehensions)
Also it should be possible to modify the row/column/diagonals functions with 2D indices like grid[0][0], grid[1][1], grid[2][2], etc. to make it more readable. Due to the way self.grid is stored, the row function can be simplified... but it will look very different from column/diagonal and so it's probably not worth it.


Calls many stored dataframes, change them and combine them I call many dataframes (using pickle), then I extract the interesting values of each one and finally combine them.  Is there a better way to do it? For example with a for loop  call them automatically instead of having to repeat the code many times?

#Dataframe 1
df_NB_E = pd.read_pickle('/Dataframes/Total Accuracy NB_E')

lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
df_NB_E.index = pd.MultiIndex.from_product([lvl0, lvl1])

df_NB_E['Total Acc'] = df_NB_E.mean(axis=1).round(4)*100
df_NB_E=df_NB_E.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()

df_NB_E.rename(columns={'10x10':'NB_E'},inplace=True)

#Dataframe 2
df_LDA_E = pd.read_pickle('/Dataframes/Total Accuracy LDA_E')

lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
df_LDA_E.index = pd.MultiIndex.from_product([lvl0, lvl1])

df_LDA_E['Total Acc'] = df_LDA_E.mean(axis=1).round(4)*100
df_LDA_E=df_LDA_E.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()

df_LDA_E.rename(columns={'10x10':'LDA_E'},inplace=True)

#Dataframe 3
df_DT_E = pd.read_pickle('/Dataframes/Total Accuracy DT_E')

lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
df_DT_E.index = pd.MultiIndex.from_product([lvl0, lvl1])

df_DT_E['Total Acc'] = df_DT_E.mean(axis=1).round(4)*100
df_DT_E=df_DT_E.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()

df_DT_E.rename(columns={'10x10':'DT_E'},inplace=True)

#Dataframe 4
df_RF_E = pd.read_pickle('/Dataframes/Total Accuracy RF_E')

lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
df_RF_E.index = pd.MultiIndex.from_product([lvl0, lvl1])

df_RF_E['Total Acc'] = df_RF_E.mean(axis=1).round(4)*100
df_RF_E=df_RF_E.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()

df_RF_E.rename(columns={'10x10':'RF_E'},inplace=True)

#Combining the 4 dataframes
pd.concat([df_NB_E, df_LDA_E, df_DT_E, df_RF_E], axis=1)

There are definitely ways to simplify this code to avoid code repetition. For each of your dataframes, I noticed that you are doing essentially the same thing with only two differences:

the path to the frame
the custom name of each frame

This suggests that these blocks can be simplified into a single function with the two dynamic elements passed in as parameters like this.

def modifyFrame(frameName,frameLocation):
    df = pd.read_pickle(frameLocation)
    lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
    lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
    df.index = pd.MultiIndex.from_product([lvl0, lvl1])
    df['Total Acc'] = df.mean(axis=1).round(4)*100
    df=df.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()
    df.rename(columns={'10x10':frameName},inplace=True)
    return df

Now there are a few ways to simplify your code. One of the simplest ways would be to just call the function four times. This might be an option if you only have a few frames to modify, and the parameters for the frames don't change.

df_NB_E = modifyFrame('NB_E', '/Dataframes/Total Accuracy NB_E')
df_LDA_E = modifyFrame('LDA_E', '/Dataframes/Total Accuracy LDA_E')
df_DT_E = modifyFrame('DT_E' , '/Dataframes/Total Accuracy DT_E')
df_RF_E = modifyFrame('RF_E' , '/Dataframes/Total Accuracy RF_E')

pd.concat([df_NB_E, df_LDA_E, df_DT_E, df_RF_E], axis=1)

If you have a lot of frames, or if you need to modify the list of frames to be modified often, then I would suggest that you group the parameters together in a list. This makes it easier to loop through the frames. Grouping the parameters into a list like this would also make it easier to store the parameters in a separate location so you could change the frame information without changing the code. This reduces the chance of introducing errors into working code.

frames = [('NB_E' , '/Dataframes/Total Accuracy NB_E'),
          ('LDA_E', '/Dataframes/Total Accuracy LDA_E'),
          ('DT_E' , '/Dataframes/Total Accuracy DT_E'),
          ('RF_E' , '/Dataframes/Total Accuracy RF_E')]

You can use a few different methods to loop through the frames. First you can use a for loop like you mentiond.

modifiedFrames = []

for frame in frames:
    modifiedFrames.append(modifyFrame(frame[0],frame[1]))

pd.concat(modifiedFrames, axis=1)

However, one of the most powerful features of the python language is list comprehension. I suggest that you read more about it here.

Below is my solution to your problem using a function, a list containing the frame information, and a list comprehension.

def modifyFrame(frameName,frameLocation):
    df = pd.read_pickle(frameLocation)
    lvl0 = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'ALL']
    lvl1 = ['10x20', '10x10', '10x5', '10x2', ]
    df.index = pd.MultiIndex.from_product([lvl0, lvl1])
    df['Total Acc'] = df.mean(axis=1).round(4)*100
    df=df.reset_index().pivot('level_1', 'level_0', 'Total Acc').loc['10x10'].reset_index()
    df.rename(columns={'10x10':frameName},inplace=True)
    return df

frames = [('NB_E' , '/Dataframes/Total Accuracy NB_E'),
          ('LDA_E', '/Dataframes/Total Accuracy LDA_E'),
          ('DT_E' , '/Dataframes/Total Accuracy DT_E'),
          ('RF_E' , '/Dataframes/Total Accuracy RF_E')]

#Combining the 4 dataframes
pd.concat([modifyFrame(frame[0],frame[1]) for frame in frames], axis=1)


Read multiple files async I want to read multiple files simultaneously and apply the same function on data.

This code works correctly, but can someone please suggest any better way of writing this?

function fileread(path,stats,callback){
   var buffer = new Buffer(stats.size);
   fs.readFile(path, buffer, function(err, data){
      if(err){
         throw err;
      }

      callback(null, data);
   });
}

function testAsync() {
    var files = ['Statistics_Schema.json','seriesData'];
    async.map(files, fs.stat, function(err, stats){
       var i=0;
       async.map(files, function(path, callback){
          fileread(path, stats[i++], callback);
          },function(err, data){
                for(var j=0; j < data.length; j++){
                 console.log(data[j].toString());
                }
           });
    });
}

I believe you can shorten it to just

function testAsync() {
    var files = ['Statistics_Schema.json', 'seriesData'];
    async.map(files, fs.readFile, function (err, data) {
        for(var i = 0, l = data.length ; i < l ; i++) {
            console.log( data[i].toString() );
        }
    });
}

Right now, you're first calling fs.stat on each file, only so you can create a buffer in your fileread method.

But fs.readFile does not take a buffer argument. It takes an options object (and there's no buffer option).

The Buffer object you're passing is an object, though, so Node doesn't complain. It just doesn't find any relevant fileRead options in that object either, so it's basically ignored.

So you don't need the buffer, which means you don't need fs.stat, which means you can skip almost all of your code.


applicationDidBecomeActive: Am I causing a memory leak? Using ARC, I'm calling the following function in an iOS app every time the app gets opened in the applicationDidBecomeActive function.

My concern is that it could create a memory leak because it's creating new instances of UIViewControllers every time the app gets opened from the background.

- (void)showMainWindow{
  NSLog(@"@Info @AppDelegate: Showing Main Window");
  self.leftMenuViewController = nil;
  self.rightMenuViewController = nil;
  MenuViewController *tempLeft = [[MenuViewController alloc]initWithSide:@"left"];
  MenuViewController *tempRight = [[MenuViewController alloc]initWithSide:@"right"];
  self.leftMenuViewController = tempLeft;
  self.rightMenuViewController = tempRight;
  self.viewDeckController =  [[IIViewDeckController alloc] initWithCenterViewController:self.webViewController
                                                                                leftViewController:self.leftMenuViewController
                                                                               rightViewController:self.rightMenuViewController];

  self.window.rootViewController = self.viewDeckController;
  [[NSNotificationCenter defaultCenter] postNotificationName:@"updateNavigationBar" object:nil];
}

This code doesn't appear to leak. To be sure, however, you should use the leaks instrument to periodically check your code.

To do such,

Select Product -> Profile (or, ⌘ I)
Choose `Leaks`
Select Profile
Exercise your app (i.e. go through all the options, background it, etc)

For more information on using the leaks tool, you can checkout Ray Wenderlich's Instruments Tutorial for iOS: How to Debug Memory Leaks.

Additional Notes:

1) Unless you have a really good reason to, you shouldn't be setting self.window.rootViewController every time that the app returns to the foreground. Instead of calling showMainWindow from within applicationDidBecomeActive, you should probably move this code within application:didFinishLaunchingWithOptions:, which is the more common place to do  initial app setup.

Further, if you need a controller to know when the app has entered the foreground (I imagine that this is the reason you're actually doing this), you should have it register to receive notification of UIApplicationWillEnterForegroundNotification. I.e.

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(YOUR_SELECTOR)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];

    // ... whatever else you do here...
}

// Also make sure to unregister too
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

2) To make this code a bit more cleaner and easier to read, I would rewrite it like this:

- (void)showMainWindow
{

    NSLog(@"@Info @AppDelegate: Showing Main Window");

    self.leftMenuViewController = [[MenuViewController alloc]initWithSide:@"left"];;
    self.rightMenuViewController = [[MenuViewController alloc]initWithSide:@"right"];;

    self.viewDeckController =  [[IIViewDeckController alloc] initWithCenterViewController:self.webViewController
                                                                                leftViewController:self.leftMenuViewController
                                                                           rightViewController:self.rightMenuViewController];

  self.window.rootViewController = self.viewDeckController;
  [[NSNotificationCenter defaultCenter] postNotificationName:@"updateNavigationBar" object:nil];
}

In such, you don't have to explicitly set self.leftMenuViewController and self.rightMenuViewController to nil or create the temp objects.


Convert a JS DataTable to an array of objects An API provides data as some sort of data table, column and rows.

I have written a function to get JS Objects from this DataTable.

function processAggregateData(data) {
    dataRows = data.data[0].rows
    var returnArray = [];
    for (var i = 0; i < dataRows.length; ++i){
        returnArray.push({
            index: dataRows[i].fld[0].v,
            average: dataRows[i].fld[1].v,
            min: dataRows[i].fld[2].v,
            max: dataRows[i].fld[3].v,
            sum: dataRows[i].fld[4].v,
            target: dataRows[i].fld[5].v,
            LLL: dataRows[i].fld[6].v,
            LL: dataRows[i].fld[7].v,
            L: dataRows[i].fld[8].v,
            H: dataRows[i].fld[9].v,
            HH: dataRows[i].fld[10].v,
            HHH: dataRows[i].fld[11].v,
            status: dataRows[i].fld[12].v
        })
    }
    return returnArray;
}

I would like to improve it, in particular:

There is a lot of 'magic constants', mapping a column number to an object property. I have tried to extract them, but have not found a way to do it without doubling the size of the function. Is that suitable here?
Of course, any improvement of the code is most welcome.

A note, to end, there is users on IE, so ECMA6 is not possible.

Thank you for your review :)

There isn't really much you can do unless you know the objects property name. I refactored the properties into an array, so you just can iterate through them as they are reused so many times.

function processAggregateData(data) {
    var dataProperties = ['index', 'average', 'min',
                          'max', 'sum', 'target',
                          'LLL', 'LL', 'L',
                          'H', 'HH', 'HHH',
                          'status'];
    dataRows = data.data[0].rows;
    var returnArray = [];
    for (var i = 0; i < dataRows.length; ++i){
        var dataObject = {};
        for(var j=0;j<dataPoperties.length;j++){
          dataObject[dataProperties[j]] = dataRows[i].fld[j].v;
        }
        returnArray.push(dataObject);
    }
    return returnArray;
}

As you can see there are no longer any magic constants.

NOTE: EcmaScript 6 is possible, you just need to transpile it into EcmaScript 5


Printing Gray code through modifying Samuel Beckett's stage instructions This is exercise 2.3.24. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Modify Beckett to print the Gray code.
Beckett refers to the following program within the text:
public class Beckett
{
    public static void moves(int n, boolean enter)
    {
        if (n == 0) return;
        moves(n-1, true);
        if (enter) System.out.println("enter " + n);
        else       System.out.println("exit " + n);
        moves(n-1, false);
    }
    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        moves(n, true);
    }
}

As stated in the text:

The playwright Samuel Beckett wrote a play called Quad that had the following property:
starting with an empty stage, characters enter and exit one at a time
so that each subset of characters on the stage appears exactly once.

The above program tries to simulate the above-explained stage instructions. Here is my attempt at turning Beckett into a program that produces Gray code:
public class exercise2_3_24
{
    public static String swap(String s, String t, int n)
    {
        n = n-1;
        return s.substring(0,n) + t + s.substring(n+1);
    }
    public static void beckett(String s, int n)
    {
        if (n == 0) return;
        beckett(s, n-1);
        System.out.println(swap(s, "1", n));
        s = swap(s, "1", n);
        beckett(s, n-1);
    }
    public static void graycodes(int n)
    {
        String s = "";
        for (int i = 0; i < n; i++)
            s += "0";
        System.out.println(s);
        beckett(s, n);
    }
    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        graycodes(n);
    }
}

Is there any way that I can improve my program?
Thanks for your attention.

I have some suggestions for your code.
Always add curly braces to loop & if
In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.
Use java.lang.StringBuilder to concatenate String in a loop.
It's generally more efficient to use the builder in a loop, since the compiler is unable to make it efficient in a loop; since it creates a new String each iteration. There are lots of good explanations with more details on the subject.
before
String s = "";
for (int i = 0; i < n; i++) {
   s += "0";
}

after
StringBuilder s = new StringBuilder();
for (int i = 0; i < n; i++) {
   s.append("0");
}

Don’t use a loop when you want to repeat a string of x elements
The API that java give you offer a method to repeat the character x times; you can use java.lang.String#repeat (Java 11+)
before
StringBuilder s = new StringBuilder();
for (int i = 0; i < n; i++) {
   s.append("0");
}

after
String s = "0".repeat(n);

Extract the expression to variables when used multiple times.
In your code, you can extract the similar expressions into variables; this will make the code shorter and easier to read.
before
beckett(s, n - 1);
System.out.println(swap(s, "1", n));
s = swap(s, "1", n);
beckett(s, n - 1);

after
int previousNumber = n - 1;
beckett(s, previousNumber);
System.out.println(swap(s, "1", n));
s = swap(s, "1", n);
beckett(s, previousNumber);

Uses the increment and decrement operators when possible
Try to use the x++ / ++x, x-- or --x instead of x = x + 1 since they are more widely used and make the code easier to read.
before
n = n - 1;

after
n--;


Find the value nearest to k in the sorted array Given a sorted array, return the 'closest' element to the input 'x'.

I do understand the merits of unit testing in separate files, but I deliberately added it to the main method for personal convenience, so don't consider that in your feedback.

I'm looking for request code review, optimizations and best practices.

public final class ClosestToK {

    private ClosestToK() { }

    /**
     * Given a sorted array returns the 'closest' element to the input 'x'.
     * 'closest' is defined as Math.min(Math.abs(x), Math.abs(y))
     *
     * Expects a sorted array, and if array is not sorted then results are unpredictable.
     *
     * If two values are equi-distant then the greater value is returned.
     *
     * @param a  The sorted array a
     * @return   The nearest element
     */
    public static int getClosestK(int[] a, int x) {

        int low = 0;
        int high = a.length - 1;

        while (low <= high) {
            int mid = (low + high) / 2;

            // test lower case
            if (mid == 0) {
                if (a.length == 1) {
                    return a[0];
                }

                return Math.min(Math.abs(a[0] - x), Math.abs(a[1] - x)) + x;
            }

            // test upper case
            if (mid == a.length - 1) {
                return a[a.length - 1];
            }

            // test equality
            if (a[mid] == x || a[mid + 1] == x) {
                return x;
            }

            // test perfect range.
            if (a[mid] < x  && a[mid + 1] > x) {
                return Math.min(Math.abs(a[mid] - x), Math.abs(a[mid + 1] - x)) + x;
            }

            // keep searching.
            if (a[mid] < x) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }

        throw new IllegalArgumentException("The array cannot be empty");
    }

    public static void main(String[] args) {
        // normal case.
        int[] a1 = {10, 20, 30, 40};
        assertEquals(30, getClosestK(a1, 28));

        // equidistant
        int[] a2 = {10, 20, 30, 40};
        assertEquals(30, getClosestK(a2, 25));

        // edge case lower boundary
        int[] a3 = {10, 20, 30, 40};
        assertEquals(10, getClosestK(a3, 5));
        int[] a4 = {10, 20, 30, 40};
        assertEquals(10, getClosestK(a4, 10));

        // edge case higher boundary
        int[] a5 = {10, 20, 30, 40};
        assertEquals(40, getClosestK(a5, 45));
        int[] a6 = {10, 20, 30, 40};
        assertEquals(40, getClosestK(a6, 40));

        // case equal to
        int[] a7 = {10, 20, 30, 40};
        assertEquals(30, getClosestK(a7, 30));

    }
}

Here's my solution which seems to work fine :

public static int getClosestK(int[] a, int x) {

    int low = 0;
    int high = a.length - 1;

    if (high < 0)
        throw new IllegalArgumentException("The array cannot be empty");

    while (low < high) {
        int mid = (low + high) / 2;
        assert(mid < high);
        int d1 = Math.abs(a[mid  ] - x);
        int d2 = Math.abs(a[mid+1] - x);
        if (d2 <= d1)
        {
            low = mid+1;
        }
        else
        {
            high = mid;
        }
    }
    return a[high];
}

Here's the principle : the interval [low, high] will contain the closest element to x at any time. At the beginning, this interval is the whole array ([low, high] = [0, length-1]). At each iteration, we'll make it strictly smaller. When the range is limited to a single element, this is the element we are looking for.

In order to make the range smaller, at each iteration, we'll consider mid the middle point of [low, high]. Because of the way mid is computed, mid+1 is also in the range. We'll check if the closest value is at mid or mid+1 and update high or low accordingly. One can check that the range actually gets smaller.

Edit to answer to comments:

As spotted by @Vick-Chijwani , this code doesn't handle perfectly the scenarios where an element appears multiple times in the input. One can add the following working tests to the code :

    // case similar elements
    int[] a8 = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10};
    assertEquals(10, getClosestK(a8, 9));
    assertEquals(10, getClosestK(a8, 10));
    assertEquals(10, getClosestK(a8, 11));

but this one will fail :

   int[] a9 = {1, 2, 100, 100, 101};
   assertEquals(3, getClosestK(a9, 2)); // actually returns 100


Custom TextBox control: AppendLine Is there any way to improve this simple addition to the textbox control: appending a new line?

class CustomTextBox : TextBox
{
    public void AppendLine(string textData)
    {
        if (this.Text.EndsWith(Environment.NewLine) || this.Text == "")
        {
            this.AppendText(textData);
        }
        else
        {
            this.AppendText(Environment.NewLine + textData);
        }
    }
}

I don't care for empty quotes designating an empty string. It should be replaced with String.Empty. It simply clarifies your intention and leaves no ambiguity that you perhaps forgot to put something in the quotes, or maybe even meant to put a space in there. Otherwise, I feel this is very simple and solid.


Garry's Mod custom spectate player I have been making my own scoreboard, and needed a custom spectate function for it, so I made this:

  util.AddNetworkString( "spectatePlayer" )
  local playerLocal
  local isSpectating = false

 net.Receive("spectatePlayer", function(length, client)
    if isSpectating then return end
        isSpectating = true
        playerLocal = client
        print(client:Nick() .. "Started spectating: " .. net.ReadEntity():Nick())
        client:Spectate(5)
        client:SpectateEntity(net.ReadEntity())

 end)

 hook.Add("Tick", "keydown", function()
        if not isSpectating then return end
                if (playerLocal:KeyDown(IN_FORWARD)) then
                        isSpectating = false
                        playerLocal:UnSpectate()
                        print(playerLocal:Nick().."Finished Spectating")
                end
        end)

Is there anything I could improve on? Am I over-complicating anything?

There's a few things to comment on:

I'm not a Gmod developer, so I'm not familiar with the spectating abilities built in, but, I'd assume that if any exist, they're probably better to use than re-inventing the wheel.

There's only two states: not spectating, and spectating. What happens if I want to simply switch between players? Do I have to stop spectating, and then select a new player to spectate?

Why can I not just press lmb and go to the next?

util.AddNetworkString( "spectatePlayer" )

You've got extraneous whitespace in your brackets.

print(client:Nick() .. "Started spectating: " .. net.ReadEntity():Nick())
print(playerLocal:Nick().."Finished Spectating")

String concatenation joins the strings, as they are. Meaning, it would read like:

  QuillStarted spectating: James Heald.
  QuillFinished Spectating

Add some whitespace in there.

print(client:Nick() .. " Started spectating: " .. net.ReadEntity():Nick())
print(playerLocal:Nick().." Finished Spectating")

Oh, and you should be keeping the cases (upper and lower) consistent in your messages:

"Started spectating: "
         ^
"Finished Spectating"
          ^