Snippets Collections
// SOLUTION 1 - MY (DISCOVERED) SOLUTION (RUNTIME - 104MS, 44.9 MB)
var isAnagram = function(s, t) {
    
    // set function to split, sort, and rejoin characters in a string
    const sortString = (str) => {
        return str.split("").sort().join("");
    }
    
    // regex removes any non-alphabet characters in the string and makes it lowercase
    s = s.replace(/[^\w]/g, '').toLowerCase()
    t = t.replace(/[^\w]/g, '').toLowerCase()

    // final comparison
    return sortString(s) === sortString(t)
  
  // ATTEMPT 1
  //     let anagram = []
    
  // return false is lengths don't match
  //     if (s.length !== t.length) return false;
  //     else {
  //         for (let i = 0; i < s.length; i++) {
  //             let arrT = t.split("")
  //             let newArrT;
  //             if (arrT.includes(s.charAt(i))) {
  //                 let index = arrT.indexOf(s.charAt(i));
  //                 console.log("s char: ", s.charAt(i));
  //                 console.log("index: ", index);

  //                 anagram.push(s.charAt(i))

  //                 console.log("splice: ", arrT.splice(index, 1))
  //                 arrT.splice(index, 0)

  //                 newArrT = arrT
  //                 console.log("newArr: ", newArrT)
  //             };
  //         };
  //     }
  //     console.log(anagram)
  //     return anagram.join("") === s;
}

// SOLTUION 2 - (BEST RUNTIME - 60MS)
var isAnagram = function(s, t) {
    const key = w => Object.entries([...w].reduce((a, c) => {
        if (!(c in a)) a[c] = 0;
        a[c] += 1;
      
        return a;
    }, {})).sort(([c1], [c2]) => c1.localeCompare(c2)).flat().join('');
  
    return key(s) === key(t);
};

// SOLUTION 3 - (RUNTIME - 72MS)
var isAnagram = function(s, t) {
    if(s.length !== t.length) return false;
  
    let map = {};
  
    for(let item of s) {
        map[item] = map[item] + 1 || 1;
    }
    
    for(let item of t) {
        if(!map[item]) return false;
        else map[item]--;
    }
  
    return true;
};
array_multisort(array_map(function($element) {
  return $element['key'];
}, $result), SORT_ASC, $result);
# Standard
import json  # Not jason.
import random  # Fair dice roll.
import time  # As if we could.
import uuid  # Not GUID!

# Boto3/Moto
import boto3  # Client factory of typing doom.
import moto  # Love and sanity for the masses.

queue_name = "EventQueue"
fifo_queue_name = "EventQueueSorted.fifo"
event_types = ["solid", "liquid", "gas"]

# Mock me if you must!
sqs_mocker = moto.mock_sqs()
sqs_mocker.start()

# Set up client.
sqs_client = boto3.client("sqs", region_name="us-east-1")

# Create standard queue for incoming events so that we can batch it up.
sqs_create_queue_result = sqs_client.create_queue(
    QueueName=queue_name,
)

queue_url = sqs_create_queue_result["QueueUrl"]

# Create FIFO queue and allow for deduplication using event ID from
# event provider.
sqs_create_fifo_queue_result = sqs_client.create_queue(
    QueueName=fifo_queue_name,
    Attributes={
        "FifoQueue": "true",  # Stringy boolean!
        "DeduplicationScope": "messageGroup",  # No comment!
        "FifoThroughputLimit": "perMessageGroupId",  # I said no comment!
    },
)

fifo_queue_url = sqs_create_fifo_queue_result["QueueUrl"]

# Make some fake records using fake timestamps. Ignore this awful.
records = [
    {
        "timestamp": int(
            (time.time() * 1000) + random.randint(-10000, 10000),
        ),
        "event_type": random.choice(event_types),
        "event_id": str(uuid.uuid1()),
    }
    for timestamp in range(10)
]

# Do the hokey pokey
random.shuffle(records)

for record in records:
    print(record)

