javascript – FizzBuzz solution – Code Review Stack Exchange

I’m preparing for junior developer interviews and am trying to come up with a more interesting/versatile solution to FizzBuzz than I’ve done in the past. Any ideas of how I might DRY this up? Is it too difficult to read?

const isMultiple = (num, mod) => {
    return num % mod == 0
}

const fizzBuzz = (range, array) => {
    return (...Array(range)).fill('').map((el,i) => {
    i ++
    for (let element of array) { 
        isMultiple(i,element.number) && (el += element.name) 
    }
        if (el == "") el = i
    return el
  });
}

const objArr = (
  {
    number: 3, 
    name: "Fizz"
  },
  {
    number: 5, 
    name: "Buzz"
  }
)

console.log(fizzBuzz(100,objArr))

Bash script whitespace compliant – Code Review Stack Exchange

I have an huge amount of file to organize, they are a JPG files in an absurd folders structure.

I need to move all files from its actual position to an organized folder structure, saving its actually position as EXIF comment because in path there information to preserve.

For example I have a file with this path:

/OLD ARCHIVE/ORGANIZATION 1/1 FANTASTIC EVENT/1995 PIPPO does something.jpg

The destination will be something like: Archive Digital/AA/1995/CCC_BB_000002.jpg

My idea is to run the script from the OLD ARCHIVE/ path in order to have all information in the fname var. Then extract information from fname var and put them in exif (and in path), at the end, move the file logging what I’m doing.

I am writing this in bash, it was working but had some problem with whitespace management, so I tried to make it whitespace compliant…but it is not working anymore.

Can someone help me?

Thanks in advance.

#!/bin/bash
#Parametri: CartellaOriginale CartellaOutput Prefisso NumeroIniziale Keywords
filenamePrefix="$3"
filenameNumber=$(printf "%05d" $4)
data=$(date +%F)
filelog="fileMovedLog_$data.txt"
CommonKeywords="$5"
echo "DEV Working on $1"
echo "DEV output folder $2"
echo "DEV filename start $filenamePrefix$filenameNumber"
echo "$1/$filelog"
echo "Backup in ${1%/}_BAK/"
#echo "$data"
read -p "Press enter to continue"
echo 'Backup in corso'
#cp -R "$1" "${1%/}_BAK/"
echo 'Backup terminato, inizio elaborazione'
#mkdir "$2"
touch "$1/$filelog"
find "$1" -name "*.jpg" -or -name "*.JPG" -type f -not -path "*_BAK"| while read fname; do
    echo "$fname"
#Chiedo l'anno
    forseAnno=$(grep -oP  '(?<!d)d{4}(?!d)' <<< "$fname")
    if ( -z "$forseAnno" )
    then 
        forseAnno='ND'
    fi
    echo "Inserire cartella anno dove inserire la foto oppure lasciare vuoto se $forseAnno"
    read annoIn </dev/tty

    if ( -z "$annoIn" )
    then #Se input è vuoto
        anno="$forseAnno"
    else #ho input, metto lì.
        anno="$annoIn"
    fi
    
    #echo "$anno"   
#Keyword per Lightroom
    #Estraggo alcune possibili KeyWord
    string=${fname,,}
    extraKey=''
    if grep -q 'palio' <<< "$string"; then
        extraKey=',palio del niballo'
    fi
    if grep -q 'dama' <<< "$string"; then
        extraKey="${extraKey},dama"
    fi
    if grep -q 'not' <<< "$string"; then
        extraKey="${extraKey},nott de biso"
    fi
    if grep -q 'cavaliere' <<< "$string"; then
        extraKey="${extraKey},cavaliere"
    fi
    if grep -q 'bigorda' <<< "$string"; then
        extraKey="${extraKey},bigorda"
    fi
    if grep -q 'corteo' <<< "$string"; then
        extraKey="${extraKey},corteo"
    fi
    if grep -q 'paggi' <<< "$string"; then
        extraKey="${extraKey},paggi"
    fi
    echo "$extraKey"
    read -e -p "Correggere le Keywords: " -i "$anno,$CommonKeywords$extraKey" keyword </dev/tty
    suffix=$(printf "%05d" $filenameNumber)
    "exiftool -p -Keywords="${keyword}" ${fname} -overwrite_original"
#Registro il precedente nome file nella descrizione
    "exiftool -p -Description+="ERA: ${fname}" $fname -overwrite_original"    
    
