Time of day based timer - run function at certain time, daily I need to call a function exactly at certain hour, daily, my programs runs 24/7.

I wrote the following timer mechanism, which generally works that way:

Calculate time until hour and generate timer with that interval.
When timer elapse, call timer event and generate another 24h timer.
Go back to step 2.

private static void InitTimeBasedTimer(TimeSpan timeToRun, Action funcToRun)
{
    TimeSpan interval = timeToRun.Subtract(DateTime.Now.TimeOfDay);
    double intervalMillis = interval.TotalMilliseconds;
    if (interval.TotalMilliseconds < 0)
    {
        intervalMillis = (new TimeSpan(24, 0, 0)).Add(interval).TotalMilliseconds;
    }
    Timer timer = new Timer(intervalMillis);
    timer.AutoReset = false;
    timer.Elapsed += (sender, e) => TimeBasedCallback(timeToRun, funcToRun);
    timer.Start();
}

public static void TimeBasedCallback(TimeSpan timeToRun, Action funcToRun)
{
    funcToRun();
    TimeSpan interval = timeToRun.Subtract(DateTime.Now.TimeOfDay); //24 h
    double intervalMillis = interval.TotalMilliseconds;
    if (intervalMillis < 0)
    {
        intervalMillis = (new TimeSpan(24, 0, 0)).Add(interval).TotalMilliseconds;
    }
    Timer timer = new Timer(intervalMillis);
    timer.AutoReset = false;
    timer.Elapsed += (sender, e) => TimeBasedCallback(timeToRun, funcToRun);
    timer.Start();
}

EDIT:
There are several functions that each writes to a DB every day in different hours. Can't afford task scheduler / process for each function. Quartz.NET seems a bit overkill for such a simple task.

Without knowing what you're trying to do, I'd say this is the wrong approach. I would create an executable and set it up as a scheduled task to run every 24 hours.

Not sure what OS you are using, but assuming it's windows its fairly easy http://windows.microsoft.com/en-au/windows7/schedule-a-task

You can use a timer. Also you can do this:

 public Form1()
    {
        InitializeComponent();
        DateTime today = DateTime.Today;
        StreamDate(today)
        timer1.Start();
    }
private void timer1_Tick(object sender, EventArgs e)
    {
        DateTime today = DateTime.Today;
        string text = System.IO.File.ReadAllText(@"C:\date.txt");
        DateTime newdate = Convert.ToDateTime(text);
        if (today != newdate)
        {
          StreamDate(today)

        }
private void StreamDate(string today)
{
            StreamWriter foldcreat = new StreamWriter(@"C:\date.txt");
            foldcreat.WriteLine(String.Format("{0}", today));
            foldcreat.Close();
}

it's if you have oportunity to create text file ....
Another way : http://www.codeproject.com/Articles/6507/NET-Scheduled-Timer


"Ticker" for game timing I designed a "Ticker" based on how I imagine Minecraft's tick system works. My ticker calls a method tickRate times a second and provides a Delta Time value (deltaTime) to the method being called.

The issue I have with my code is that I find the update method (which handles timing) to be ugly but I'm not sure what I can do.

My ticker class is designed to be instantiated and used whenever, it does not have to be used right away (which is why I don't set any time related information in the constructor). This is why there is a check for nextTick and lastTick being 0 inside update, as to ensure that the delta time does not go crazy on the first tick. The issue with this is that it looks a bit ugly, however I'm not sure what I could do. I could move the reset code into the reset method, however that would now mean that the reset method is time dependant, and must be only be called when you intend to use the ticker.

Ticker.java

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

public class Ticker {
    private long lastTick;
    private long nextTick;
    private int tickRate;

    private Set<TickListener> tickListeners = new HashSet<>();

    public Ticker(int tickRate) {
        this.tickRate = tickRate;
    }

    public void addTickListener(TickListener listener) {
        tickListeners.add(listener);
    }

    public void removeTickListener(TickListener listener) {
        tickListeners.remove(listener);
    }

    public void setTickRate(int tickRate) {
        this.tickRate = tickRate;
    }

    public int getTickRate() {
        return tickRate;
    }

    public void reset() {
        lastTick = 0;
        nextTick = 0;
    }

    public boolean update() {
        long currentTime = System.currentTimeMillis();

        if (currentTime >= nextTick) {
            long targetTimeDelta = 1000L / tickRate;

            if (lastTick == 0 || nextTick == 0) {
                lastTick = currentTime - targetTimeDelta;
                nextTick = currentTime;
            }

            float deltaTime = (float) (currentTime - lastTick) / targetTimeDelta;

            for (TickListener listener : tickListeners) {
                listener.onTick(deltaTime);
            }

            lastTick = currentTime;
            nextTick = currentTime + targetTimeDelta;

            return true;
        }

        return false;
    }
}

TickListener.java

public interface TickListener {
    void onTick(float deltaTime);
}

Example usage

Ticker ticker = new Ticker(20); // 20 ticks per second

ticker.addTickListener(new TickListener() {

    @Override
    public void onTick(float deltaTime) {
        System.out.println(String.format("Ticked with deltaTime %f", deltaTime));
    }
});

while (true) {
    ticker.update();
}

This is one of the cleanest code I have come across in a while. Congrats to your lovely, well-written code!

Just some points:

I don't like seeing this:

public class Ticker {
    private long lastTick;
    // ...
    }
}

It is more readable (IMO) when you put spaces after the beginning and before the end:

public class Ticker {

    private long lastTick;
    // ...
    }

}

I don't see a reason why not to do so, as the rest of your code is very well spaced.
This method:

public boolean update() {
    long currentTime = System.currentTimeMillis();

    if (currentTime >= nextTick) {
        long targetTimeDelta = 1000L / tickRate;

        if (lastTick == 0 || nextTick == 0) {
            lastTick = currentTime - targetTimeDelta;
            nextTick = currentTime;
        }

        float deltaTime = (float) (currentTime - lastTick) / targetTimeDelta;

        for (TickListener listener : tickListeners) {
            listener.onTick(deltaTime);
        }

        lastTick = currentTime;
        nextTick = currentTime + targetTimeDelta;

        return true;
    }

    return false;
}

Just my opinion, but I feel uncomfortable with that many spaces in code. The only place I would use spaces would be:

Between Node declarations in JavaFX, or JWhatever declarations in Swing.
Where there is an obvious change in what the code will do.

So it would be more like:

public boolean update() {
    long currentTime = System.currentTimeMillis();
    if (currentTime >= nextTick) {
        long targetTimeDelta = 1000L / tickRate;
        if (lastTick == 0 || nextTick == 0) {
            lastTick = currentTime - targetTimeDelta;
            nextTick = currentTime;
        }

        float deltaTime = (float) (currentTime - lastTick) / targetTimeDelta;
        for (TickListener listener : tickListeners) {
            listener.onTick(deltaTime);
        }

        lastTick = currentTime;
        nextTick = currentTime + targetTimeDelta;
        return true;
    }
    return false;
}

An Example how I do it in my Projects when I need it, is that I use a new Thread and let it have handle the needed Stuff.

TickHandler.java

package me.donjoe.foo;

import java.util.List;
import java.util.ArrayList;

public class TickHandler extends Thread {

    private int tickRate = 60;
    private List<TickHandler> q = new ArrayList<>();

    @Override
    public void run() {
        try {
            // Devide 1000 Millisecond (1 Second) through the tickrate
            // to get the time every tick has
            long timeout = 1000L / this.tickRate;
            // Buffer-Time which carries over the Time that the last tick took too long.
            // Used to make the Ticks in-sync again.
            long buffer = 0L;
            while (true) {
                // Check if Interrupted. If so, stop this Thread
                if (this.isInterrupted()) throw new InterruptedException();
                // Start Time
                long startTime = System.currentTimeMillis();

                // TODO: Do some Stuff here
                // Handle the TickHandler / Callbacks
                for (TickHandler handler : this.q) handler.handle();
                // Maybe clear the Q, depends on how you like to work with it
                // this.q.clear();

                // Time to wait in this Tick
                long toWait = (timeout - buffer) - (System.currentTimeMillis() - start);

                // When the Time is negative, the Tick took too long to execute.
                // Set the buffer to the time it took too long and let is balance out.
                if (toWait < 0) buffer = -toWait;
                else {
                    this.wait(toWait);
                    // Clear the buffer. No time to wait on the next one
                    buffer = 0L;
                }
            }
        } catch (InterruptedException e) {
            // The Thread got stopped. Do stuff here
        }
    }
}


Read string of any length in C I've written code in C for reading a string of any length, and printing the string. It's one of my first C programs. I posted the program as part of a Stack Overflow question, and received a comment:

... there are many things wrong with your C version.

I'd really like to know what is wrong with the function I have written. Suspects: EOF handling, calling dynamic memory allocation functions too many times.
#include <stdlib.h>
#include <stdio.h>

/* Asks the user for string input.
 * Returns a pointer to the string entered by the user.
 * The pointer must be freed.
 */
char* input()
{
    char *s = malloc(sizeof(char));  /* For the null character */
    if (s == NULL) {
        fprintf(stderr, "Error: malloc\n");
        exit(1);
    }
    s[0] = '\0';

    /* Read characters one by one */
    char ch;
    size_t s_len = 0;
    while((ch = (char) getchar()) != '\n') {
        if (ch == EOF) {
            exit(0);
        }
        s_len++;
        s = realloc(s, (s_len * sizeof(char)) + sizeof(char));
        if (s == NULL) {
            fprintf(stderr, "Error: realloc\n");
            exit(1);
        }
        s[s_len - 1] = ch;
        s[s_len] = '\0';
    }
    return s;
}

int main()
{
    printf("Name: ");
    char *s = input();
    printf("%s\n", s);
    free(s);
    return 0;
}

/* Asks the user for string input.
 * Returns a pointer to the string entered by the user.
 * The pointer must be freed.
 */

Slightly misleading in that this function doesn't ask for input. (As written it is not responsible for printing the prompt.)

Perhaps also should clarify the intended behavior:

If there is input that is not terminated by a newline, is that string returned?
When input is terminated with a newline, is the newline preserved in the returned string?