# {'timestamp': 1628905019640, 'event_type': 'liquid', 'event_id': '1d6d987b-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905015766, 'event_type': 'liquid', 'event_id': '1d6d987f-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905019341, 'event_type': 'gas', 'event_id': '1d6d9881-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905012019, 'event_type': 'solid', 'event_id': '1d6d9880-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905026503, 'event_type': 'liquid', 'event_id': '1d6d987c-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905024388, 'event_type': 'gas', 'event_id': '1d6d9882-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905017491, 'event_type': 'gas', 'event_id': '1d6d9883-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905013437, 'event_type': 'solid', 'event_id': '1d6d987e-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905012744, 'event_type': 'solid', 'event_id': '1d6d987d-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905010779, 'event_type': 'gas', 'event_id': '1d6d987a-fca0-11eb-9b68-cbb48e88eb48'}

# Pretend we are uberkitten.io and we are sending you 10 out of order
# records

entries = []

for record in records:
    sqs_send_message_result = sqs_client.send_message(
        QueueUrl=queue_url,
        MessageBody=json.dumps(record),
    )

# ... Pretend we pooled up a bunch of messages over 300 seconds.

# With a Lambda based subscription we can pool thousands of messages
# over a very long period up to a 1MB payload... here in moto land
# we don't have the luxury but we can imitate.

sqs_receiver_message_result = sqs_client.receive_message(
    QueueUrl=queue_url,
    MaxNumberOfMessages=10,
)

# ... Pretend we are a LAMBDA that is now receiving a ton of messages.

# Note: This would usually be a "Records" event and use different key
# casing just because.. yeh.

messages = sqs_receiver_message_result["Messages"]

# Convert body back to JSON for all the messages before we go on.
for message in messages:
    message["DecodedBody"] = json.loads(message["Body"])

# I'm still undecided about MSG
messages.sort(key=lambda message: message["DecodedBody"]["timestamp"])

entries = []

# Iterate through messages and create a new bulk of entries from the
# newly sorted list.
for message in messages:
    record = message["DecodedBody"]
    entries.append(
        {
            "Id": str(uuid.uuid1()),
            "MessageBody": message["Body"],
            "MessageGroupId": record["event_type"],
            "MessageDeduplicationId": record["event_id"],
        }
    )

# Enqueue FiFoables.
sqs_send_message_batch_results = sqs_client.send_message_batch(
    QueueUrl=fifo_queue_url,
    Entries=entries,
)

# ... Pretend we pooled up the maximum batch size for a FIFO queue..
# which is not hard to pretend at all.

sqs_receiver_message_result = sqs_client.receive_message(
    QueueUrl=fifo_queue_url,
    MaxNumberOfMessages=10,
)

# ... Pretend we are ANOTHER LAMBDA that will be processing the "sorted"
# messages.

messages = sqs_receiver_message_result["Messages"]

records_by_event_type = {}

for message in messages:
    message["DecodedBody"] = json.loads(message["Body"])
    record = message["DecodedBody"]

    records_by_event_type.setdefault(record["event_type"], [])
    records_by_event_type[record["event_type"]].append(record)


# And now demonstrate how out of control an article script can get.
for event_type, records in records_by_event_type.items():
    print(event_type)
    for record in records:
        print(record)

# gas
# {'timestamp': 1628905010779, 'event_type': 'gas', 'event_id': '1d6d987a-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905017491, 'event_type': 'gas', 'event_id': '1d6d9883-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905019341, 'event_type': 'gas', 'event_id': '1d6d9881-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905024388, 'event_type': 'gas', 'event_id': '1d6d9882-fca0-11eb-9b68-cbb48e88eb48'}
# solid
# {'timestamp': 1628905012019, 'event_type': 'solid', 'event_id': '1d6d9880-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905012744, 'event_type': 'solid', 'event_id': '1d6d987d-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905013437, 'event_type': 'solid', 'event_id': '1d6d987e-fca0-11eb-9b68-cbb48e88eb48'}
# liquid
# {'timestamp': 1628905015766, 'event_type': 'liquid', 'event_id': '1d6d987f-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905019640, 'event_type': 'liquid', 'event_id': '1d6d987b-fca0-11eb-9b68-cbb48e88eb48'}
# {'timestamp': 1628905026503, 'event_type': 'liquid', 'event_id': '1d6d987c-fca0-11eb-9b68-cbb48e88eb48'}

# How dare you mock me!
sqs_mocker.stop()
Example: Shuffle Deck of Cards

// program to shuffle the deck of cards

// declare card elements
const suits = ["Spades", "Diamonds", "Club", "Heart"];
const values = [
  "Ace",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "10",
  "Jack",
  "Queen",
  "King",
];