#Sistemo la CreateDate
    "exiftool -wm cg -CreateDate="${anno}:01:01 00:00:00" -overwrite_original ${fname}"
    if ( $? -ne 0 ) #avevo già una data
    then
        datafile=("exiftool -S -createdate $fname")
        while true 
        do 
            if ( $anno -lt 2021 ) #la scrittura della data in EXIF la faccio solo se è un anno minore di 2021. Se ho messo 5060 per indicare anni 50-60 non lo metto
            then 
                    read -e -p "Sovrascrivere la data $datafile con $anno?(Yes/No/Vuoto)" -i "Y" yn </dev/tty
            else
                    read -e -p "Sovrascrivere la data $datafile con $anno?(Yes/No/Vuoto)" -i "N" yn </dev/tty
            fi
            case $yn in 
                (Yy)* ) "exiftool -p -CreateDate=${anno}:01:01 00:00:00' -overwrite_original";break;;
                (Nn)* ) break;; #Non fo una sega
                (0123456789)(0123456789)(0123456789)(0123456789)* ) "exiftool -p -CreateDate=${yn}:01:01 00:00:00 -overwrite_original";break;;
                * ) echo "Inserire Y(es)/N(o) o l'anno";;
            esac
        done
    fi
#Procedo allo spostamento e logging
    echo "Sposto ${fname} ${2}/${anno}/$filenamePrefix$suffix.jpg"
    read -p "Press enter to continue"
    mv "$fname" "$2/$anno/$filenamePrefix$suffix.jpg"
    echo "${fname}; $filenamePrefix$suffix.jpg" >>$1/$filelog
    ((filenameNumber++))
    echo ""
done
echo "Completato";


```

Sudoku Graph in Julia – Code Review Stack Exchange

I’m building a graph coloring sudoku solver in Julia, so the first thing i’m tackling is the graph implementation. I have the bare structure completed, meaning I can create the graph with all of the right edges.

In terms of efficiency, it’s currently at

@timev s = SudokuGraph(3);

> 0.001573 seconds (16.05 k allocations: 1013.641 KiB)
> elapsed time (ns): 1573000
> bytes allocated:   1037968
> pool allocs:       16050
> non-pool GC allocs:1
> malloc() calls:    3
> realloc() calls:   1

But to be honest I’m not sure if this is good or bad.

After the initial writing and refactoring, this is what it looks like. I’d appreciate tips on making it more idiomatic/proper Julia or efficient.

(Note, in set_cell! I changed // to / for the sake of not breaking the syntax highlighting here)

#Pkg.add("Combinatorics")
using Combinatorics

mutable struct Node
    row::Int
    col::Int
    cell::Int
    value::Int

    function Node(coords::Tuple{Int,Int})
        row, col = coords
        return new(row, col, 0, 0)
    end
end

function set_cell!(node::Node, size::Int)
    col = node.col - 1
    row = node.row - 1
    node.cell = 1 + floor(((col / size) + row) - (row % size))
end

function get_coordinates(node::Node)::Tuple{Int,Int,Int}
    return (node.row, node.col, node.cell)
end

function are_adjacent(nodes::Tuple{Node,Node})::Bool
    a, b = get_coordinates.(nodes)
    return any(a .== b)
end

struct Edge
    nodes::Tuple{Node,Node}

    function Edge(nodes::Tuple{Node,Node})
        return new(nodes)
    end
end

function nodes_to_edges(nodes::Vector{Node})::Vector{Edge}
    return Edge.(Tuple.(filter(are_adjacent, Tuple.(combinations(nodes, 2)))))
end

mutable struct SudokuGraph
    nodes::Vector{Node}
    edges::Vector{Edge}

    function SudokuGraph(size::Int)
        cols = size^2
        space = Iterators.product(1:cols, 1:cols)
        nodes = Node.(reshape((space...), cols^2))
        set_cell!.(nodes, fill(size))
        edges = nodes_to_edges(nodes)

        return new(nodes, edges)
    end
end

Thank you!

Rewrite php script – Code Review Stack Exchange

I have written one script in PHP which is defined here:

Click Here to See Code

I am improving the code quality and readability. For example splitting it into multiple functions, use PHP predefined variables, use PSR naming conventions etc.

class nextcrontime{
//Get Single argument passed
function calculate_next_cron(){
    If(isset($_GET('time')) && !empty($_GET('time'))){
        //Read config.txt file
        $read_txt_file = fopen ("config.txt", "r");
        $splitime = explode(":", $_GET('time'));
        // Loop Content from config.txt line by line and perform required actions
        while (!feof ($read_txt_file)) {
            $line = fgets($read_txt_file, 4096);
            $list = explode(" ", $line);
            
            if($list(0) != '*' && $list(1)=='*'){
                $newtime = $splitime(0).":".$list(0);
                if(strtotime($newtime) >=  strtotime($_GET('time'))){
                    echo $newtime." ".'Today'." ".$list(2);
                }else{
                    $time = date('Y-m-d H:i', strtotime($newtime) + 60*60);
                    if (date("Y-m-d") > $time) {
                        echo date("H:i", strtotime($time))." ".'Today'." ".$list(2);
                    }else{
                        echo date("H:i", strtotime($time))." ".'Tomorrow'." ".$list(2);
                    }
                }
            }
        }else{
        echo "Please Pass Time in HH:MM format. Example > php-cgi -f Index.php time=16:10.";
        return;
    }
    //Close File Handler
    fclose ($read_txt_file);
}}}