char* input()
{
    char *s = malloc(sizeof(char));  /* For the null character */

In C, char by definition is 1 byte. sizeof (char) is unnecessary and adds visual noise.

    if (s == NULL) {
        fprintf(stderr, "Error: malloc\n");
        exit(1);

It's usually considered poor behavior if calling a library function causes the entire program to terminate.  You should return an error value (e.g. NULL) and leave that decision up to the caller.

    }
    s[0] = '\0';

    /* Read characters one by one */
    char ch;

ch must be an int.  getchar returns an int precisely so that it can return a value outside the range of char (technically unsigned char) to indicate failure (i.e., the EOF value).  Otherwise you would not be able to distinguish EOF from a legitimate byte value.

    size_t s_len = 0;
    while((ch = (char) getchar()) != '\n') {
        if (ch == EOF) {

It's more idiomatic to check for EOF in the loop condition and then check for character values inside the loop body:

int ch;
while ((ch = getchar()) != EOF) {
    if (ch == '\n') {
        ...

Checking for EOF in the loop condition allows you to safely truncate ch to char throughout the entire loop body, which makes it a bit easier to reason about.

            exit(0);

Same thing here about terminating the program.  It's especially weird here since this exits with a success code and doesn't return the string to the caller.

        }
        s_len++;
        s = realloc(s, (s_len * sizeof(char)) + sizeof(char));

Never do x = realloc(x, ...).  If realloc fails and returns NULL, you will have lost the old value of x and will be unable to free it, resulting in a memory leak.  You instead should use a temporary variable:

char* newBuffer = realloc(s, ...);
if (newBuffer == NULL) {
  ...
}
s = newBuffer;

Again, sizeof (char) is noise.  You additionally should generally avoid sizeof (Type); it's not robust if the types change since you would need to edit more places (and neglecting to do so could lead to silent buffer overflows and introduce security vulnerabilities).  It's better to use sizeof expression where expression is based on the corresponding variable.  For example, if you want the code to be robust if the type of s changes (e.g. if you wanted to adapt the code to support wchar_t), you should do:

char* newBuffer = realloc(s, (s_len + 1 /* NUL */) * sizeof *s);
...

Finally, calling realloc for every byte read is grossly inefficient.  A better approach is to maintain a buffer where you keep track of its allocated size and to grow it exponentially (e.g. doubling in size) whenever you need more space.

        if (s == NULL) {
            fprintf(stderr, "Error: realloc\n");
            exit(1);

Same thing about terminating the program.  Also should do free(s); along this path.

int main()
{
    printf("Name: ");

I/O is normally buffered.  You should call fflush(stdout) afterward to ensure that the prompt is printed to the screen before waiting for input.

Realistically, you would want to check that the input characters are acceptable to your program.


Three sum problem using HashMap in Java Given an array and a value, find all the triplets in the array whose sum is equal to the given value. For example, if the given array is {12, 3, 4, 1, 6, 9} and the given sum is 24, then this is one triplet (12, 3 and 9) which contributes to the total sum of 24.
Solution for given example:
6, 9, 9
6, 6, 12
3, 9, 12
Conditions:

The ordering of the numbers in the solution does not matter.

Duplicate triplet is not allowed.

A number is not allowed to be used multiple times.

This question was asked here.
Here is my code which addresses all the issues. One concern is the code looks a little muddy which I want to avoid in the production grade code. Any constructive feedback is appreciated.
Runtime: O(n2)
GitHub
public class ThreeSum {

    static class Triplet {
        final List<Integer> triplets;

        public Triplet(int x, int y, int z) {
            triplets = Arrays.asList(x, y, z);
            Collections.sort(triplets);
        }

        @Override
        public int hashCode() {
            return Objects.hash(triplets.get(0), triplets.get(1), triplets.get(2));
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof Triplet) {

                Triplet other = (Triplet) o;
                return other.triplets.get(0) == this.triplets.get(0) &&
                        other.triplets.get(1) == this.triplets.get(1) &&
                        other.triplets.get(2) == this.triplets.get(2);
            }

            return false;
        }

        @Override
        public String toString() {
            return String.format("(%d, %d, %d)", triplets.get(0), triplets.get(1), triplets.get(2));
        }
    }

    public static Set<Triplet> findTriplets(int numbers[], int targetSum) {
        Set<Triplet> triplets = new HashSet<>();

        // insert all pairs in the look up table
        Map<Integer, int[]> lookup = new HashMap<>();
        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                int total = numbers[i] + numbers[j];
                lookup.put(total, new int[]{i, j});
            }
        }

        // look for the complement, if found viola! here you go with the triplet
        for (int currentIndex = 0; currentIndex < numbers.length; currentIndex++) {
            int complement = targetSum - numbers[currentIndex];

            if (lookup.containsKey(complement)) {
                int indexes[] = lookup.get(complement);

                if (currentIndex != indexes[0] && currentIndex != indexes[1]) {
                    int x = numbers[indexes[0]], y = numbers[indexes[1]];
                    triplets.add(new Triplet(x, y, numbers[currentIndex]));
                }
            }
        }

        return triplets;
    }
}

You are storing the integers of a Triplet as a List internally, yet you are not really taking advantage of the interface List's functionality. For example:

return Objects.hash(triplets.get(0), triplets.get(1), triplets.get(2));

Why not simply do this:

return triplets.hashCode();

Or, another example:

return other.triplets.get(0) == this.triplets.get(0) &&
        other.triplets.get(1) == this.triplets.get(1) &&
        other.triplets.get(2) == this.triplets.get(2);

This can be replaced by this:

return other.triplets.equals(this.triplets);

There's an issue I didn't catch in the old question but which was already present there: Your code doesn't consider the possibility that the same sum is formed by more than one pair of numbers, because you are simply mapping integers to one pair of indices, and if you encounter a pair that adds up to a sum that is already stored in lookup, the old index pair gets overridden.

A way to overcome this problem could be to map the integers to a List<int[]>), but this would make things even more complicated, and I think the reason that this would get overly complicated is that you are, in fact, hard-coding a recursive process (first you create the pairs, then from the pairs you create the triplets etc.). You could instead try to write a method that accumulates all possible n-tuplets, with n being any arbitrary positive integer, through recursion, e.g. like this:

If n is 1, then return an array/list of all integers
If n is greater than 1, then iterate through the original array and, for every integer in it, combine this integer with all n-1-tuplets formed by the numbers that follow this integer in the array (taking only the following numbers and not the preceding numbers prevents duplicate tuplets that only differ in the order of the integers).

I imagine that this would be much easier to code than what you currently have (maybe this is also what you mean by your code being "muddy"), and also much more flexible. True, if it's just about pairs, then it might not be as fast as what you did here, but if it comes to tuplets of more than 2 numbers, I don't think there is much benefit of what you are trying to do here (although this is just a guess, I didn't actually benchmark it).

Your code is quite inefficient by storing all the sums of pairs into the hashmap.

The memory requirements grow exponentially (adding array entry n adds n more pairs, so it grows in a factorial manner).

You are better off by holding onto a pair only as long as you need it.  This can be done by checking all possible additions to that pair at once and then throwing it away.

This is most easily done recursively.  You have a set of numbers, and the next number you can either include in your set or not.  Repeat this recursively.

Generally, for any given set of array values, you hold onto it only as long as you need it, to try combining it with other items from the array.  Once you find a solution you save it.  Once you've exhausted all possibilities with that set you throw it away.

public class Recurse {
    static final int target = 24;
    static final int sumCount = 3;
    ArrayList<int[]> solutions = new ArrayList<int[]>();

    public void sum(int arr[], int arrayIndex, int sum, int indicesSoFar[]) {
        //you can either include the current value or not

        //first we try skipping it
        if(indicesSoFar.length + arr.length - (arrayIndex + 1) >= sumCount) { //only skip if there are enough numbers left
            sum(arr, arrayIndex + 1, sum, indicesSoFar);
        }
        //now we try using it
        int val = arr[arrayIndex];
        int added = val + sum;
        if(indicesSoFar.length + 1 == sumCount) {//if we use it, it is the last in the set
            if(added == target) {// the sum matches, so it is a solution
                int next[] = Arrays.copyOf(indicesSoFar, indicesSoFar.length + 1);
                next[indicesSoFar.length] = arrayIndex;
                solutions.add(next);
            }
        } else if(added <= target) {//use it if we can (the sum is not too large).  This assumes all array values are positive, if negative values allowed, then remove the "if(added <= target)" condition
            int next[] = Arrays.copyOf(indicesSoFar, indicesSoFar.length + 1);
            next[indicesSoFar.length] = arrayIndex;
            sum(arr, arrayIndex + 1, added, next);
        }
    }

    public static void main(String args[]) {
        new Recurse().sum(new int[] {12, 3, 4, 1, 6, 9}, 0, 0, new int[0]);
    }
}

That's all you need when you use the recursive approach.  If you add code to print out the results as shown:

public static void main(String args[]) {
        Recurse recurse = new Recurse();
        int arr[] = new int[] {12, 3, 4, 1, 6, 9};
        recurse.sum(arr, 0, 0, new int[0]);
        for(int solution[] : recurse.solutions) {
            StringBuilder vals = new StringBuilder();
            StringBuilder indices = new StringBuilder();
            for(int index : solution) {
                if(vals.length() > 0) {
                    indices.append(", ");
                    vals.append(" + ");
                }
                indices.append("arr[").append(index).append("]");
                vals.append(arr[index]);
            }
            System.out.println("Solution: " + indices + "; " + vals);
        }
    }

Then it gives you:

Solution: arr[0], arr[1], arr[5] 12 + 3 + 9

Now, according to your requirements you don't want multiple values used, but it's not clear to me if you are only talking about not using the same array element more than once (ie a[i] can appear just once for each i in each solution) or you are talking about using the same number more than once (ie the number x can appear only once in each solution), or you are talking about using the same set of added numbers more than once (the solution x,y,z can appear just once).  If you want to handle the other cases, such as to prevent solutions with duplicate values then just check the existing solutions before adding another.  Using a HashSet is ideal for this:

public class Recurse {
    static final int target = 24;
    static final int sumCount = 3;
    ArrayList<int[]> solutions = new ArrayList<int[]>();
    ArrayList<int[]> duplicates = new ArrayList<int[]>();
    HashSet<ArrayList<Integer>> solutionSet = new HashSet<ArrayList<Integer>>();

    public void sum(int arr[], int arrayIndex, int sum, int indicesSoFar[]) {
        //you can either include the current value or not

        //first we try skipping it
        if(indicesSoFar.length + arr.length - (arrayIndex + 1) >= sumCount) { //only skip if there are enough numbers left
            sum(arr, arrayIndex + 1, sum, indicesSoFar);
        }
        //now we try using it
        int val = arr[arrayIndex];
        int added = val + sum;
        if(indicesSoFar.length + 1 == sumCount) {//if we use it, it is the last
            if(added == target) {
                int next[] = Arrays.copyOf(indicesSoFar, indicesSoFar.length + 1);
                next[indicesSoFar.length] = arrayIndex;
                ArrayList<Integer> solution = new ArrayList<Integer>();
                for(int i : next) {
                    solution.add(arr[i]);
                }
                Collections.sort(solution);
                if(!solutionSet.contains(solution)) {
                    solutionSet.add(solution);
                    solutions.add(next);
                } else {
                    duplicates.add(next);
                }
            }
        } else if(added <= target) {//this assumes all array values are positive, if negative allowed, then no "if(added < target)" here
            int next[] = Arrays.copyOf(indicesSoFar, indicesSoFar.length + 1);
            next[indicesSoFar.length] = arrayIndex;
            sum(arr, arrayIndex + 1, added, next);
        }
    }

    public static void main2(String args[]) {
        new Recurse().sum(new int[] {12, 3, 4, 1, 6, 9}, 0, 0, new int[0]);
    }

    public static void main(String args[]) {
        Recurse recurse = new Recurse();
        int arr[] = new int[] {12, 3, 4, 1, 6, 3, 9};
        recurse.sum(arr, 0, 0, new int[0]);
        for(int i = 0; i < 2; i++) {
            String label = i == 0 ? "Solution: " : "Duplicate: ";
            ArrayList<int[]> solutionList = i == 0 ? recurse.solutions : recurse.duplicates;
            for(int solution[] : solutionList) {
                StringBuilder vals = new StringBuilder();
                StringBuilder indices = new StringBuilder();
                for(int index : solution) {
                    if(vals.length() > 0) {
                        indices.append(", ");
                        vals.append(" + ");
                    }
                    indices.append("arr[").append(index).append("]");
                    vals.append(arr[index]);
                }
                System.out.println(label + indices + "; " + vals);
            }
        }
    }
}

Which gives:

Solution: arr[0], arr[5], arr[6]; 12 + 3 + 9
Duplicate: arr[0], arr[1], arr[6]; 12 + 3 + 9


Calculating energy from mass and light speed I'm learning Java JDK 1.8 since one day and I'm using Java's methods to the first time. I have never used Java before because I'm a Python/Django developer.

I created a method which let to get energy in function of two parameters: mass and light speed. I would like to know if my method is well-written or if I made some mistakes about method, call, etc.

import java.util.Scanner;

public class methodes {

    public static double Energie(double m, double c)
      {
       return (double) (m*Math.pow(c, 2));
      }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int C = 300000 ;
        double m ;

        System.out.println("Valeur de la masse en kg : ");
        m = sc.nextDouble();

        double E = Energie(m,C);
        System.out.println("Pour " + m + " kg donné, l'énergie équivaut à " + E + " Joules");

    }

}

The implementation looks fine. Only the conventions on capital letters and spacing might be a bit different in the java community.

A class name always starts with a capital letter

public class Methodes

General utility classes are usually called Util but Methodes is fine depending on your own project preference. Especially when you're not native English it might change depending on who you work with, and how well you know the language.

Method names start with a lower case. And the opening { is placed at the same line as the method name

public static double energie(double m, double c) {
    return (double) (m*Math.pow(c, 2));
}

If you really want to place { at the line after the method name that's fine as long as you're consistent. So either do it always, or do it never. (big discussion in general about which is better, the community overal prefers on the same line).

Variables start with a lower case letter and are camel case, constants are written full uppercase and separated with _. Preferably use meaningful names, although m, C and e in this context are already pretty decent.

public class ExampleClass {
    //this is a constant. Since java 7 (?) you can also use _ in numbers to read easier.
    public static final int SPEED_OF_LIGHT = 300_000;

    public static int calculateEnergy(double mass) {
        return (double) (mass*Math.pow(SPEED_OF_LIGHT , 2));
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Valeur de la masse en kg : ");
        double mass = sc.nextDouble();

        double energy = calculateEnergy(mass);
        System.out.println("Pour " + mass + " kg donné, l'énergie équivaut à "
                          + energy + " Joules");
    }
}

Since you are a physicist, you should know the exact value of the speed of  light and that 300,000 km/s is way too much. You must use the correct values for constants.

Depending on what you use this speed of light constant for, you may have to take into account that this constant is only valid in vacuum.


Parse a simple key=value config file in C Write a program that should read a file formatted strictly like
  this below:

$ cat sample

bingo=2
bingo2=939
bingo3=text

  The left and right side of = are consecutively parameter name and
  its respective value. The values can be integer or strings. Each parameter is
  separated by a newline. The parameter name and its value will not be more than
  127 bytes.

This program is fed an input search token, and if found, parse_param_file() will fill the input arguments with string or integer value.

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

#define TEXT "sample"

/*
 * Function: parse_param_file
 * Arguments:
 * token    - param name that needs to be looked up
 * buf      - buffer for string value. Pass NULL if unwanted
 * buf_int  - buffer for integer value. Pass NULL if unwanted
 * filename - string formatted path to the file
 */
int parse_param_file(const char *token, char **buf, int *buf_int,
        const char *filename) {
    if (!token || (!buf && !buf_int)) {
        printf("%s: invalid args\n", __FUNCTION__);
        return 1;
    }
    FILE *f = fopen(filename, "r");
    if (f == NULL) {
        printf("%s: %s not found\n", __FUNCTION__, filename);
        return 1;
    }
    char *left = malloc(128);
    char *right = malloc(128);
    char *dlim_ptr, *end_ptr;
    char fbuf[256];
    while (fgets(fbuf, 256, f)) {
        dlim_ptr = strstr(fbuf, "=");
        end_ptr = strstr(dlim_ptr, "\n");
        strncpy(left, fbuf, dlim_ptr - fbuf);
        strncpy(right, dlim_ptr + 1, end_ptr - dlim_ptr - 1);
        if (strcmp(left, token) == 0) {
            /* Param found */
            if (buf != NULL)
                *buf = strdup(right);
            if (buf_int != NULL)
                *buf_int = atoi(right);
            fclose(f);
            free(left);
            free(right);
            return 0;
        }
    }
    fclose(f);
    printf("%s: Param not found in %s\n", __FUNCTION__, filename);
    free(left);
    free(right);
    return 1;
}

/* How to use parse_param_file() */
int main(void) {
    char *buf = malloc(128);
    int val = 0;

    /* Test 1 */
    if (parse_param_file("bingo2", NULL, NULL, TEXT))
        fprintf(stderr, "parse_param_file() failed\n");
    printf("buf : %s\n", buf);
    printf("int : %d\n", val);
    /* Test 2 */
    if (parse_param_file("bingo3242", NULL, &val, TEXT))
        fprintf(stderr, "parse_param_file() failed\n");
    printf("buf : %s\n", buf);
    printf("int : %d\n", val);
    /* You must clear *buf and val if you want to reuse them as args again */
    /* Test 3 */
    if (parse_param_file("bingo3", &buf, &val, TEXT))
        fprintf(stderr, "parse_param_file() failed\n");
    printf("buf : %s\n", buf);
    printf("int : %d\n", val);

    free(buf);
    return 0;
}

Interface
I'm not overly fond of the interface you've defined to the function. I think trying to combine reading integers and reading strings into a single function makes it more difficult to use. For most C code, I think the old guiding principle of UNIX ("do one thing, and do it well") provides excellent guidance. As such, I'd probably have two separate functions, one for reading a string, the other for reading a number.
I haven't tested it to be sure, but at first glance it also looks like if you ask to read a number, it does a poor job of signalling failure. For example, if your file has: foo=0 and you try to read foo as a number, it'll set the number to 0, and return 0. But if the file contains foo=Joe instead, it looks to me like it'll do exactly the same.
I'd prefer that if it couldn't convert the rest of the line after the = to a number that it return 1 to indicate that it has failed.
Memory Allocation
Since you only use our left and right inside of your function, and free them again before returning, there's probably no need to allocate them on the heap. You can just allocate them as local arrays, and use them. The obvious exception to this would be if you were targeting a tiny micro-controller that might well have less than 256 bytes available on the stack. In that case, however, you usually won't have a file system either, so the entire function becomes irrelevant.
Standard Library
I think judicious use of fscanf can simplify the code quite a bit.
For reading a string, it seems like the obvious interface would be to just return the value part of the pair, and if it's not found, return a NULL pointer:
char *read_string(FILE *file, char const *desired_name) {
    char name[128];
    char val[128];

    while (fscanf(file, "%127[^=]=%127[^\n]%*c", name, val) == 2) {
        if (0 == strcmp(name, desired_name)) {
            return strdup(val);
        }
    }
    return NULL;
}

When reading a number, we probably need something closer to your original interface, with a return value to indicate success/failure, and receive a pointer to an int where we write the value (if it's found):
int read_int(FILE *file, char const *desired_name, int *ret) {
    char *temp = read_string(file, desired_name);

    char *stop;
    *ret = strtol(temp, &stop, 10);
    int ret_val = stop == NULL || *stop != '\0';
    free(temp);
    return ret_val;
}

Note that as it stands right now, the return value reflects converting the entire remainder of the line (everything after the =) to the desired number. If part of it can be converted, that part will be written to the destination, but the return will still indicate failure. For example, if you had foo=1234abcd, attempting to read foo as a number would give you 1234, but return 1 because the abcd part couldn't be converted.
It would also be possible to simply ignore any trailing garbage, so foo=1234abcd would read the 1234 part, and return 0 to signal success:
int read_int(FILE *file, char const *desired_name, int *ret) {
    char *temp = read_string(file, desired_name);

    char *stop;
    *ret = strtol(temp, &stop, 10);
    int ret_val = stop == temp;
    free(temp);
    return ret_val;
}

In this case, we just need to check that at least one character was converted, in which case stop will have be advanced at least one character after the input.

Well I don't know exactly what strstr does, but I would've used strtok (string tokenizer) somewhere in the process as its purpose is to find delimiters and split strings there.


Greater on the right side in Java Given an array of integers, replace every element with the next
  greatest element (greatest element on the right side) in the array.
  Since there is no element next to the last element, replace it with
  -1.

  Input:

  The first line of input contains an integer T denoting the number of
  test cases. The first line of each test case is N,N is the size of
  array. The second line of each test case contains N input A[i].

  Output:

  Print the modified array.

  Constraints:

  1 ≤ T ≤ 50 1 ≤ N ≤ 100 1 ≤ A[i] ≤ 1000

  Example:

  Input:

2
6
16 17 4 3 5 2
4
2 3 1 9

  Output:

17 5 5 5 2 -1
9 9 9 -1

My approach:

/*package whatever //do not write package name here */

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Collections;

class GFG {

    private static int [] calcNewArr(int [] arr)
        {
            int [] ans = new int[arr.length];
            ans[0] = getNextBiggest(arr,1);
            for (int i = 1; i < arr.length - 1; i++)
                {
                    ans[i] = getNextBiggest(arr,i+1);
                }
            ans[ans.length - 1] = -1;
            return ans;
        }

    private static int getNextBiggest (int [] arr, int start)
        {
            int max = Integer.MIN_VALUE;
            for (int i = start; i < arr.length; i++ )
                {
                    if ( max < arr[i])
                        {
                            max = arr[i];
                        }
                }
            return max;
        }

    public static void main (String[] args) throws IOException {
       BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
       String line = br.readLine();

       int numTests = Integer.parseInt(line);
       String line2;
       String line3;
       int size;
       int [] arr;
       int [] result;

       for (int i = 0; i < numTests; i++)
        {
            line2 = br.readLine();
            size = Integer.parseInt(line2);
            line3 = br.readLine();
            String []inps = line3.split(" ");
            arr = new int[size];
            for (int j = 0; j < size; j++)
                {
                 arr[j] = Integer.parseInt(inps[j]);
                }
            result = calcNewArr(arr);
            for (int k = 0; k < size; k++)
                {
                    System.out.print(result[k] + " ");
                }
           System.out.println();
        }

    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?

2.Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?

Reference

You're doing a lot of work to parse the input. It seems like it'd be easier if you just used the Scanner class:

final Scanner sc = new Scanner(System.in);
final int numTests = sc.nextInt();

for (int i = 0; i < numTests; i++) {
    final int size = sc.nextInt();
    final int[] arr = new int[size];
    final int[] result;

    for (int j = 0; j < size; j++) {
        arr[j] = sc.nextInt();
    }
    result = calcNewArr(arr);
}

Your implementation runs at \$O(n^2)\$, however, this should be possible in \$O(n)\$ time if you just looked through the array right to left. If the question was asking for left to right on a reverse of the array, the problem would be pretty obvious since it's basically just iterate through and apply some simple rules:

The first element is -1
Copy the highest number seen so far into the position
If the value replaced is greater, set it as the largest number seen so far

So, I think something like this fulfills your calcNewArray:

int largest = -1;

for (int i = ans.length - 1; i >= 0; i--) {
    final int value = ans[i];
    ans[i] = largest;
    largest = Math.max(largest, value);
}

Obviously, comments can improve the code and there's some stylistic things that'll make most Java devs raise their eyebrows, but it's not a big deal. One thing, in particular, however, is to consistently use the following format for array types:

int[] arr = new int[size];

As opposed to int [] arr or int []arr

You can sort the original array first, and then sort the index number of the original array. In this way, we only need to compare the index number of the sorted array with the original data index number, and the required result can be obtained in one cycle.


Asynchronous SSLSTREAM Recently I have written an SslStream class asynchronously authenticate clients and receive message from them. I still would like anyone to suggest improvements for my code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.IO;

public class Wrapper
{
    public byte[] buffer;
    public SslStream sslStream;
    public object connector;
}

public class Sock
{
    private Dictionary<string, byte> Connections;
    public event Action<Wrapper> AnnounceNewConnection;
    public event Action<Wrapper> AnnounceDisconnection;
    public event Action<byte[], Wrapper> AnnounceReceive;
    private Socket _sock;

    private X509Certificate certificate = X509Certificate.CreateFromCertFile("exportedcertificate.cer");

    public Sock(int port)
    {
        try
        {
            Connections = new Dictionary<string, byte>();
            _sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _sock.Bind(new IPEndPoint(IPAddress.Any, port));
            _sock.Listen(500);
            _sock.BeginAccept(AcceptConnections, new Wrapper());
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

    private void AcceptConnections(IAsyncResult result)
    {
        Wrapper wr = (Wrapper)result.AsyncState;
        try
        {
            wr.sslStream = new SslStream(new NetworkStream(_sock.EndAccept(result), true));
            wr.sslStream.BeginAuthenticateAsServer(certificate, EndAuthenticate, wr);

            _sock.BeginAccept(AcceptConnections, new Wrapper());
        }
        catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); }
    }

    private void EndAuthenticate(IAsyncResult result)
    {
        Wrapper wr = (Wrapper)result.AsyncState;
        try
        {
            try { wr.sslStream.EndAuthenticateAsServer(result); }
            catch { }

            if (wr.sslStream.IsAuthenticated)
            {
                AnnounceNewConnection.Invoke(wr);
                if (wr.sslStream.CanRead)
                {
                    wr.buffer = new byte[5];
                    wr.sslStream.BeginRead(wr.buffer, 0, wr.buffer.Length, ReceiveData, wr);
                }
            }
            else
            {
                AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose();
            }
        }
        catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); }
    }

    private void ReceiveData(IAsyncResult result)
    {
        Wrapper wr = (Wrapper)result.AsyncState;
        try
        {
            AnnounceReceive.Invoke(wr.buffer, wr);

            SocketError error = SocketError.Disconnecting;
            int size = wr.sslStream.EndRead(result);
            if (error == SocketError.Success && size != 0)
            {
                wr.buffer = new byte[size];
                wr.sslStream.BeginRead(wr.buffer, 0, wr.buffer.Length, ReceiveData, wr);
            }
            else
            {
                wr.sslStream.Close();
                wr.sslStream.Dispose();
                AnnounceDisconnection.Invoke(wr);
            }
        }
        catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); wr.sslStream.Close(); wr.sslStream.Dispose(); }
    }
}

Also, how can I verify server authentication?

I can't comment on how secure your code is, however there are a couple of other problems that I would like to point out.

Clutter

Your using directives can be cut down to:

using System;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

Naming

Let me show you what I think of when I see a class called Sock:

You need to give that class a better name, for instance SslSocketMonitor. Actually, I don't know enough about your class to find a good name; use your brain to find a better one.
Let me show you what I think of when I see a class called Wrapper:

Because you are using it as a parameter to an event, this ought to be called something like SslSocketEventArgs, but certainly not Wrapper.
Decide on one naming convention and stick to it. You are using three different conventions for naming private fields:

private Dictionary<string, byte> Connections; // UpperCase
private Socket _sock;                         // _lowerCasePrefixed
private X509Certificate certificate;          // lowerCase

Your event names are nonstandard and not particularly clear.
Instead of AnnounceNewConnection try Connected,
instead of AnnounceDisconnection try Disconnected,
and instead of AnnounceReceive use ReceivedData.

API problems

.NET programmers are familiar with events. Therefore, it makes sense to implement the pattern properly:

SslSocketEventArgs (formerly Wrapper) needs to be derived from System.EventArgs
Instead of using Action:

public event Action<Wrapper> AnnounceNewConnection;
public event Action<Wrapper> AnnounceDisconnection;
public event Action<byte[], Wrapper> AnnounceReceive;

use the more expressive and conventional EventHandler<T>:

public event EventHandler<SslSocketEventArgs> Connected;
public event EventHandler<SslSocketEventArgs> Disconnected;
public event EventHandler<SslSocketEventArgs> ReceivedData;

It's not safe to directly invoke event handlers as they could easily be null. So define the following extension method to safely invoke the event handlers:

public static class EventHandlerExtensions
{
    public static void InvokeSafely<T>(this EventHandler<T> eventHandler,
                       object sender, T eventArgs) where T : EventArgs
    {
        if (eventHandler != null)
        {
            eventHandler(sender, eventArgs); // syntactic sugar for .Invoke
        }
    }
}

and replace all the usages:

Disconnected.InvokeSafely(this, wr);
Received.InvokeSafely(this, wr); // etc...

I'm not a fan of beginning listening in the constructor. It would be better to invoke that explicitly in a separate method.
There should be a way to cancel listening. Write a public method to enable this.

Programming errors

Your field Dictionary<string, byte> Connections is initialized but never used. Delete it.
You have lines like these spread throughout your code:

wr.sslStream.Close();
wr.sslStream.Dispose();

That scares me. What if you forgot to close it somewhere? It would be best to enclose all uses of the class in using statements where possible.
In ReceiveData, you make the following (constant) assignment:

SocketError error = SocketError.Disconnecting;

So the following condition will always be false:

if (error == SocketError.Success && size != 0)

What you are probably trying to do is instead of catch (Exception):

catch (SocketException e)
{
    // handle properly!
    Console.WriteLine(e.SocketErrorCode);
}

Very good, but this only error is double invoke 'SslStream()'

_sslStream = new SslStream(NetworkStream(socket.EndAccept(result), true));


Sending n requests in one time I need to test my new functionality by sending about 100 requests in one time.

public class MyTest {
    // ...

    @Test
    public void test() throws Exception {
        Runnable[] runners = new Runnable[size];
        Thread[] threads = new Thread[size];

        for(int i=0; i<threads.length; i++) {
            runners[i] = new RequestThread(i);
        }

        for(int i=0; i<threads.length; i++) {
            threads[i] = new Thread(runners[i]);
        }

        for(int i=0; i<threads.length; i++) {
            threads[i].start();
        }

        while (!threadsAreDead(threads)) {}
    }

    private boolean threadsAreDead(Thread[] threads) {
        for(int i=0; i<threads.length; i++) {
            if (threads[i].isAlive()) return false;
        }

        return true;
    }
}

class RequestThread implements Runnable {
    public RequestThread(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        try {
            b2b.execute(request);
        } catch (B2BException e) {
            // ...
        }
    }

}

Have you any idea how to optimize above code to send requests more 'in one time'?

Your test case looks relatively comprehensive in the sense that, yes, it fires off the 100 concurrent threads, but, you ask "how to make it more 'at the same time' ?"
There are two aspects I can suggest:

Use an ExecutorService
Use a CountDownLatch

ExecutorService
One of the novelties about the ExecutorService system is the concept of the Future, and it's foundation, the Callable class. The Callable interface is similar to the Runnable, except it can return a value, and throw an exception. These are two important differences.
The exception thrown in a Callable is trapped, and then re-thrown when the Future's get() method is called. This means that exceptions in remote threads can be collected in the calling thread.
In your case, throwing the exception is the most significant.
Consider the following code that sets up your threads appropriately:
@Test
public void test() throws Exception {
    ExecutorService threads = Executors.newFixedThreadPool(size);
    List<Callable<Boolean>> torun = new ArrayList<>(size);
    for (int i = 0; i < size; i++) {
        torun.add(new Callable<Integer>() {
            public Boolean call() throws B2BException {
                b2b.execute(request);
                return Boolean.TRUE;
            }
        });
    }

    // all tasks executed in different threads, at 'once'.
    List<Future<Boolean>> futures = threads.invokeAll(torun);

    // no more need for the threadpool
    threads.shutdown();
    // check the results of the tasks...throwing the first exception, if any.
    for (Future<Boolean> fut : futures) {
        fut.get();
    }

    //check the threadpool is now in fact complete
    if (!threads.isShutDown()) {
        // something went wrong... our accounting is off...
    }

}

OK, that is a better way of setting up the threads, and gets the exceptions to be thrown inside the test thread, rather than inside the remote threads.
CountDownLatch
If you are concerned that the threads should all be doing things more 'at the same time', and not worrying about start up time, etc. then consider using a count-down latch.
This device is set with a counter, and, when triggered, it will count down by one, and then lock, until all the counts are counted down.
You can use it in the above example code like:
@Test
public void test() throws Exception {
    ExecutorService threads = Executors.newFixedThreadPool(size);
    List<Callable<Boolean>> torun = new ArrayList<>(size);
    final CountDownLatch countdown = new CountDownLatch(size);
    for (int i = 0; i < size; i++) {
        toron.add(new Callable<Integer>() {
            public Boolean call() throws B2BException, InterruptedException {
                countdown.countDown();
                countdown.await();
                b2b.execute(request);
                return Boolean.TRUE;
            }
        });
    }

    // all tasks executed in different threads, at 'once'.
    List<Future<Boolean>> futures = threads.invokeAll(torun);

    // no more need for the threadpool
    threads.shutdown();
    // check the results of the tasks...throwing the first exception, if any.
    for (Future<Boolean> fut : futures) {
        fut.get();
    }

    //check the threadpool is now in fact complete
    if (!threads.isShutDown()) {
        // something went wrong... our accounting is off...
    }

}

The above system will set up all the threads, so they are all 'runnable', and then only when every thread is established and ready, will the locks be released.
You will still not get complete concurrent use, but it will/may be better having more threads start 'at once'.
Other....
You should consider using a custom ThreadFactory for the thread pool, like I suggested in this answer.

new Callable<Integer>() wont work. new Callable<Boolean>() is the right approach here.

for (int i = 0; i < threadPoolSize; i++) {
        torun.add(new Callable<Boolean>() {
            public Boolean call() throws InterruptedException {
                countdown.countDown();
                countdown.await();
                // Your implementation
                return Boolean.TRUE;
            }
        });
    }


Printing pyramids in C (CS50) I'm taking the CS50 course, and we're asked to create a program which takes an input (the total height of the pyramid) and outputs a pyramid of that height.
i.e Here’s how the program might work if the user inputs 8 when prompted:
$ ./mario
Height: 8
       #  #
      ##  ##
     ###  ###
    ####  ####
   #####  #####
  ######  ######
 #######  #######
########  ########

Here is my code:
#include <cs50.h>
#include <stdio.h>

void print_hashes(int width, int empty_space);

int main(void)
{
    // Get height input between ranges 1 to 8 inclusive
    int height;
    do
    {
        height = get_int("Height: ");
    }
    while (height < 1 || height > 8);
    // Loops through each row
    for (int row = 1; row <= height; row++)
    {
        // Prints the left part of the pyramid, we need to print empty spaces before printing the hashes, so
        // the width is equal to the height, amount of hashes printed is equal to the row, so amount of empty spaces is the width - row
        print_hashes(height, height - row);
        printf("  ");
        // Prints the right part of the pyramid, we don't need to print empty spaces before printing hashes, so
        // the width is equal to the amount of hashes, i.e the row and the amount of empty space is just 0
        print_hashes(row, 0);
        printf("\n");
    }
}

void print_hashes(int width, int empty_space)
{
    // Loops through the column in the row
    for (int column = 0; column < width; column++)
    {
        // Checks if there needs to be an empty space within that column, if so print a space and if not print a hash
        if (column < empty_space)
        {
            printf(" ");
        }
        else
        {
            printf("#");
        }
    }
}

I would like some feedback on my code and how I could improve it; things like readability, efficiency, etc.
Is my code easily understandable? Am I overdoing the comments? The reason I put a lot of comments is because in my experience, when looking at code days/weeks after writing it, I tend to forget what it does. So I wrote explanations so that I can easily understand the code in the future.
How do I improve the style, and are there any code conventions I'm not following? Can I optimize this to make it a faster process? Or maybe there's a better way to do the same thing? Basically, how do I improve my code?

The code can be structured better, so the code is more self-documenting.
Self-documenting code doesn't need as many comments, which makes it easier on everyone. Comments that aren't there can't be obsolete either.

Take input (height)
Output pyramid

Those are the only lines I want to see in main. The rest should be in functions.
You started out nicely by creating a print_hashes function, but we can do better. For example, the entire do ... while can be in a function.
int ask_height(void)
{
    // Get height input between ranges 1 to 8 inclusive
    int height;
    do
    {
        height = get_int("Height: ");
    }
    while (height < 1 || height > 8);
    return height;
}

Now, we can start the main program like this instead:
int main(void)
{
    int height = ask_height();

That turns 7 lines in main into 1 line in main. And since the function name is descriptive, the comments are almost obsolete.
We can do the same thing with the rest of the program.
void print_pyramid(int height)
{
    // Loops through each row
    for (int row = 1; row <= height; row++)
    {
        // Prints the left part of the pyramid, we need to print empty spaces before printing the hashes, so
        // the width is equal to the height, amount of hashes printed is equal to the row, so amount of empty spaces is the width - row
        print_hashes(height, height - row);
        printf("  ");
        // Prints the right part of the pyramid, we don't need to print empty spaces before printing hashes, so
        // the width is equal to the amount of hashes, i.e the row and the amount of empty space is just 0
        print_hashes(row, 0);
        printf("\n");
    }
}

And all of a sudden, we have nicely split-out code, each function has one and only 1 thing to do (you may want to read up on the SRP, the Single-responsibility principle).
Now your file starts like this:
#include <cs50.h>
#include <stdio.h>

int ask_height(void);
void print_hashes(int width, int empty_space);
void print_pyramid(int height);

int main(void)
{
    int height = ask_height();
    print_pyramid(height);
}

That's it. The rest is in functions. The function names can probably be further improved, but I'm quite awful at that myself. If you want to go a step further, you don't even need a height variable in main. This works too:
int main(void)
{
    print_pyramid(ask_height());
}

The rest is in functions, and functions can be re-used. Besides, should you ever want to call your program from an outside location, that's a lot easier now too.

printf is overkill for printing a single character - you could use putc instead.
However, printf provides some useful facilities that we can use to our advantage.  Look at this for inspiration:
#include <stdio.h>

int main(void)
{
    const int width = 8;
    for (int i = 0;  i < width;  ++i) {
        printf("%*s%.*s\n", width-i, "", i, "################");
    }
}

See how we can use printf() to pad the empty string with spaces, or truncate a longer string to a given width.
You'll want to read the printf documentation to see how . and * are used in format strings, and think of a way to ensure you have enough # characters to print.


Random walk with equal probability This method randomly increments or decrements (with equal probability) until either -3 or 3 are reached. I'd like to maintain printing the value of pos on each iteration, and printing the largest positive number max reached at the end of the loop. How can I improve this method using the Random() function? I know this sounds pretty ambiguous, but I'd like to know if I can make rand.nextInt(2) == 0 an easier condition to understand? Any suggestions/improvements are welcome!

public static void randomWalk() {
    Random rand = new Random();
    int pos = 0;
    int max = 0;
    System.out.println("position = " + pos);
    while (pos > -3 && pos < 3) {
        if (rand.nextInt(2) == 0) {
            pos++;
            if (pos > 0) {
                max = pos;
            }
        } else {
            pos--;
        }
        System.out.println("position = " + (int) pos);

    }
    System.out.println("max position = " + max);
}

There's a minor bug there:

        if (pos > 0) {
            max = pos;
        }

should test pos > max instead.

Use

max = Math.max(max, pos)

to make it shorter.

  I'd like to know if I can make rand.nextInt(2) == 0 an easier condition to understand?

Use rand.nextBoolean(). For a probability of exactly 50%, it's perfect.

For other probabilities, you can use

 rand.nextDouble() < probability

Another possibility is simply

pos += 2 * rand.nextInt(2) - 1;
max = Math.max(max, pos);

or

pos += rand.nextBoolean() ? 1 : -1;
max = Math.max(max, pos);

or

private static final int[] DELTAS = {+1, -1};

pos += DELTAS[rand.nextInt(DELTAS.length)];
max = Math.max(max, pos);

without any conditionals. You may consider it tricky, but it isn't. Obviously, my last solution shouldn't be used for such a simple case.

Concerning the computation of max it may be slightly less efficient since it gets executed even if the value decreases. But this doesn't matter unless you need to optimize heavily (your print is many orders of magnitude slower than this).

Expression

pos > -3 && pos < 3

Can be

Math.abs(pos) < 3

Random choice

Java Random had method for sampling boolean values nextBoolean

Bug

This line

if (pos > 0) {

do not give you

  the largest positive number max reached at the end of the loop

Improvement

You don't need to make loop at all. You need random generator that will provide 2 values at each iteration:

max positive number
3 or -3

This can be done using random in following way

long sample = Math.abs(rand.nextLong());
int pos, max;
if (sample % 2 == 0) {
    pos = 3;
    max = 3;
} else {
    pos = -3;
    max = int(sample % 3);
}


"Speed date" interview questions I'm learning Ruby and I would like to know if I have used the good syntax.
My script works, but can I simplify it and make it more elegant.

puts "Hello, what is youre name?"
name = gets.chomp

puts "Are you a boy? (yes/no)"
genre = gets.chomp

if genre == ("yes")
    puts "Do you like soccer #{name}? (yes/no)"
    foot = gets.chomp

        if foot == ("yes")
            puts "And beer? (yes/no)"
            biere = gets.chomp

                if biere == ("yes")
                    puts "Nice buddy!"
                else
                    puts "Too bad #{name}! But you like soccer!"
                end
        else
            puts "You're complicated #{name}!!!"
        end
else
    puts "Do you like romantics movies?"
    film = gets.chomp
end

I suggest defining an ask for free-form answers and a choose function for multiple-choice questions.  The choose function can perform validation.

You can use case-when instead of if-else.

def ask(msg)
  puts msg
  gets.chomp
end

def choose(msg, choices)
  loop do
    down_choices = choices.map(&:downcase)
    puts "#{msg} (#{choices.join('/')})"
    result = gets.chomp.downcase
    return result if down_choices.include?(result)
    puts "That answer is invalid"
  end
end

name = ask "Hello, what's you're name, dude?"
case choose "Are you a boy?", ["yes", "no"]
when "yes" # boy
  case choose "Do you like soccer #{name}?", ["yes", "no"]
  when "yes" # likes soccer
    case choose "And beer?", ["yes", "no"]
    when "yes" # likes beer
      puts "Nice buddy!"
    else # doesn't likes beer
      puts "Too bad #{name}! But you like soccer!"
    end
  else # doesn't like soccer
    puts "You're complicated #{name}!!!"
  end
else # girl
  ask "Do you like romantics movies?"
end

Note that nothing is done with the answer to the question, "Do you like romantics movies?".

You can use classes. I would be more thorough, but not simpler.

(Disclaimer: I'm a noob too, so don't take this as the way to do it. I got into some trouble here trying to make sure all the classes had the necessary variables. But it works!)

class Say
  def greeting
    print "Hello, what is youre name?  "
    @name = gets.chomp.capitalize
    @name = "John_Doe" if @name == ''

    print "Are you a boy? [Y/N]  "
    a_boy = gets.chomp.downcase
    gender = Logic.new.evaluate(a_boy)

    {:name => @name.downcase, :gender => (gender ? :male : :female)}
  end

  def response(topic, condition)
    case topic
    when :beer
      if condition == true
        puts "\nNice buddy!"
      else
        puts "\nToo bad #{@name}! But you like soccer!"
      end
    when :movies
      if condition == true
        puts "\nI figured as much..."
      else
        puts "\nWhat kind of girl doesn't like romantic movies?"
      end
    else
      puts "\nYou're complicated #{@name}!!!"
    end
  end

end

class DoYouLike
  attr_accessor :person

  def initialize(person)
    begin
      @person = person
      @name = @person[:name].capitalize
      #@gender = @person[:gender].capitalize
      @logic = Logic.new
    rescue
      @name = @person.capitalize
    end
  end

  def soccer?
    answer = nil

    while answer.nil?
      print "Do you like soccer #{@name}? [Y/N] "
      foot = gets.chomp.downcase

      answer = @logic.evaluate(foot)
    end

    answer
  end

  def beer?
    answer = nil

    while answer.nil?
      print "And beer? [Y/N] "
      beer = gets.chomp.downcase

      answer = @logic.evaluate(beer)
    end
    answer
  end

  def romantic_movies?
    answer = nil

    while answer.nil?
      print "Do you like romantics movies? "
      film = gets.chomp.downcase

      answer = @logic.evaluate(film)
    end
    answer
  end

end

class Logic
  def initialize
    @say = Say.new
  end

  def pass_var(you_like)
    @you_like = you_like
    @person = @you_like.person
  end

  def decision_tree
    if @person[:gender] == :male
      if @you_like.soccer?
        if @you_like.beer?
          @say.response(:beer, true)
        else
          @say.response(:beer, false)
        end
      else
        @say.response(:soccer, false)
      end
    else
      if @you_like.romantic_movies?
        @say.response(:movies, true)
      else
        @say.response(:movies, false)
      end
    end
  end

  def evaluate(answer)
    case answer
    when 'yes', 'y'
      true
    when 'no', 'n'
      false
    else
      puts "Please answer yes or no"
      nil
    end
  end
end

say = Say.new
person = say.greeting
you_like = DoYouLike.new(person)
logic = Logic.new
logic.pass_var(you_like)
logic.decision_tree


Windows application that draws India's flag I have written a small Windows application that draws India's flag in the window. I am very new to using Visual C++ and I want to understand if my code can be improved further.

#include "afxwin.h"
#include <math.h>

class CMyApp : public CWinApp
{
public:
    virtual BOOL InitInstance ();
};

class CMainWindow : public CFrameWnd
{
public:
    CMainWindow();
protected:
    afx_msg void OnPaint();
    DECLARE_MESSAGE_MAP();
};

CMyApp myAPP;

BOOL CMyApp::InitInstance()
{
     m_pMainWnd = new CMainWindow;
     m_pMainWnd->ShowWindow(m_nCmdShow);
     m_pMainWnd->UpdateWindow();
     return TRUE;
}

BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)
    ON_WM_PAINT()
    END_MESSAGE_MAP()

CMainWindow::CMainWindow ()
{
    Create(NULL,_T("India's Flag"), WS_OVERLAPPEDWINDOW );
}
void IndiaFlag(CDC &dc, int x, int y)
{
    dc.SetBkMode(TRANSPARENT);
    CRect rect;
    CPen pen(PS_SOLID, 1, RGB(0,0,0));
    CPen *oldPen = dc.SelectObject(&pen);
    {
        CBrush brush(RGB(255,130,0));
        CBrush *oldBrush = dc.SelectObject(&brush);
        dc.Rectangle(x,y,x+200,(y+50));
    }
    {
        CBrush brush(RGB(255,255,255));
        CBrush *oldBrush = dc.SelectObject(&brush);
        dc.Rectangle(x,(y+50),(x+200),(y+100));
        CPen pen2(PS_SOLID, 1,RGB(0,0,255));
        CPen *oldPen = dc.SelectObject(&pen2);
        dc.Ellipse((x+75),(y+50),(x+125),(y+100));
        double Nx,Ny;
        for (int angle=0;angle<360; angle+=15)
        {
            int angle2 = angle;
            double length = 25*(cos(double(angle2 *(3.14159265 / 180))));
            double len2 = 25*(sin(double(angle2 *(3.14159265 / 180))));
            int originX = (x+100);
            int originY = (y+75);
            Nx = originX + length;
            Ny = originY - len2;
            dc.MoveTo(originX,originY);
            dc.LineTo(Nx,Ny);
        }
    }
    {
        CBrush brush(RGB(34,139,34));
        CBrush *oldBrush = dc.SelectObject(&brush);
        dc.Rectangle(x,(y+100),(x+200),(y+150));
    }
}
void CMainWindow::OnPaint ()
{
    CPaintDC dc(this);
    IndiaFlag(dc, 150, 150);
}

In case you wondered, this is what the Indian flag looks like:

Thanks to your method IndiaFlag, I guess you're drawing a flag of India. The problem is, I don't know what it looks like. OK, I gonna google it.

It consists of 3 stripes: orange, white and green (top to bottom) and a sort of a wheel in the center. So, why don't you just say:

int const width = ...
int const height = ...
int const stripeHeight = height / 3;

drawStripe(0, 0, width, stripeHeight, Orange);
drawStripe(0, stripeHeight, width, 2 * stripeHeight, White);
drawStripe(0, 2 * stripeHeight, width, 3 * stripeHeight, Green);
drawWheel(width / 2, height / 2)

?

This code describes what your're drawing in fact. There are no brushes or pencils here, because if I ask you what the flag looks like, for sure you're not going to tell me about pencils and brushes and how GDI works. You'll probably say there are 3 stripes and a wheel in the center and that's what I want to hear.

So, why do you write the code like you're not going to tell anyone what happens in there?

Looking at your code, I'd say that all the names you give are terrible:

CBrush brush(RGB(255,255,255));

What does it mean? You're only going to have a single brush, so that's why you call it a "brush"? Nothing specific about it? If I see a name brush 20 lines later, do you expect me to remember it is white or any specific at all?

CBrush *oldBrush = dc.SelectObject(&brush);

An old brush? When I see oldBrush 20 lines later, do you expect me to remember what this brush is? Do YOU know why you need this oldBrush? I see no code where you switch back to it, so why do you even do it?

    dc.Rectangle(x,(y+50),(x+200),(y+100));

What is x here? Why y+50? What is 500? What is 200?

    CPen pen2(PS_SOLID, 1,RGB(0,0,255));

And once again, something called pen2. Is this pen any specific, or you're just telling me you're using 2 pens? Should I care? Etc.

P.S. Procedures/Functions/Methods describe actions, so their names are traditionally DoWhat. Your IndiaFlag violates the principle, because it says What.

IMO, this code seems ok!

To have a better clarity, you could create some functions for the drawing parts so that you India flag is made of smaller function. For example, for the inda flag, I would create a "drawColoredRectangle" and "drawCircleStar" just to make in clearer.

But for the rest, I think it's ok!


Socket chat room in Python This is a Python chat room that I've been working on and it enables to you to chat to other people on the same network through Python.

Server.py:

import socket
import sys

s = socket.socket()
host = socket.gethostname()
print(" server will start on host : ", host)
port = 8080
s.bind((host,port))
name = input(str("Please enter your username: "))
print("")
print("Server is waiting for incoming connections")
print("")
s.listen(1)
conn, addr = s.accept()
print("Recieved connection")
print("")
s_name = conn.recv(1024)
s_name = s_name.decode()
print(s_name, "has joined the chat room")
conn.send(name.encode())

while 1:
    message = input(str("Please enter your message: "))
    conn.send(message.encode())
    print("Sent")
    print("")
    message = conn.recv(1024)
    message = message.decode()
    print(s_name, ":" ,message)
    print("")

Client.py:

import socket
import sys

s = socket.socket()
host = input(str("Please enter the hostname of the server : "))
port = 8080
s.connect((host,port))
name = input(str("Please enter your username : "))
print(" Connected to chat server")

s.send(name.encode())
s_name = s.recv(1024)
s_name = s_name.decode()
print("")
print(s_name, "has joined the chat room ")

while 1:
    message = s.recv(1024)
    message = message.decode()
    print(s_name, ":" ,message)
    print("")
    message = input(str("Please enter your message: "))
    message = message.encode()
    s.send(message)
    print("Sent")
    print("")

I just wanted suggestions on how I can to improve this chatroom to make it better and faster. All suggestions will be greatly appreciated.

host = input(str("Please enter the hostname of the server : "))
...
message = input(str("Please enter your message: "))

can be changed to simply:

message = input("Please enter your message: ")
...
host = input("Please enter the hostname of the server : ")

since there is no need to cast a string to a string.

while 1:

is fine, but is more readable as:

while True:

Having print statements like the following:

print("")

is redundant. If you want an extra newline after a print statement; Add "\n" to the end of the preceding print statements to remove a function call, and reduce code clutter. E.G:

print("Sent\n")

This is more of a personal preference, but fstring formatting is more readable  than the following:

print(s_name, ":" ,message)

should be:

print( f"{s_name}: {message}" )

If we send two or more messages from any side at once, another side will receive only a single message at once rather than all.


Powerset (all subsets of a set) in Java I am trying to get a powerset (all subsets of a set) in Java. So my logic for that is:

A given set is one subset, so add so it as it is to result.
Remove each element of set from given set and we will get all the combinations for 1 element less. Add these results to final result.
Recursively find subsets of all sets from step 2 and add to result.

I tried searching for a similar solution on Stack Overflow but did not get one. Is this a clean way to implement it?

import java.util.*;

public class PowerSet {
    public static <E> Set<Set<E>> findPowerSet(Set<E> set){
        Set<Set<E>> ret = new HashSet<Set<E>>();
        ret.add(set);
        if(set.isEmpty()){
            return ret;
        }
        Iterator<E> it = set.iterator();
        while(it.hasNext()){
            Set<E> tmp = new HashSet<E>(set);   //create a copy of current set
            tmp.remove(it.next());              //remove current element from copy set
            ret.add(tmp);                       //add the remaining set to result
            ret.addAll(findPowerSet(tmp));      //recursively find subsets of copy set
        }
        return ret;
    }

    public static void main(String[] args) {
        Set<Character> set = new HashSet<Character>();
        set.add('a');set.add('b');set.add('c');
        System.out.println("Input set");        printSet(set);
        System.out.println("\nsub sets");
        findPowerSet(set).stream().forEach(PowerSet::printSet);
    }

    public static <E> void printSet(Set<E> set){
        StringBuilder sb = new StringBuilder(set.size()==0 ? "{}\n" :"{");
        Iterator<E> it = set.iterator();
        while(it.hasNext()){
            sb.append(it.next().toString())
            .append(it.hasNext()? ", " : "}\n");
        }
        System.out.print(sb.toString());
    }
}

if(set.isEmpty()){
            return ret;
        }

This is unnecessary. If the set is empty, the iterator will return false to the first hasNext(), and you'll go straight to the final return ret;.

Other than that, it seems like a simple, obviously correct, approach.

However, it is quite inefficient.

        Iterator<E> it = set.iterator();
        while(it.hasNext()){
            Set<E> tmp = new HashSet<E>(set);   //create a copy of current set
            tmp.remove(it.next());              //remove current element from copy set
            ret.add(tmp);                       //add the remaining set to result
            ret.addAll(findPowerSet(tmp));      //recursively find subsets of copy set
        }
        return ret;
    }

Suppose that we call it with a set of \$n\$ elements. The outermost call produces a set of \$2^n\$ subsets by taking the union of \$n\$ subresults, each of \$2^{n-1}\$ elements. So the outermost call discards as duplicates \$(n-2)2^{n-1}\$ subsets. But, of course, each of those recursive calls discarded \$(n-3)2^{n-2}\$ subsets from their subresults, etc.

This is why the typical simple implementation is to build up from the empty set.

An advanced implementation, which isn't always better but can reduce copying in some use cases, is to write a custom iterator which uses a Gray code to add or remove precisely one element in each call to next().

It's good - but it's not object-oriented! All your methods are static and I guess that's fine but it's a procedural way of thinking. We can't instantiate a PowerSet (in fact, we can but it's useless). In your example, once you recieve your set of sets, the entire semantic that it's a powerset has been lost.

What would be better is if a PowerSet object was useful for something. Perhaps we could implement Set or Collection. I suggest we implement Iterable. Because it's easy and I'm lazy.

public class PowerSet<E> implements Iterable<Set<E>>
{
    private final Set<Set<E>> sets;

    public PowerSet(final Set<E> input)
    {
        sets = findPowerSet(input);
    }

    private static Set<Set<E>> findPowerSet(final Set<E> set)
    {
        // Identical to your code, but now private! (also made the param final)
    }

    public void print()
    {
        // Now non-static! Implement it yourself :)
    }

    public Iterator<Set<E>> iterator()
    {
        return sets.iterator(); // Just delegate to our set of sets
    }
}

Our PowerSet object is now useful! We can use it like this:

PowerSet<Character> pset = new PowerSet<>(set);
pset.print();

or

for(Set<Character> foo : pset)
{
    foo.toArray();
}

I would also go one step further and use Collections.unmodifiableSet to enforce that a user cannot modify the powerset, thereby invalidating it.

You could provide a method to return the original set, if you wanted.


Repetitive days of the week code Could someone help me shorten this code, please?

while cd == "monday":
    if cp == "0":
        for v in mon.values():
            print(v)
            break
        break
    elif cp == "1":
        print(mon[1])
        break
    elif cp == "2":
        print(mon[2])
        break
    elif cp == "3":
        print(mon[3])
        break
    elif cp == "4":
        print(mon[4])
        break
    elif cp == "5":
        print(mon[5])
        break
    cd = False

while cd == "tuesday":
    if cp == "0":
        for v in tues.values():
            print(v)
            break
        break
    elif cp == "1":
        print(tues[1])
        break
    elif cp == "2":
        print(tues[2])
        break
    elif cp == "3":
        print(tues[3])
        break
    elif cp == "4":
        print(tues[4])
        break
    elif cp == "5":
        print(tues[5])
        break
    cd = False

You could simplify your code to look something like this (warning: I didn't test my code, so you should double-check to make sure it functions identically to the original)

days_map = {
    "monday": mon,
    "tuesday": tues
}

day = days_map[cd]
if cp == "0":
    print(day.values()[0])
else:
    print(day[int(cp)])

Several notes:

In your code, you use a while loop, but in every case, immediately break out of it, either by literally using break or by making the conditional false. What you want instead is an "if" statement. However, because the "if" statements are almost identical, you can simplify it completely by replacing it with a call to a dict.

(In case you aren't familiar with what dicts are, they're really nifty data structures that make life insanely easier. As you can see, they helped turn a large chunk of code into just 10 or so lines! Here's a link to CodeAcademy which gives an introduction to them))

I'm assuming that mon and tues are dicts of some kind -- I made another dict (days_map) to refer to them. This is a common technique in Python -- whenever you have a large amount of if and elif statements, check to see if you can somehow fold things into a dictionary so you can need to make only a single call.

Your for loop is also redundant. If you have a break immediately after, then it's equivalent to simply printing the first value.

I'm considering the code only for "monday"

while cd == "monday":
    for i in range(0, 6):
        if cp == str(i):
            print(mon[i])
            break
break
cd = false


Sorting integer array Please check this program that sorts an integer array.  It doesn't look very efficient.  Please tell me how to correct this.

int temp;
for(int i=0;i<nums.length-1;i++)
{
    if(nums[i]>nums[i+1])// if this is true, swap the value
    {
        temp=nums[i];
        nums[i]=nums[i+1];
        nums[i+1]=temp;
        i=-1;//If there is swap happen, loop will start again from 0th element
    }
}

Here are some links to sorting techniques:
bubble sort ,
insertion sort, merge sortWhat you're doing in your code isn't efficient. In the worst case scenario where the array is totally unsorted it'll take quite sometime to sort it the way you're doing it.

Your algorithm does not look like a viable array sorting algorithm.  Perhaps there are some data sets that it would be able to yield a correct result on, but I do not think it would yield correct results for arbitrary data sets.  Maybe it's alright ... without working through it all I can say is that it's an unusual solution.

Following is the pseudo-code for a conceptually very simple sorting algorithm called the "Delayed Replacement Sort" (or, perhaps more commonly, the "Selection Sort"):

Begin DELAYEDSORT
 For ITEM=1 to maximum number of items in list-1
    LOWEST=ITEM
    For N=ITEM+1 to maximum number of items in list
       Is entry at position N lower than entry at position LOWEST?
          If so, LOWEST=N
    Next N
    Is ITEM different from LOWEST
       If so, swap entry at LOWEST with entry in ITEM
 Next ITEM
End DELAYEDSORT

You should be able to easily adapt this pseudo-code into a Java method.  Note that this algorithm has two loops:

the outer loop is finished when the whole array has been sorted
the inner loop finds the "lowest" element in the portion of the array that is still unsorted.

After the inner loop, a check is made to see if a swap needs to be made.  It is this step that gives the algorithm its name; swapping is only done if it needs to be done to order the element indicated by the index of the outer loop.

Good luck.


Euler Problem 7 (finding the 10001st prime) in Powershell I am having issue making this code more efficient. The problem to be solved is as follows:

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
  see that the 6th prime is 13.

  What is the 10,001st prime number?

I'm looking to complete this in powershell. My code runs well up until about 4.8k primes.

$incNum1 = 1
$incNum2 = 2
$divisNum = 2 * $incNum2 - 1
$highestNum = 0
$k = 1
$nextNum = 2 * $incNum1 + 1

while($k -lt 6000){

    $upTo = [int][Math]::Ceiling(($nextNum / 2))

    $break = $false

    while($divisNum -lt $upTo){
        $modRes = $nextNum % $divisNum

        if($modRes -eq 0){

            $break = $true

            break
        }

        $incNum2++
        $divisNum = 2 * $incNum2 - 1
    }

    if(!$break){

        $highestNum = $nextNum

        echo $nextNum

        $k++
    }

    $incNum2 = 2
    $divisNum = 2 * $incNum2 - 1

    $incNum1++

    $nextNum = 2 * $incNum1 + 1
}

echo $highestNum

I'd start with

removing redundancy
measuring the time automatically
output to screen slows down, comment it out

depending on the speed of the computer used I get results of ~74..120 seconds.
Compared with 0.450 secs here with matlalb there IS potential to get better ;-)

## Q:\Test\2018\11\08\CR_207250.ps1

$StartTime = get-date
$PrimeNo = 10001

$incNum1 = 0
$highestNum = 0
$k = 1

while($k -lt $PrimeNo){
    $incNum2 = 2
    $divisNum = 2 * $incNum2 - 1
    $incNum1++
    $nextNum = 2 * $incNum1 + 1

    $upTo = [Math]::Ceiling(($nextNum / 2))
    $break = $false
    while($divisNum -lt $upTo){
        $modRes = $nextNum % $divisNum

        if($modRes -eq 0){
            $break = $true
            break
        }
        $incNum2++
        $divisNum = 2 * $incNum2 - 1
    }
    if(!$break){
        $highestNum = $nextNum
#        "{0}:{1}" -f $k,$nextNum
        $k++
    }
}

"## PrimeNo: {0} is {1} calculated in {2} seconds" -f $PrimeNo,$highestNum,
    ((Get-Date)-$StartTime).TotalSeconds

## PrimeNo: 10001 is 104743 calculated in 73,6911884 seconds
## PrimeNo: 10001 is 104743 calculated in 118,3481173 seconds

You could calculate the upper bound based on Prime Number Theory. Once you have this number you can implement the Sieve of Eratosthenes. One possible implementation is using a HashTable with every number from 2 to your upperbound as the key and a bool indicating prime status for the value. Iterate through the sieve marking each number. As you find a new prime increment a counter and when the counter matches n return that prime.


SPOJ FASHION challenge I just started attempting SPOJ problems. And I'm aware of Java using more memory and time compared to most of the other languages. But even some of the solutions in Java have better results than my accepted code. And it hurts!

Here is my accepted code for FASHION with TIME: 0.41 and MEM: 4284M.The best solution in Java for the same question has TIME: 0.04 and MEM: 1398M.

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int i = 0;
        Scanner sc = new Scanner(System.in);
        int testCases = sc.nextInt();
        while (testCases > 0) {
            int modelsWithMe = sc.nextInt();
            int[] men = new int[modelsWithMe];
            int[] women = new int[modelsWithMe];
            int hotnessSum = 0;
            for (i = 0; i < modelsWithMe; i++) {
                men[i] = sc.nextInt();
            }
            for (i = 0; i < modelsWithMe; i++) {
                women[i] = sc.nextInt();
            }
            Arrays.sort(men);
            Arrays.sort(women);
            for (i = 0; i < modelsWithMe; i++) {
                hotnessSum = hotnessSum + men[i] * women[i];
            }
            System.out.println(hotnessSum);
            testCases--;
        }

    }
}

I did see a few questions on performance, such as this and this. I am doing a few of it and some are not applicable for this solution's point of view. Here, maybe, I can read the entire line at once and split the string instead of calling nextInt each time and reduce I/O operations. What else can I do to reach the level of efficiency and speed as that of top answers? Best practices may be?

you can abuse the fact that

  All hotness ratings are (integers) on a scale of 0 to 10

Just keep track of how many men/women there are of each score. This looks something like this:

int[] men = new int[11];
for (i = 0; i < modelsWithMe; i++) {
    men[sc.nextInt()]++;
}

Then for the score you need to figure out how to combine the pairs given those frequency arrays.

int m = 10;
int w = 10;
while(m >= 0){
    while(men[m] == 0) {
        m--;
    }
    while(women[w] == 0){
        w--;
    }
    hotnessSum += m*w;
    men[m]--;
    women[w]--;
}

This calculation can still be optimised greatly. If you have 21 man score 10 and 30 women score 10 for example, you could add 21*10*10 to the total and reduce the frequencies of both by 21 instead of looping 21 times to achieve the same total. I'll leave turning this into code to you.

I'm not sure if this is exactly reason but - when I put the same code with changed name of class this with name Main have better time. It means when I used "public class Main" time was 0.06, and when I used "class MyName" it was 0.08


Generate n appointments in the next m months I work with an API where I need to write code to generate n appointment dates in the coming m months (from today). For the purpose, I write a Random date generator class provided. One condition is I need to use the java.sql.Date for the class.

import java.sql.Date;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Objects;
import java.util.Random;
public class RandomDate {

    private final Random random;

    private final Date currentDate;
    private final int months;

    public RandomDate(Random random, Date currentDate, int months) {

        this.random = random;
        this.currentDate = currentDate;
        this.months = months;
    }

    public Date getRangeEndDate() {

    Calendar calendar = new GregorianCalendar();

    calendar.setTimeInMillis(this.currentDate.getTime());
    calendar.add(Calendar.DATE, this.months * 30);

    return new Date(calendar.getTimeInMillis());
}

public Date generateRandomDate(Date endDate) {

    int start = (int) this.currentDate.toLocalDate().toEpochDay();
    int end = (int) endDate.toLocalDate().toEpochDay();

    long randomDay = start + random.nextInt(end - start);
    return Date.valueOf(LocalDate.ofEpochDay(randomDay));
}

}

I have an issue that within the code I use the time classes from 3 different packages (java.sql, java.time, and java.util). How can I write it more elegantly?

The essential part of your code is:

static LocalDate random(LocalDate start, int months, Random rnd) {
    LocalDate end = start.plusMonths(months);
    int days = (int) ChronoUnit.DAYS.between(start, end);
    return start.plusDays(rnd.nextInt(days + 1));
}

I have no idea why you need more code than this to express the idea.

I don't see any practical reason to use either the old and ugly java.util.Date or the even uglier java.util.Calendar or the inappropriate java.sql.Date (since this code has nothing to do with databases, let alone SQL). All you need are the classes from java.time, and java.time.temporal.

I updated the code with only using the java.time.LocalDate

public class RandomDate {

    private final LocalDate today;

    private final Random random;
    private final int months;

    public RandomDate(Random random, int months) {

        this.today = LocalDate.now();

        this.random = random;
        this.months = months;
    }

    public LocalDate getRangeEndDate() {

        LocalDate rangeEndDay = this.today.plusDays(this.months * 30);
        return rangeEndDay;
    }

    public LocalDate generateRandomDate(LocalDate endDate) {

        int start = (int) this.today.toEpochDay();
        int end = (int) endDate.toEpochDay();

        long randomDay = start + random.nextInt(end - start);
        return LocalDate.ofEpochDay(randomDay);
    }

    public LocalDate getToday() {
        return today;
    }

    public Random getRandom() {
        return random;
    }

    public int getMonths() {
        return months;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof RandomDate)) return false;
        RandomDate that = (RandomDate) o;
        return getMonths() == that.getMonths() &&
                Objects.equals(getToday(), that.getToday()) &&
                Objects.equals(getRandom(), that.getRandom());
    }

    @Override
    public int hashCode() {

        return Objects.hash(getToday(), getRandom(), getMonths());
    }

    @Override
    public String toString() {
        return "RandomDate{" +
                "today=" + today +
                ", random=" + random +
                ", months=" + months +
                '}';
    }

}