// empty array to contain cards
let deck = [];

// create a deck of cards
for (let i = 0; i < suits.length; i++) {
    for (let x = 0; x < values.length; x++) {
        let card = { Value: values[x], Suit: suits[i] };
        deck.push(card);
    }
}

// shuffle the cards
for (let i = deck.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * i);
    let temp = deck[i];
    deck[i] = deck[j];
    deck[j] = temp;
}

console.log('The first five cards are:');

// display 5 results
for (let i = 0; i < 5; i++) {
    console.log(`${deck[i].Value} of ${deck[i].Suit}`)
}

//output
The first five cards are:
4 of Club
5 of Diamonds
Jack of Diamonds
2 of Club
4 of Spades
function shuffle(array) {
  const curIdx = array.length;

  // While there remain elements to shuffle...
  while (0 !== cur_idx) {
    // Pick a remaining element...
    const randIdx = Math.floor(Math.random() * curIdx);
    curIdx -= 1;

    // And swap it with the current element.
    const originalIdx = array[curIdx];
    array[curIdx] = array[randIdx];
    array[randIdx] = originalIdx;
  }
  return array;
}

// Usage of shuffle
const arr = [1, 2, 3, 4, 5, 6];
arr = shuffle(arr);
console.log(arr);

// shorter
function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var originalIdx = array[i];
        array[i] = array[j];
        array[j] = originalIdx;
    }
}

//es6
function shuffle_array(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}
const shuffleArray = array => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const shuffledArray = array.sort((a, b) => 0.5 - Math.random());

// using Array map and Math.random
const shuffledArr = array => array.map(a => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map(a => a.value);

const arr = [333,1,2,11,22,3,4]
console.log(arr.sort())

arr.sort((a,b)=>a-b)

console.log(arr)
 [[pdoResources?
                                        &parents=`0`
                                        &resources=`[[++company]], [[++new-products]], [[++used-products]], [[++koptika]], [[++services]], [[++brands]], [[++news]], [[++contact]]`
                                        &limit=`20`
                                        &depth=`10`
                                        &tpl=`footerLinksTPL`
                                        &sortby=`FIELD(modResource.id, [[++company]], [[++new-products]], [[++used-products]], [[++koptika]], [[++services]], [[++brands]], [[++news]], [[++contact]] )`
                                        &sortdir=`ASC`
                                        &showHidden=`1`
                                        &context=`[[!getContext]]`
                                    ]]
set srcFldr to (choose folder with prompt "Select the source folder:")
set destFldr to (choose folder with prompt "Select the destination folder:")
tell application "Finder"
	--set fileList to files of srcFldr -- sorted by name in HFS Plus' fashion (?)
	set fileList to sort (get files of srcFldr) by name -- sorted by name in Finder's fashion
	set fileCnt to count fileList
	set ff to {}
	repeat with i from 2 to fileCnt by 2
		set end of ff to item i of fileList
	end repeat
	move ff to destFldr -- you can move list at once
end tell
const a = [
    {
        k: 1, me: false, prim: false
    }, {
        k: 2, me: false, prim: false
    }, {
        k: 3, me: false, prim: false
    }, {
        k: 4, me: false, prim: false
    }, {
        k: 5, me: true, prim: true
    }, {
        k: 6, me: false, prim: false
    }
]

a
    .sort((x, y) => (x.prim === y.prim) ? 0 : x.prim ? -1 : 1)
    .sort((x, y) => (x.me === y.me) ? 0 : x.me ? -1 : 1)

console.log(a)
star

Tue Sep 21 2021 14:51:47 GMT+0000 (UTC) https://leetcode.com/submissions/detail/558649741/?from=explore&item_id=882

#javascript #strings #regex #sort #anagram #loops #unsolved
star

Thu Sep 16 2021 08:36:20 GMT+0000 (UTC)

#php #sort #array
star

Sat Aug 14 2021 01:40:11 GMT+0000 (UTC)

#aws #boto3 #sqs #fifo #sort
star

Fri Apr 02 2021 08:01:12 GMT+0000 (UTC)

#javascript #array #sort
star

Tue Mar 09 2021 17:18:08 GMT+0000 (UTC) https://discussions.apple.com/thread/2323904

#applescript #sort #files
star

Fri Jun 26 2020 11:34:47 GMT+0000 (UTC)

#javascript #sort #typescript

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension