I'm trying to convert this javascript password score function to swift, so I can use the same logic on mobile as we do on web. Here is the JS fiddle with the code to test:
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "Strong";
if (score > 60)
return "Good";
if (score >= 30)
return "Weak";
return "";
}
I'm having an issue in converting this part:
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
I've tried to create a dictionary to store the character as key and then increment the value with each occurrences of that key, but it's not working as expected.
let string = "Testing22!"
var score = 0
var dictionary = [String.Element: Int]()
for x in string {
let value = dictionary[x] ?? 0
dictionary[x] = value + 1
score += 5 / value
}
print(dictionary) //["s": 1, "T": 1, "g": 1, "2": 2, "n": 1, "i": 1, "!": 1, "t": 1, "e": 1]
print(score)
I'm also not sure of the most efficient way to handle the regex checks for the bonus points section.
I'd port it over to swift like this, I'm sure there are some improvements to be made, but thats a quick conversion:
func scorePassword(_ inputString: String?) -> Double {
var score: Double = 0
guard let string = inputString, !string.isEmpty else { return score }
// award every unique letter until 5 repetitions
let countedSet = NSCountedSet()
for x in string {
countedSet.add(x)
score += 5.0 / Double(countedSet.count(for: x))
}
// bonus points for mixing it up
let variations = [
"^(?=.*[0-9]).*$",
"^(?=.*[a-z]).*$",
"^(?=.*[A-Z]).*$",
"^(?=.*\\W).*$"
]
var variationCount: Double = 0
for check in variations {
print(string.testRegex(check))
variationCount += string.testRegex(check) ? 1 : 0
}
score += (variationCount - 1) * 10
return floor(score)
}
func checkPassStrength(_ inputString: String?) -> String {
let score = scorePassword(inputString)
if score > 80 {
return "Strong"
} else if score > 60 {
return "Good"
} else if score > 30 {
return "Weak"
}
return ""
}
extension String {
func testRegex(_ regex: String) -> Bool {
let test = NSPredicate(format: "SELF MATCHES %#", regex)
return test.evaluate(with: self)
}
}
You can run js code inside Swift and get the result from it, so you can share code between platforms.
let jsSource = """
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /W/.test(pass),
}
variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "Strong";
if (score > 60)
return "Good";
if (score >= 30)
return "Weak";
return "";
}
"""
let context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("scorePassword")
let result = testFunction?.call(withArguments: ["1234"])
print("js result : " , result )
Note; I edited the part "digits: /\d/.test(pass)" to "digits: /d/.test(pass)"
Related
I implemented select sort in Flutter and in SwiftUI. I made the implementations as similar as possible.
Swift:
func selectSort(list: inout [Double]) -> [Double] {
for i in 0..<list.count {
var minElPos = i;
for j in (minElPos + 1)..<list.count {
if list[j] < list[minElPos] {
minElPos = j;
}
}
// swap
let temp = list[i];
list[i] = list[minElPos];
list[minElPos] = temp;
}
return list;
}
// Measuring time
func generateRandomList(size: Int) -> [Double] {
var res = Array<Double>(repeating: 0.0, count: size)
for i in 0..<size {
res[i] = Double.random(in: 0...1)
}
return res;
}
var arrayToTest: [Double] = generateRandomList(size: 8000);
let startingPoint = Date()
selectSort(list: &arrayToTest);
let time = startingPoint.timeIntervalSinceNow * -1;
Flutter:
class SelectSort {
static List<double> call(List<double> list) {
for(int i = 0; i < list.length - 1; i++) {
int minElPos = i;
for(int j = minElPos + 1; j < list.length; j++) {
if(list[j] < list[minElPos]) {
minElPos = j;
}
}
// swap
double temp = list[i];
list[i] = list[minElPos];
list[minElPos] = temp;
}
return list;
}
}
// Measuring time
class Utils {
static List<double> generateRandomList(int nbOfElements) {
var random = new Random();
List<double> res = List(nbOfElements);
for (var i = 0; i < nbOfElements; i++) {
res[i] = random.nextDouble();
}
return res;
}
}
List<double> arrayToTest = Utils.generateRandomList(8000);
final stopwatch = Stopwatch()..start();
SelectSort.call(arrayToTest);
stopwatch.stop();
int time = stopwatch.elapsedMilliseconds;
I measured the execution time for an array of random numbers. The array size is 8000. Flutter needs 0.053s and SwiftUI needs 0.141s. Does anyone have a clue why flutter as a hybrid framework has better performance than a native solution?
Both apps were run in release mode on a physical device.
I'm trying to get outline working with a custom language in VScode. I have the below code but I feel like it is slow because of the way I find a range in class. Are there better ways to find the range and assign children. I've thought about just keeping track of the depth of the brackets and assigning all functions/methods/classes in higher depths into the last item of previous depth.
It was based off of this answer.
class JSLDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
public provideDocumentSymbols(document: vscode.TextDocument,
token: vscode.CancellationToken): Thenable<vscode.DocumentSymbol[]> {
return new Promise((resolve, reject) => {
var symbols: vscode.DocumentSymbol[] = [];
var depth = 0;
for (var i = 0; i < document.lineCount; i++) {
var line = document.lineAt(i);
var txt = line.text;
var ltxt = txt.toLowerCase();
let open_brackets = ltxt.match(/\(/g) || [];
let close_brackets = ltxt.match(/\)/g) || [];
// console.log(ltxt)
// console.log(open_brackets, close_brackets)
//console.log(i, open_brackets.length, close_brackets.length)
depth += open_brackets.length - close_brackets.length;
//console.log(depth);
if (ltxt.includes("define class(")) {
let sname = txt.trim().substr(14, txt.trim().length - 16); //this is hard coded right now but it's kind of working
let detail = "ARGS:x, y returns z";
let start_pos = new vscode.Position(i, 0);
let n_bracket = 1;
let i_char = 0;
//let children: vscode.DocumentSymbol[] = []
let ds = new vscode.DocumentSymbol(sname, detail, vscode.SymbolKind.Class, line.range, line.range);
for(var i_line = i; n_bracket > 0; i_line++){
let class_line = document.lineAt(i_line);
let mtxt = class_line.text;
let ic;
if(i == i_line) ic = 16;
else ic = 0;
for(i_char = ic; i_char < mtxt.length; i_char++){
if(mtxt[i_char] === "(") n_bracket++;
else if(mtxt[i_char] === ")") n_bracket--;
if(n_bracket === 0) break
}
if (/(\w[\w\d\s]*)=\s*method\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i.test(mtxt)) {
let result = mtxt.match(/(\w[\w\d\s]*)=\s*method\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i)!;
let mname = result[1].trim();
let m_details = ""
if(result.length == 3){
m_details = result[2].trim();
}
ds.children.push(new vscode.DocumentSymbol(mname, m_details, vscode.SymbolKind.Method, class_line.range, class_line.range));
}
if(n_bracket === 0) break
}
let end_pos = new vscode.Position(i_line, i_char);
let rng = new vscode.Range(start_pos, end_pos);
ds.range = rng;
//ds.children = children;
symbols.push(ds);
}
else if (/(\w[\w\d\s]*)=\s*function\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/.test(ltxt)) {
let result = txt.match(/(\w[\w\d\s]*)=\s*function\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i)!;
let sname = result[1].trim();
let detail = "";
if(result.length == 3){
detail = "(" + result[2].trim() + ")";
}
symbols.push(new vscode.DocumentSymbol(sname, detail, vscode.SymbolKind.Function, line.range, line.range));
}
}
resolve(symbols);
});
}
}
I am practicing my array form of data structure with swift.
I made a class "student"
and there are functions like display() and delete()
However, the application is not working.
There is an error message that
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, sub code=0x0).
I think this error is about "optional" problem.
Here is my code.
class student
{
var studentArray = [[String]?]()
var numberOfStudents : Int = 10;
func display()
{
for (var i = 0; i < numberOfStudents ; i++)
{
print("{");
for (var j = 0; j < 2; j++)
{
print(studentArray[i]![j] + " ");
}
print("}");
}
}
func delete( value : String)
{
var i = 0
for ( i = 0; i < numberOfStudents ; i++)
{
if (value == studentArray[i]![1])
{
break;
}
}
if (i == numberOfStudents - 1 )
{
print("not found");
}
else
{
for (var k = i; k < numberOfStudents - 1 ; k++)
{
studentArray[k]![1] = studentArray[k+1]![1];
studentArray[k]![0] = studentArray[k+1]![0];
}
numberOfStudents--;
}
}
}
var hello = student()
hello.studentArray = [["0","0ee"],["9","9ee", ]]
hello.display() // I have a error at this point
hello.studentArray
Could anyone explain what is about it for me?
There are several mistakes in your code. The actual error is caused by your numberOfStudents variable, which is hard coded to 10, even though the array only contains 2 elements. Use studentArray.count in your for loop, not 10. Then read the Swift manual. You should not be using optionals nor C-style for loops in this example.
Here's how I would do it...
class Student { // Capitalise your classes
// Unnecessary whitespace removed
var studentArray: [[String]] = [] // No need for optionals here
/*
var numberOfStudents : Int = 10; // var is useless & wrong, also no need for semi-colon
*/
func display() {
/* A Swift-ier way to do this is
for student in studentArray {
print("{")
for field in student {
print(field + " ")
}
print("}")
}
However, using indexing:
*/
for i in 0 ..< studentArray.count {
print("{")
for j in 0 ..< studentArray[i].count { // Don't *know* this will be 2
print(studentArray[i][j] + " ") // Don't need semi-colons unless you want to put multiple statements on the same line
}
print("}")
}
}
/* func delete() not used in question, so removed from answer */
}
var hello = Student()
hello.studentArray = [["0","0ee"], ["9","9ee", ]] // Note spurious (but not wrong) comma
hello.display()
hello.studentArray
I have to make a connect-four game using scala. I have attached the code but everytime the game runs and gets to row 3 it just continues to change the second rows entry instead of going to the next row. Any help would be appreciated. I found this code on another thread on here and couldn't figure out how to get it to work:
// makes the board
val table = Array.fill(9,8)('-')
var i = 0;
while(i < 8){
table(8)(i) = (i+'0').toChar
i = i+1;
}
// prints starting board
def printBoard(table: Array[Array[Char]]) {
table.foreach( x => println(x.mkString(" ")))
}
//player 1 moves
def playerMove1(){
val move = readInt
var currentRow1 = 7
while (currentRow1 >= 0)
if (table(currentRow1)(move) != ('-')) {
currentRow1 = (currentRow1-1)
table(currentRow1)(move) = ('X')
return (player2)}
} else {
table(currentRow1)(move) = ('X')
return (player2)
}
}
//player 2 moves
def playerMove2(){
val move = readInt
var currentRow2 = 7
while (currentRow2 >= 0)
if (table(currentRow2)(move) != ('-')) {
currentRow2 = (currentRow2-1)
table(currentRow2)(move) = ('O')
return (player1)}
} else {
table(currentRow2)(move) = ('O')
return (player1)
}
}
//player 1
def player1(){
printBoard(table)
println("Player 1 it is your turn. Choose a column 0-7")
playerMove1()
}
//player 2
def player2(){
printBoard(table)
println("Player 2 it is your turn. Choose a column 0-7")
playerMove2()
}
for (turn <- 1 to 32){
player1
player2
}
I've tried to make your code readable and compiling and also tried to fix some logic.
However, I've never worked with Scala so this is just a first sketch where you might want to continue ...
Some functions can be merged and the currentRow needed a fix. See here:
object ConnectFour{
val table = Array.fill(9,8)('-')
val currentRow = Array.fill(8)(8)
def main(args: Array[String]) {
var i = 0;
while(i < 8) {
table(8)(i) = (i+'0').toChar
i = i+1;
}
player(1)
}
def printBoard(table: Array[Array[Char]]) {
table.foreach( x => println(x.mkString(" ")))
}
def player(playerNr : Int){
printBoard(table)
println("Player " + playerNr + " it is your turn. Choose a column 0-7")
var column = readAndVerifyInt
var nextUser = 1 : Int
var symbol = 'O' : Char
if(playerNr == 1) {
symbol = 'X'
nextUser = 2
}
var curR = currentRow(column)
while (curR >= 0) {
if (table(curR)(column) != ('-')) {
curR = curR-1
currentRow(column) = curR
}
table(curR)(column) = symbol
player(nextUser)
}
}
def readAndVerifyInt() : Int = {
var column = readInt
if (column >= 0 && column <= 7) {
return column
} else {
println(" > Please try again")
return readAndVerifyInt
}
}
}
I need a sus implementation in c# for finding candidate individuals in a population this is what i have so far but im not sure if it is correct.
public void sus(IEnumerable<TimeTable>population)
{
var ag = population.Sum(i => normalize((double) i.Fitness, true));
var mark = rnMutate.NextDouble();
var index = 0;
foreach (var candidate in population)
{
var cu = population.Sum(i => normalize((double)i.Fitness, false)) / ag * 5;
while (cu > mark + index)
{
Survivors.Add(candidate);
index++;
}
}
}
public double normalize(double fitness, bool natural)
{
if (natural)
return fitness;
return fitness == (double)FitnessLBound ? double.PositiveInfinity : 1 / fitness;
}
private IEnumerable<TimeTable> StochasticSample(IEnumerable<TimeTable> population, int size)
{
var t = population.Sum(it => it.Fitness);
var temp = new List<TimeTable>();
var ptr = rnMutate.NextDouble();
var sum = 0M;
for (int i = 0; i < size; i++)
{
for (sum += ExpValue(i, t); sum > (decimal) ptr; ptr++)
{
temp.Add(population.ElementAt(i));
--size;
}
}
return temp;
}
private decimal ExpValue(decimal fitness, decimal sum)
{
return decimal.Divide(fitness, sum);
}