Python terminal animation Is there a better way of creating this terminal animation without having a series of conditional statements (i.e. if ... elif ... elif...)?

import sys, time
count = 100
i = 0
num = 0

def animation():
    global num
    if num == 0:
        num += 1
        return '[=      ]'
    elif num == 1:
        num += 1
        return '[ =     ]'
    elif num == 2:
        num += 1
        return '[  =    ]'
    elif num == 3:
        num += 1
        return '[   =   ]'
    elif num == 4:
        num += 1
        return '[    =  ]'
    elif num == 5:
        num += 1
        return '[     = ]'
    elif num == 6:
        num += 1
        return '[      =]'
    elif num == 7:
        num += 1
        return '[      =]'
    elif num == 8:
        num += 1
        return '[     = ]'
    elif num == 9:
        num += 1
        return '[    =  ]'
    elif num == 10:
        num += 1
        return '[   =   ]'
    elif num == 11:
        num += 1
        return '[  =    ]'
    elif num == 12:
        num += 1
        return '[ =     ]'
    elif num == 13:
        num = 0
        return '[=      ]'

while i < count:
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation())
    sys.stdout.flush()
    time.sleep(0.2)

You can build up the string like this:

def animation(counter, length):
    stage = counter % (length * 2 + 2)
    if stage < length + 1:
        left_spaces = stage
    else:
        left_spaces = length * 2 - 1 - stage
    return '[' + ' ' * left_spaces + '=' + ' ' * (length - left_spaces) + ']'

for i in range(100):
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation(i, 6))
    sys.stdout.flush()
    time.sleep(0.2)

Alternatively store the animation strings in a tuple or list:

animation_strings = ('[=      ]', '[ =     ]', '[  =    ]', '[   =   ]',
                     '[    =  ]', '[     = ]', '[      =]', '[      =]',
                     '[     = ]', '[    =  ]', '[   =   ]', '[  =    ]',
                     '[ =     ]', '[=      ]')
for i in range(100):
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation_strings[i % len(animation_strings)])
    sys.stdout.flush()
    time.sleep(0.2)

You can replace the animation function with cycle from itertools:

import sys, time
from itertools import cycle
animation = cycle('[=      ]', '[ =     ]', '[  =    ]', '[   =   ]',
                  '[    =  ]', '[     = ]', '[      =]', '[      =]',
                  '[     = ]', '[    =  ]', '[   =   ]', '[  =    ]',
                  '[ =     ]', '[=      ]')
# alternatively:
# animation = cycle('[' + ' ' * n + '=' + ' ' * (6 - n) + ']'
#                   for n in range(7) + range(6, -1, -1))

for _ in range(100):
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation.next())
    sys.stdout.flush()
    time.sleep(0.2)

Finally, you could make your own generator function.

def animation_generator(length):
    while True:
        for n in range(length + 1):
            yield '[' + ' ' * n + '=' + ' ' * (length - n) + ']'
        for n in range(length + 1):
            yield '[' + ' ' * (length - n) + '=' + ' ' * n + ']'

animation = animation_generator(6)
for _ in range(100):
    sys.stdout.write('\b\b\b')
    sys.stdout.write(animation.next())
    sys.stdout.flush()
    time.sleep(0.2)

EDIT: made the above suggestions less reliant on global variables

A liitle modification:
*Also reduce the size of python shell window
import sys, time
count = 100
i = 0
num = 0

def animation():
    global num
    if num == 0:
        num += 1
        return '[=      ]'
    elif num == 1:
        num += 1
        return '[ =     ]'
    elif num == 2:
        num += 1
        return '[  =    ]'
    elif num == 3:
        num += 1
        return '[   =   ]'
    elif num == 4:
        num += 1
        return '[    =  ]'
    elif num == 5:
        num += 1
        return '[     = ]'
    elif num == 6:
        num += 1
        return '[      =]'
    elif num == 7:
        num += 1
        return '[      =]'
    elif num == 8:
        num += 1
        return '[     = ]'
    elif num == 9:
        num += 1
        return '[    =  ]'
    elif num == 10:
        num += 1
        return '[   =   ]'
    elif num == 11:
        num += 1
        return '[  =    ]'
    elif num == 12:
        num += 1
        return '[ =     ]'
    elif num == 13:
        num = 0
        return '[=      ]'

while i < count:
    sys.stdout.write('\b\b\b\n')
    sys.stdout.write(animation())
    sys.stdout.flush()
    time.sleep(0.2)


Destructor for a linked list The full code is located here: https://gist.github.com/4521540

It's a dummy List in C++. My concern is with freeing up memory.
It doesn't crash when I run my code. It looks like my if/else covers everything.

It starts by deleting the second item if there is. That's what the while loop does.
If there is only one present (or left with one), delete startNode.

startNode is a pointer points to the first item in the list.
endNode always points to the last item in the list.

Am I deleting the pointer or the underlying object?

I do mostly Python. Last time I wrote a serious C++ homework was about 2 years ago in my algorithm class so I really can't remember everything off my head.

~List()
{
    // there is at least one item
    if(startNode != 0)
    {
        // release memory starting from the second item
        ListNode *current, *soon;
        current = this->startNode->next;
        while(current != 0)  // if there are at least two items
        {
            /* When there is no more items after current,
             * delete current and leave.
             * Otherwise, free up current and move on to
             * the next item.
             */
            if(current->next != 0)
            {
                soon = current->next;
                delete current;
                current = soon;
            }
            else
            {
                delete current;
                break;
            }

        }
    }

    delete this->startNode;
    delete this->endNode;
}

Also, do I need to delete the myList in my main program? I think when I exit the program, the destructor is automatically called.

First, to answer your questions about new/delete: Everything you new, you must delete at some point, or you leak memory. When you new, you are given a pointer to the object that has been allocated. Similarly, when you use delete, you must use a pointer to that same object, and the memory that was allocated will be freed. After doing this, the pointer will be pointing at freed memory and you should not delete this again. It doesn't matter where you use new, in main() or otherwise, you need to delete it at some point.

Now to your code: Your code will double-delete either the first node when the list size is 1, or the last node, when the list size is greater than 1. Double deletes cause undefined behaviour including crashes.

Let's look at list of size 1 first. Your while loop won't be entered, and you basically skip down to the end where you do

delete this->startNode;
delete this->endNode;

Since startNode and endNode should both be pointing to the only node in the list, it will get deleted twice!

If you have a list of more items, the loop will delete every item except the first. Then the last two statements occur. In this case, this->endNode will be the original end of the list (since you never alter it here) and so it will be deleted twice.

Here is a simpler version that just deletes every node, starting from the first.

~List
{
    ListNode* current = startNode;
    ListNode* next;

    while (current != NULL) {
        next = current->next;
        delete current;
        current = next;
    }
}

A cleaner way would be to go iteratively through the list.

I would do something like:

~List()
{
    if(startNode == NULL)
       return;

    if(startNode->Next != 0)
    {
         delete this->startNode->Next;
    }
    delete this->startNode;
}

This will go through your list, and startNode->Next will be the new startNode (this), thus it should delete the whole list just fine.