task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Parse_an_IP_Address | Parse an IP Address | The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.
Taking the following as inputs:
127.0.0.1
The "localhost" IPv4 address
127.0.0.1:80
The "localhost" IPv4 address, with a specified port (80)
::1
The "localhost" IPv6 address
[::1]:80
The "localhost" IPv6 address, with a specified port (80)
2605:2700:0:3::4713:93e3
Rosetta Code's primary server's public IPv6 address
[2605:2700:0:3::4713:93e3]:80
Rosetta Code's primary server's public IPv6 address, with a specified port (80)
Task
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
Example
127.0.0.1 has the address number 7F000001 (2130706433 decimal)
in the ipv4 address space.
::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the
address number FFFF7F000001 (281472812449793 decimal).
::1 has address number 1 and serves the same purpose in the ipv6 address
space that 127.0.0.1 serves in the ipv4 address space.
| #Rust | Rust | use std::{
net::{IpAddr, SocketAddr},
str::FromStr,
};
#[derive(Clone, Debug)]
struct Addr {
addr: IpAddr,
port: Option<u16>,
}
impl std::fmt::Display for Addr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let ipv = if self.addr.is_ipv4() { "4" } else { "6" };
let hex = match self.addr {
IpAddr::V4(addr) => u32::from(addr) as u128,
IpAddr::V6(addr) => u128::from(addr),
};
match self.port {
Some(p) => write!(
f,
"address: {}, port: {}, hex: {:x} (IPv{})",
self.addr, p, hex, ipv
),
None => write!(
f,
"address: {}, port: N/A, hex: {:x} (IPv{}) ",
self.addr, hex, ipv
),
}
}
}
impl FromStr for Addr {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Ok(addr) = s.parse::<IpAddr>() {
Ok(Self { addr, port: None })
} else if let Ok(sock) = s.parse::<SocketAddr>() {
Ok(Self {
addr: sock.ip(),
port: Some(sock.port()),
})
} else {
Err(())
}
}
}
fn print_addr(s: &str) {
match s.parse::<Addr>() {
Ok(addr) => println!("{}: {}", s, addr),
_ => println!("{} not a valid address", s),
}
}
fn main() {
[
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80",
]
.iter()
.cloned()
.for_each(print_addr);
} |
http://rosettacode.org/wiki/Parse_an_IP_Address | Parse an IP Address | The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.
Taking the following as inputs:
127.0.0.1
The "localhost" IPv4 address
127.0.0.1:80
The "localhost" IPv4 address, with a specified port (80)
::1
The "localhost" IPv6 address
[::1]:80
The "localhost" IPv6 address, with a specified port (80)
2605:2700:0:3::4713:93e3
Rosetta Code's primary server's public IPv6 address
[2605:2700:0:3::4713:93e3]:80
Rosetta Code's primary server's public IPv6 address, with a specified port (80)
Task
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
Example
127.0.0.1 has the address number 7F000001 (2130706433 decimal)
in the ipv4 address space.
::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the
address number FFFF7F000001 (281472812449793 decimal).
::1 has address number 1 and serves the same purpose in the ipv6 address
space that 127.0.0.1 serves in the ipv4 address space.
| #Scala | Scala | object IPparser extends App {
/*
Parse an IP (v4/v6) Address
This software can parse all ipv4/ipv6 address text representations
of IP Address in common usage against the IEF RFC 5952 specification.
The results of the parse are:
- The parts of the text are valid representations. This is indicated in the list by a ✔ or ✘.
- The intended version; 4 or 6.
- Compliance with RFC 5952 in respect with double colons Compressed zeroes expansion ('::') and lower case letters.
- Hexadecimal representation of the intended IP address.
- If part in the text the port number which is optional.
- The used text string search pattern.
As much of the information is produced if there are invalid parts in the remark field.
*/
def myCases = Map(
"http:" -> IPInvalidAddressComponents(remark = "No match at all: 'http:'."),
"http://" -> IPInvalidAddressComponents(remark = "No match at all: 'http://'."),
"http:// " -> IPInvalidAddressComponents(remark = "No match at all: 'http:// '."),
"http://127.0.0.1/" -> ResultContainer(4, BigInt("7F000001", 16)),
"http://127.0.0.1:80/" -> ResultContainer(4, BigInt("7F000001", 16), Some(80)),
"http://127.0.0.1:65536" ->
IPInvalidAddressComponents(4, BigInt("7F000001", 16), Some(65536), remark = "Port number out of range."),
"http://192.168.0.1" -> ResultContainer(4, BigInt("C0A80001", 16)),
"http:/1::" -> ResultContainer(6, BigInt("10000000000000000000000000000", 16)),
"http:/2001:0db8:0:0:0:0:1428:57ab/" -> ResultContainer(6, BigInt("20010db80000000000000000142857ab", 16)),
"2001:0db8:0:0:8d3:0:0:0" -> ResultContainer(6, BigInt("20010db80000000008d3000000000000", 16)),
"2001:db8:0:0:8d3::" -> ResultContainer(6, BigInt("20010db80000000008d3000000000000", 16)),
"http:/2001:db8:3:4::192.0.2.33" -> ResultContainer(6, BigInt("20010db80003000400000000c0000221", 16)),
"2001:db8:85a3:0:0:8a2e:370:7334" -> ResultContainer(6, BigInt("20010db885a3000000008a2e03707334", 16)),
"2001:db8::1428:57ab" -> ResultContainer(6, BigInt("20010db80000000000000000142857ab", 16)),
"2001:db8::8d3:0:0:0" -> ResultContainer(6, BigInt("20010db80000000008d3000000000000", 16)),
"256.0.0.0" -> IPInvalidAddressComponents(4, remark = "Invalid octets."),
"2605:2700:0:3::4713:93e3" -> ResultContainer(6, BigInt("260527000000000300000000471393e3", 16)),
"::" -> ResultContainer(6, BigInt("00000000000000000000000000000000", 16)),
"1::8" -> ResultContainer(6, BigInt("00010000000000000000000000000008", 16)),
"::1" -> ResultContainer(6, BigInt("00000000000000000000000000000001", 16)),
"::192.168.0.1" -> ResultContainer(6, BigInt("000000000000000000000000c0a80001", 16)),
"::255.255.255.255" -> ResultContainer(6, BigInt("000000000000000000000000ffffffff", 16)),
"http:/[::255.255.255.255]:65536" ->
IPInvalidAddressComponents(6, BigInt("000000000000000000000000ffffffff", 16), Some(65536), remark = "Port number out of range."),
"::2:3:4:5:6:7:8" -> ResultContainer(6, BigInt("00000002000300040005000600070008", 16), strictRFC5952 = false),
"::8" -> ResultContainer(6, BigInt("00000000000000000000000000000008", 16)),
"::c0a8:1" -> ResultContainer(6, BigInt("000000000000000000000000c0a80001", 16)),
"::ffff:0:255.255.255.255" -> ResultContainer(6, BigInt("0000000000000000ffff0000ffffffff", 16)),
"::ffff:127.0.0.0.1" -> IPInvalidAddressComponents(4, remark = "Address puntation error: ':127.0.0.0.1'."),
"::ffff:127.0.0.1" -> ResultContainer(6, BigInt("00000000000000000000ffff7f000001", 16)),
"::ffff:192.168.0.1" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a80001", 16)),
"::ffff:192.168.173.22" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a8ad16", 16)),
"::ffff:255.255.255.255" -> ResultContainer(6, BigInt("00000000000000000000ffffffffffff", 16)),
"::ffff:71.19.147.227" -> ResultContainer(6, BigInt("00000000000000000000ffff471393e3", 16)),
"1:2:3:4:5:6:7::" -> ResultContainer(6, BigInt("00010002000300040005000600070000", 16), strictRFC5952 = false),
"8000:2:3:4:5:6:7::" -> ResultContainer(6, BigInt("80000002000300040005000600070000", 16), strictRFC5952 = false),
"1:2:3:4:5:6::8" -> ResultContainer(6, BigInt("00010002000300040005000600000008", 16), strictRFC5952 = false),
"1:2:3:4:5::8" -> ResultContainer(6, BigInt("00010002000300040005000000000008", 16)),
"1::7:8" -> ResultContainer(6, BigInt("00010000000000000000000000070008", 16)),
"a::b::1" -> IPInvalidAddressComponents(remark = "Noise found: 'a::b::1'."),
"fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" -> ResultContainer(6, BigInt("0fffffffffffffffffffffffffffffff", 16)),
"FFFF:ffff:ffff:ffff:ffff:ffff:ffff:ffff" -> ResultContainer(6, BigInt("ffffffffffffffffffffffffffffffff", 16), strictRFC5952 = false),
"ffff:ffff:ffff:fffg:ffff:ffff:ffff:ffff" -> IPInvalidAddressComponents(remark = "No match at all: 'ffff:ffff:ffff:fffg…'."),
"g::1" -> IPInvalidAddressComponents(6, remark ="Invalid input 'g::1'."),
"[g::1]:192.0.2.33" -> IPInvalidAddressComponents(4, remark = "Address puntation error: ':192.0.2.33'."),
"1:2:3:4:5:6:7:8" -> ResultContainer(6, BigInt("00010002000300040005000600070008", 16)),
"1:2:3:4:5::7:8" -> ResultContainer(6, BigInt("00010002000300040005000000070008", 16), strictRFC5952 = false),
"1:2:3:4::6:7:8" -> ResultContainer(6, BigInt("00010002000300040000000600070008", 16), strictRFC5952 = false),
"1:2:3:4::8" -> ResultContainer(6, BigInt("00010002000300040000000000000008", 16)),
"1:2:3::5:6:7:8" -> ResultContainer(6, BigInt("00010002000300000005000600070008", 16), strictRFC5952 = false),
"1:2:3::8" -> ResultContainer(6, BigInt("00010002000300000000000000000008", 16)),
"1:2::4:5:6:7:8" -> ResultContainer(6, BigInt("00010002000000040005000600070008", 16), strictRFC5952 = false),
"1:2::8" -> ResultContainer(6, BigInt("00010002000000000000000000000008", 16)),
"1::3:4:5:6:7:8" -> ResultContainer(6, BigInt("00010000000300040005000600070008", 16), strictRFC5952 = false),
"1::4:5:6:7:8" -> ResultContainer(6, BigInt("00010000000000040005000600070008", 16)),
"1::5:6:7:8" -> ResultContainer(6, BigInt("00010000000000000005000600070008", 16)),
"[1::6:7:8]" -> ResultContainer(6, BigInt("0010000000000000000000600070008", 16)),
"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" -> ResultContainer(6, BigInt("ffffffffffffffffffffffffffffffff", 16)),
"64:ff9b::192.0.2.33" -> ResultContainer(6, BigInt("0064ff9b0000000000000000c0000221", 16)),
"64:ff9b::256.0.2.33" ->
IPInvalidAddressComponents(6, BigInt("0064ff9b000000000000000000000000", 16), remark = "Invalid octets."),
"[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443" -> ResultContainer(6, BigInt("20010db885a308d313198a2e03707348", 16), Some(443)),
"[2001:db8:85a3:8d3:1319:8a2e:370:7348]:100000" ->
IPInvalidAddressComponents(6, BigInt("20010db885a308d313198a2e03707348", 16), Some(100000), remark = "Port number out of range."),
"[2605:2700:0:3::4713:93e3]:80" -> ResultContainer(6, BigInt("260527000000000300000000471393e3", 16), Some(80)),
"[::ffff:192.168.0.1]:22" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a80001", 16), Some(22)),
"[::ffff:192.168.173.22]:80" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a8ad16", 16), Some(80)),
"[::ffff:71.19.147.227]:80" -> ResultContainer(6, BigInt("00000000000000000000FFFF471393E3", 16), Some(80)),
"2001:0DB8:0:0:0:0:1428:57AB" -> ResultContainer(6, BigInt("20010DB80000000000000000142857AB", 16), strictRFC5952 = false),
"2001:0DB8:0:0:8D3:0:0:0" -> ResultContainer(6, BigInt("20010DB80000000008D3000000000000", 16), strictRFC5952 = false),
"2001:DB8:0:0:8D3::" -> ResultContainer(6, BigInt("20010DB80000000008D3000000000000", 16), strictRFC5952 = false),
"2001:DB8:3:4::192.0.2.33" -> ResultContainer(6, BigInt("20010DB80003000400000000C0000221", 16), strictRFC5952 = false),
"2001:DB8:85A3:0:0:8A2E:370:7334" -> ResultContainer(6, BigInt("20010DB885A3000000008A2E03707334", 16), strictRFC5952 = false),
"2001:DB8::1428:57AB" -> ResultContainer(6, BigInt("20010DB80000000000000000142857AB", 16), strictRFC5952 = false),
"2001:DB8::8D3:0:0:0" -> ResultContainer(6, BigInt("20010DB80000000008D3000000000000", 16), strictRFC5952 = false),
"2605:2700:0:3::4713:93E3" -> ResultContainer(6, BigInt("260527000000000300000000471393E3", 16), strictRFC5952 = false),
"::192.168.0.1" -> ResultContainer(6, BigInt("000000000000000000000000C0A80001", 16)),
"::255.255.255.255" -> ResultContainer(6, BigInt("000000000000000000000000FFFFFFFF", 16)),
"::C0A8:1" -> ResultContainer(6, BigInt("000000000000000000000000c0a80001", 16), strictRFC5952 = false),
"::FFFF:0:255.255.255.255" -> ResultContainer(6, BigInt("0000000000000000FFFF0000FFFFFFFF", 16), strictRFC5952 = false),
"::FFFF:127.0.0.0.1" -> IPInvalidAddressComponents(4, remark = "Address puntation error: ':127.0.0.0.1'."),
"::FFFF:127.0.0.1" -> ResultContainer(6, BigInt("00000000000000000000FFFF7F000001", 16), strictRFC5952 = false),
"::FFFF:192.168.0.1" -> ResultContainer(6, BigInt("00000000000000000000FFFFC0A80001", 16), strictRFC5952 = false),
"::FFFF:192.168.173.22" -> ResultContainer(6, BigInt("00000000000000000000FFFFC0A8AD16", 16), strictRFC5952 = false),
"::FFFF:255.255.255.255" -> ResultContainer(6, BigInt("00000000000000000000FFFFFFFFFFFF", 16), strictRFC5952 = false),
"::FFFF:71.19.147.227" -> ResultContainer(6, BigInt("00000000000000000000FFFF471393E3", 16), strictRFC5952 = false),
"[1::]:80" -> ResultContainer(6, BigInt("00010000000000000000000000000000", 16), Some(80)),
"[2001:DB8:85A3:8D3:1319:8A2E:370:7348]:443" -> ResultContainer(6, BigInt("20010db885a308d313198a2e03707348", 16), Some(443), strictRFC5952 = false),
"[2605:2700:0:3::4713:93E3]:80" -> ResultContainer(6, BigInt("260527000000000300000000471393e3", 16), Some(80), strictRFC5952 = false),
"[::1]:80" -> ResultContainer(6, BigInt("00000000000000000000000000000001", 16), Some(80)),
"[::1]:65536" ->
IPInvalidAddressComponents(6, BigInt("00000000000000000000000000000001", 16), Some(65536), remark = "Port number out of range."),
"[::]:80" -> ResultContainer(6, BigInt("00000000000000000000000000000000", 16), Some(80)),
"[::FFFF:192.168.0.1]:22" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a80001", 16), Some(22), strictRFC5952 = false),
"[::FFFF:192.168.173.22]:80" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a8ad16", 16), Some(80), strictRFC5952 = false),
"[::FFFF:71.19.147.227]:80" -> ResultContainer(6, BigInt("00000000000000000000ffff471393e3", 16), Some(80), strictRFC5952 = false),
"A::B::1" -> IPInvalidAddressComponents(remark = "Noise found: 'A::B::1'."),
"FFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF" -> ResultContainer(6, BigInt("0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16), strictRFC5952 = false),
"FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF" -> ResultContainer(6, BigInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16), strictRFC5952 = false),
"FFFF:FFFF:FFFF:FFFG:FFFF:FFFF:FFFF:FFFF" -> IPInvalidAddressComponents(remark = "No match at all: 'FFFF:FFFF:FFFF:FFFG…'."),
"G::1" -> IPInvalidAddressComponents(6, remark = "Invalid input 'G::1'."),
"64:FF9B::192.0.2.33" -> ResultContainer(6, BigInt("0064FF9B0000000000000000C0000221", 16), strictRFC5952 = false),
"64:FF9B::256.0.2.33" -> IPInvalidAddressComponents(6, BigInt("0064FF9B000000000000000000000000", 16), remark = "Invalid octets.")
)
def IPInvalidAddressComponents(version: Int = 0,
address: BigInt = BigInt(0),
port: Option[Int] = None,
valid: Boolean = false,
remark: String = "",
strict: Boolean = false) = ResultContainer(version, address, port, valid, remark, strict)
case class ResultContainer(version: Int,
address: BigInt,
port: Option[Int] = None,
valid: Boolean = true,
remark: String = "",
strictRFC5952: Boolean = true)
class IpAddress(val originalString: String) {
import IpAddress._
val (usedPattern, result: ResultContainer) = originalString match {
case trapPattern() => (trapPattern, IPInvalidAddressComponents(remark = s"Noise found: '${shortener(originalString)}'."))
case allIpV6PortedPatternsCompiled(adr, port) => parseIpV6(adr, Option(port).map(_.toInt))
case allIpV6UnspecPortPatternsCompiled(adr) => parseIpV6(adr)
case ipV4PortSpecCompiled(adr, port) => (ipV4PortSpecCompiled, parseIpV4(adr, Option(port).map(_.toInt)))
case _ => ("Exhausted of all matches.", IPInvalidAddressComponents(remark = s"No match at all: '${shortener(originalString, 19)}'."))
}
override def toString: String = {
def hexAddr = if (result.version == 6) f"${result.address}%#034x" else f"${result.address}%#010x"
def validInd = if (result.valid) '\u2714' else '\u2718'
def rfc5952 = if (result.strictRFC5952) "comply" else "broken"
def version = result.version match {
case 0 => " ?"
case 4 => "IPv4"
case 6 => "IPv6"
}
def surround(s: String) = if (result.valid) s" $s " else s"($s)"
def port = if (result.port.isDefined) surround(result.port.get.toString) else if (result.valid) " " else "? "
def hexAddrField = f"${if (result.valid || result.address != 0) surround(hexAddr) else "? "}%36s "
f"${shortener(originalString, 45)}%46s $version $validInd $rfc5952 $hexAddrField $port%8s ${result.remark}%-40s $usedPattern"
}
def shortener(s: String, maxlength: Int = 12): String = {
val size = s.length()
s.substring(0, math.min(size, maxlength)) + (if (size > maxlength) "…" else "")
}
private def parseIpV6(ipAddress: String, port: Option[Int] = None): (String, ResultContainer) = {
def colonedStringToBigInt(colonedString: String): (BigInt, Int) = {
// Compressed zeroes expansion
val ar = if (colonedString contains "::") colonedString.split("::", 2) else Array("", colonedString)
val (left, right) = (ar.head.split(':').filterNot(_.isEmpty), ar(1).split(':').filterNot(_.isEmpty))
val sixteenBitExpansions = 8 - (right.length + left.length)
((left ++ Seq.fill(sixteenBitExpansions)("0") ++ right)
.map(BigInt(_, 16).toLong).map(BigInt(_)).reduceLeft((acc, i) => (acc << 16) | i),
sixteenBitExpansions)
}
def parseEmbeddedV4(seg: String, ip4Seg: String, usedRegEx: String): (String, ResultContainer) = {
val (ip4, ip6Parser, test) =
(parseIpV4(ip4Seg), colonedStringToBigInt(seg.replaceFirst(ipV4Regex("3"), "0:0")), portNumberTest(port))
(usedRegEx, ResultContainer(originalString, 6, ip4.address + ip6Parser._1, port,
ip4.valid && test.isEmpty, ip4.remark + test, ip4.valid && test.isEmpty))
}
if (!ipAddress.forall((('A' to 'F') ++ ('a' to 'f') ++ ('0' to '9') ++ Vector(':', '.')).contains(_)))
("[^:.[0-9][A-F][a-f]]", IPInvalidAddressComponents(6, remark = s"Invalid input '${shortener(ipAddress)}'."))
else
ipAddress match {
case pattern10Compiled(seg, ip4Seg) => parseEmbeddedV4(seg, ip4Seg, pattern10Compiled.toString())
case pattern11Compiled(seg, ip4Seg) => parseEmbeddedV4(seg, ip4Seg, pattern11Compiled.toString())
case ip6PatternsRawCompiled(seg, _*) =>
val (ip6Parser, test) = (colonedStringToBigInt(seg), portNumberTest(port))
(ip6PatternsRawCompiled.toString(),
ResultContainer(ipAddress, 6, ip6Parser._1, port,
valid = test.isEmpty, test, strictRFC5952 = ip6Parser._2 != 1 && test.isEmpty))
case _ => ("V6 match exhausted.", IPInvalidAddressComponents(6, remark = "V6 address puntation error."))
}
} // parseIpV6
private def parseIpV4(sIP: String, port: Option[Int] = None): ResultContainer = {
def wordsToNum(words: Array[Long]): Long = words.reduceLeft((acc, i) => (acc << 8) | i)
if (sIP.head.isDigit && sIP.matches(ipV4Regex("3"))) {
val octets = sIP.split('.').map(_.toLong)
if (octets.forall(_ < 256)) {
val portNumberOK = portNumberTest(port)
ResultContainer(4, BigInt(wordsToNum(octets)), port, portNumberOK.isEmpty, portNumberOK, portNumberOK.isEmpty)
} else IPInvalidAddressComponents(4, remark = "Invalid octets.")
}
else IPInvalidAddressComponents(4, remark = s"Address puntation error: '${shortener(sIP)}'.")
}
private def portNumberTest(port: Option[Int]) = if (port.isEmpty || port.get < math.pow(2, 16)) "" else "Port number out of range."
} // IpAddress
object IpAddress {
val (ip6PatternsRawCompiled, pattern11Compiled) = (ipV6Patterns.mkString("(", "|", ")").r, embeddedV4patterns()(1).r)
val (trapPattern, pattern10Compiled) = (""".*?(?:(?:\w*:{2,}?){2,}?\w)|(?:\[?)""".r, embeddedV4patterns().head.r)
val allIpV6PortedPatternsCompiled = ("""[^\\.]*?\[(""" + allIpV6 +""")\](?::(\d{1,6}))?[^\.:]*?""").r
val allIpV6UnspecPortPatternsCompiled = (""".*?(""" + allIpV6 +""")[^\.:]*?""").r
val ipV4PortSpecCompiled = s".*?([:.\\]]?${ipV4Regex()})(?::(\\d{1,6}))?.*?".r
// Make a regex pattern with non-capturing groups by the disabling the capturing group syntax (?:).
def allIpV6 = (embeddedV4patterns("(?:") ++ ipV6Patterns).map(s => "(?:" + s.drop(1)).mkString("|")
def ipV6Patterns = {
def ipV6SegRegWC = """\w{1,4}"""
Seq(
s"((?::(?:(?::$ipV6SegRegex){1,7}|:)))",
s"((?:$ipV6SegRegWC:(?::$ipV6SegRegex){1,6}))",
s"((?:$ipV6SegRegex:){1,2}(?::$ipV6SegRegex){1,5})",
s"((?:$ipV6SegRegex:){1,3}(?::$ipV6SegRegex){1,4})",
s"((?:$ipV6SegRegex:){1,4}(?::$ipV6SegRegex){1,3})",
s"((?:$ipV6SegRegex:){1,5}(?::$ipV6SegRegex){1,2})",
s"((?:$ipV6SegRegex:){1,6}:$ipV6SegRegex)",
s"((?:$ipV6SegRegex:){1,7}:)",
s"((?:$ipV6SegRegex:){7}$ipV6SegRegex)"
)
}
private def embeddedV4patterns(nonCapturePrefix: String = "(") =
Seq(s"(::(?:(?:FFFF|ffff)(?::0{1,4}){0,1}:){0,1}$nonCapturePrefix${ipV4Regex("3")}))",
s"((?:$ipV6SegRegex:){1,4}:$nonCapturePrefix${ipV4Regex("3")}))")
private def ipV6SegRegex = """[\dA-Fa-f]{1,4}"""
private def ipV4Regex(octets: String = "3,") = s"(?:\\d{1,3}\\.){$octets}\\d{1,3}"
}
object ResultContainer {
def apply(orginalString: String, version: Int,
address: BigInt, port: Option[Int],
valid: Boolean, remark: String,
strictRFC5952: Boolean): ResultContainer =
// To comply with strictRFC5952 all alpha character must be lowercase too.
this (version, address, port, valid, remark, strictRFC5952 && !orginalString.exists(_.isUpper))
}
{
val headline = Seq(f"${"IP addresses to be parsed. "}%46s", "Ver.", f"${"S"}%1s", "RFC5952",
f"${"Hexadecimal IP address"}%34s", f"${"Port "}%10s", f"${" Remark"}%-40s", f"${" Effective RegEx"}%-40s")
println(headline.mkString("|") + "\n" + headline.map(s => "-" * s.length).mkString("+"))
val cases: Set[IpAddress] = myCases.keySet.map(new IpAddress(_))
println(cases.toList.sortBy(s => (s.originalString.length, s.originalString)).mkString("\n"))
logInfo(s"Concluding: ${myCases.size} cases processed, ${cases.count(_.result.valid)} valid ✔ and ${cases.count(!_.result.valid)} invalid ✘.")
logInfo("Successfully completed without errors.")
def logInfo(info: String) {
println(f"[Info][${System.currentTimeMillis() - executionStart}%5d ms]" + info)
}
}
} // IPparser cloc.exe : 235 loc |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
my $number = '[+-/$]?(?:\.\d+|\d+(?:\.\d*)?)';
my $operator = '[-+*/^]';
my @tests = ('1 2 + 3 4 + ^ 5 6 + ^', '3 4 2 * 1 5 - 2 3 ^ ^ / +');
for (@tests) {
my(@elems,$n);
$n = -1;
while (
s/
\s* (?<left>$number) # 1st operand (will be 'left' in infix)
\s+ (?<right>$number) # 2nd operand (will be 'right' in infix)
\s+ (?<op>$operator) # operator
(?:\s+|$) # more to parse, or done?
/
' '.('$'.++$n).' ' # placeholders
/ex) {
$elems[$n] = "($+{left}$+{op}$+{right})" # infix expression
}
while (
s/ (\$)(\d+) # for each placeholder
/ $elems[$2] # evaluate expression, substitute numeric value
/ex
) { say } # track progress
say '=>' . substr($_,2,-2)."\n";
} |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Oforth | Oforth | : fs(s, f) f s map ;
: f1 2 * ;
: f2 sq ;
#f1 #fs curry => fsf1
#f2 #fs curry => fsf2 |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Order | Order | #include <order/interpreter.h>
#define ORDER_PP_DEF_8fs ORDER_PP_FN( 8fn(8F, 8S, 8seq_map(8F, 8S)) )
#define ORDER_PP_DEF_8f1 ORDER_PP_FN( 8fn(8V, 8times(8V, 2)) )
#define ORDER_PP_DEF_8f2 ORDER_PP_FN( 8fn(8V, 8times(8V, 8V)) )
ORDER_PP(
8let((8F, 8fs(8f1))
(8G, 8fs(8f2)),
8do(
8print(8ap(8F, 8seq(0, 1, 2, 3)) 8comma 8space),
8print(8ap(8G, 8seq(0, 1, 2, 3)) 8comma 8space),
8print(8ap(8F, 8seq(2, 4, 6, 8)) 8comma 8space),
8print(8ap(8G, 8seq(2, 4, 6, 8))))) ) |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #XPL0 | XPL0 | proc Print; int N, A, B, C, D, E;
int I, P;
def Tab = $09;
[P:= @A; \point to first number
for I:= N to 5-1 do ChOut(0, Tab);
for I:= 0 to N-1 do
[IntOut(0, P(I)); ChOut(0, Tab); ChOut(0, Tab)];
CrLf(0);
];
int N, P, Q, R, S, T, U, V, W, X, Y, Z; \ 151
[for X:= 0 to 40-11 do \ N P
for Z:= 0 to 151-4 do \ Q R S
[Y:= X+Z; \ T U V W
T:= X+11; \X 11 Y 4 Z
U:= 11+Y;
V:= Y+4;
W:= 4+Z;
if T+U = 40 then
[R:= U+V;
S:= V+W;
N:= 40+R;
P:= R+S;
if N+P = 151 then
[Print(1, 151);
Print(2, N, P);
Print(3, 40, R, S);
Print(4, T, U, V, W);
Print(5, X, 11, Y, 4, Z);
exit;
];
];
];
] |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #zkl | zkl | # Pyramid solver
# [151]
# [ ] [ ]
# [ 40] [ ] [ ]
# [ ] [ ] [ ] [ ]
#[ X ] [ 11] [ Y ] [ 4 ] [ Z ]
# Known: X - Y + Z = 0
p:=T( L(151), L(Void,Void), L(40,Void,Void), L(Void,Void,Void,Void),
L("X", 11, "Y", 4, "Z") );
addlConstraint:=Dictionary( "X",1, "Y",-1, "Z",1, "1",0 );
solvePyramid(p, addlConstraint); |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #PureBasic | PureBasic | EnableExplicit
Procedure.b CheckPW(pw.s)
Define flag.b=#True,
tmp.b=#False,
c.c,
s.s,
i.i
For c='a' To 'z'
tmp=Bool(FindString(pw,Chr(c)))
If tmp : Break : EndIf
Next
flag & tmp
tmp=#False
For c='A' To 'Z'
tmp=Bool(FindString(pw,Chr(c)))
If tmp : Break : EndIf
Next
flag & tmp
tmp=#False
For c='0' To '9'
tmp=Bool(FindString(pw,Chr(c)))
If tmp : Break : EndIf
Next
flag & tmp
tmp=#False
For c='!' To '/'
s+Chr(c)
Next
For c=':' To '@'
s+Chr(c)
Next
s+"[]^_{|}~"
For i=1 To Len(pw)
tmp=Bool(FindString(s,Mid(pw,i,1)))
If tmp : Break : EndIf
Next
flag & tmp
ProcedureReturn flag
EndProcedure
Procedure.s InputHdl(prompt.s="")
Define txt.s,
s.s,
r.i,
hlp.s
Restore Help_01
Read.s hlp
Print(prompt)
Repeat
s=Inkey()
If s<>""
If FindString("0123456789",s)
txt+s
Print(s)
EndIf
If s=Chr(27)
txt="0"
Break
EndIf
ElseIf RawKey()
r=RawKey()
If r=112
PrintN("")
PrintN(hlp)
Print(~"\n"+prompt)
EndIf
EndIf
Delay(20)
Until s=Chr(13)
PrintN("")
ProcedureReturn txt
EndProcedure
NewList PasswordChar.c()
Define c.c,
pwlen.i,
n_of_pw.i,
pwstr.s,
i.i
For c='!' To '~'
If c<>'\' And c<>'`'
AddElement(PasswordChar()) : PasswordChar()=c
EndIf
Next
OpenConsole("Password generator: F1=Help; Esc=End")
Repeat
pwlen=Abs(Val(InputHdl("Length of the password (n>=4): ")))
If pwlen=0 : Break : EndIf
If pwlen<4 : Continue : EndIf
n_of_pw=Abs(Val(InputHdl("Number of passwords (n>=1): ")))
If n_of_pw=0 : Break : EndIf
For i=1 To n_of_pw
Repeat
pwstr=Mid(pwstr,2)
RandomizeList(PasswordChar())
ResetList(PasswordChar())
While NextElement(PasswordChar())
pwstr+Chr(PasswordChar())
If Len(pwstr)>=pwlen : Break : EndIf
Wend
Until CheckPW(pwstr)
PrintN(RSet(Str(i),Len(Str(n_of_pw))," ")+") "+pwstr)
pwstr=""
Next
PrintN("")
ForEver
End
DataSection
Help_01:
Data.s ~"Help: Password generator\n"+
~"------------------------\n"+
~"Blabla bla blabla bla blablabla.\n"+
~"Blabla bla blablabla.\n"+
~"Bla blabla bla blablabla bla.\n"+
~"Blabla bla blabla bla.\n"+
~"Bla blabla bla blablabla blablabla.\n"+
~"Blabla bla blabla bla blablabla.\n"+
~"Blabla blabla bla blablabla."
EndOfHelp:
EndDataSection |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #Phix | Phix | include builtins\sha256.e
include builtins\VM\pThreadN.e -- (shd not be rqd on 0.8.1+)
function asHex(string s)
string res = ""
for i=1 to length(s) do
res &= sprintf("%02X",s[i])
end for
return res
end function
sequence starts
constant start_cs = init_cs(), -- critical section
hashes = {x"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
x"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
x"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"}
procedure find_passwords()
sequence thrashes = {} -- thread-safe copy of hashes
enter_cs(start_cs)
for i=1 to length(hashes) do
thrashes = append(thrashes,thread_safe_string(hashes[i]))
end for
leave_cs(start_cs)
while true do
string pwd
enter_cs(start_cs)
if length(starts)=0 then
leave_cs(start_cs)
exit
end if
pwd = starts[$]&repeat('a',4)
starts = starts[1..$-1]
leave_cs(start_cs)
while length(pwd) do
string hash = sha256(pwd)
if find(hash,thrashes) then ?{pwd,asHex(hash)} end if
for i=5 to 2 by -1 do
if pwd[i]!='z' then
pwd[i] += 1
exit
end if
pwd[i] = 'a'
if i=2 then pwd = "" exit end if
end for
end while
end while
exit_thread(0)
end procedure
for nthreads=4 to 4 do
atom t0 = time()
starts = tagset('a','z',-1)
sequence threads = {}
for i=1 to nthreads do
threads = append(threads,create_thread(routine_id("find_passwords"),{}))
end for
wait_thread(threads)
string e = elapsed(time()-t0)
printf(1,"completed with %d threads in %s\n",{nthreads,e})
end for
|
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #OxygenBasic | OxygenBasic |
'CONFIGURATION
'=============
% max 8192 'Maximum amount of Prime Numbers (must be 2^n) (excluding 1 and 2)
% cores 4 'CPU cores available (limited to 4 here)
% share 2048 'Amount of numbers allocated to each core
'SETUP
'=====
'SOURCE DATA BUFFERS
sys primes[max]
sys numbers[max]
'RESULT BUFFER
double pp[max] 'main thread
'MULTITHREADING AND TIMING API
'=============================
extern lib "kernel32.dll"
'
void QueryPerformanceCounter(quad*c)
void QueryPerformanceFrequency(quad*freq)
sys CreateThread (sys lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, *lpThreadId)
dword WaitForMultipleObjects(sys nCount,*lpHandles, bWaitAll, dwMilliseconds)
bool CloseHandle(sys hObject)
void Sleep(sys dwMilliSeconds)
'
quad freq,t1,t2
QueryPerformanceFrequency freq
'MACROS AND FUNCTIONS
'====================
macro FindPrimes(p)
'==================
finit
sys n=1
sys c,k
do
n+=2
if c>=max then exit do
'
'IS IT DIVISIBLE BE ANY PREVIOUS PRIME
'
for k=1 to c
if frac(n/p[k])=0 then exit for
next
'
if k>c then
c++
p[c]=n 'STORE PRIME
end if
end do
end macro
macro ProcessNumbers(p,bb)
'=========================
finit
sys i,b,e
b=bb*share
e=b+share
sys v,w
for i=b+1 to e
v=numbers(i)
for j=max to 1 step -1
w=primes(j)
if w<v then
if frac(v/w)=0 then
p(i)=primes(j) 'store highest factor
exit for 'process next number
end if
end if
next
next
end macro
'THREAD FUNCTIONS
function threadA(sys v) as sys
ProcessNumbers(pp,v)
end function
function threadB(sys v) as sys
ProcessNumbers(pp,v)
end function
function threadC(sys v) as sys
ProcessNumbers(pp,v)
end function
end extern
function mainThread(sys b)
'===========================
ProcessNumbers(pp,b)
end function
'SOURCE DATA GENERATION
sys seed = 0x12345678
function Rnd() as sys
'====================
'
mov eax,seed
rol eax,7
imul eax,eax,13
mov seed,eax
return eax
end function
function GenerateNumbers()
'=========================
sys i,v,mask
mask=max * 8 -1 'as bit mask
for i=1 to max
v=rnd()
v and=mask
numbers(i)=v
next
end function
FindPrimes(primes)
GenerateNumbers()
% threads Cores-1
% INFINITE 0xFFFFFFFF 'Infinite timeout
sys Funs[threads]={@threadA,@threadB,@threadC} '3 additional threads
sys hThread[threads], id[threads], i
'
'START TIMER
'
QueryPerformanceCounter t1
'
for i=1 to threads
hThread(i) = CreateThread 0,0,funs(i),i,0,id(i)
next
MainThread(0) 'process numbers in main thread (bottom share)
if threads>0 then
WaitForMultipleObjects Threads, hThread, 1, INFINITE
end if
for i=1 to Threads
CloseHandle hThread(i)
next
'CAPTURE NUMBER WITH HIGHEST PRIME FACTOR
sys n,f
for i=1 to max
if pp(i)>f then f=pp(i) : n=i
next
'STOP TIMER
QueryPerformanceCounter t2
print str((t2-t1)/freq,3) " secs " numbers(n) " " f 'number with highest prime factor
|
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #PARI.2FGP | PARI/GP | v=pareval(vector(1000,i,()->factor(2^i+1)[1,1]));
vecmin(v) |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Fortran | Fortran | REAL FUNCTION EVALRP(TEXT) !Evaluates a Reverse Polish string.
Caution: deals with single digits only.
CHARACTER*(*) TEXT !The RPN string.
INTEGER SP,STACKLIMIT !Needed for the evaluation.
PARAMETER (STACKLIMIT = 6) !This should do.
REAL*8 STACK(STACKLIMIT) !Though with ^ there's no upper limit.
INTEGER L,D !Assistants for the scan.
CHARACTER*4 DEED !A scratchpad for the annotation.
CHARACTER*1 C !The character of the moment.
WRITE (6,1) TEXT !A function that writes messages... Improper.
1 FORMAT ("Evaluation of the Reverse Polish string ",A,// !Still, it's good to see stuff.
1 "Char Token Action SP:Stack...") !Such as a heading for the trace.
SP = 0 !Commence with the stack empty.
STACK = -666 !This value should cause trouble.
DO L = 1,LEN(TEXT) !Step through the text.
C = TEXT(L:L) !Grab a character.
IF (C.LE." ") CYCLE !Boring.
D = ICHAR(C) - ICHAR("0") !Uncouth test to check for a digit.
IF (D.GE.0 .AND. D.LE.9) THEN !Is it one?
DEED = "Load" !Yes. So, load its value.
SP = SP + 1 !By going up one.
IF (SP.GT.STACKLIMIT) STOP "Stack overflow!" !Or, maybe not.
STACK(SP) = D !And stashing the value.
ELSE !Otherwise, it must be an operator.
IF (SP.LT.2) STOP "Stack underflow!" !They all require two operands.
DEED = "XEQ" !So, I'm about to do so.
SELECT CASE(C) !Which one this time?
CASE("+"); STACK(SP - 1) = STACK(SP - 1) + STACK(SP) !A + B = B + A, so it is easy.
CASE("-"); STACK(SP - 1) = STACK(SP - 1) - STACK(SP) !A is in STACK(SP - 1), B in STACK(SP)
CASE("*"); STACK(SP - 1) = STACK(SP - 1)*STACK(SP) !Again, order doesn't count.
CASE("/"); STACK(SP - 1) = STACK(SP - 1)/STACK(SP) !But for division, A/B becomes A B /
CASE("^"); STACK(SP - 1) = STACK(SP - 1)**STACK(SP) !So, this way around.
CASE DEFAULT !This should never happen!
STOP "Unknown operator!" !If the RPN script is indeed correct.
END SELECT !So much for that operator.
SP = SP - 1 !All of them take two operands and make one.
END IF !So much for that item.
WRITE (6,2) L,C,DEED,SP,STACK(1:SP) !Reveal the state now.
2 FORMAT (I4,A6,A7,I4,":",66F14.6) !Aligned with the heading of FORMAT 1.
END DO !On to the next symbol.
EVALRP = STACK(1) !The RPN string being correct, this is the result.
END !Simple enough!
PROGRAM HSILOP
REAL V
V = EVALRP("3 4 2 * 1 5 - 2 3 ^ ^ / +") !The specified example.
WRITE (6,*) "Result is...",V
END |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada | function Palindrome (Text : String) return Boolean is
begin
for Offset in 0..Text'Length / 2 - 1 loop
if Text (Text'First + Offset) /= Text (Text'Last - Offset) then
return False;
end if;
end loop;
return True;
end Palindrome; |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #J | J | task1 =: {. (((= 10&#:) # ]) palindromic_multiples_of_eleven)
palindromic_multiples_of_eleven =: [: (#~ (99&< *. palindrome&>)) (11*i.100001)&*
palindrome =: (-: |.)@:":
20 task1&> >:i.9
121 1001 1111 1221 1331 1441 1551 1661 1771 1881 1991 10901 11011 12221 13431 14641 15851 17171 18381 19591
242 2002 2112 2222 2332 2442 2552 2662 2772 2882 2992 20702 21912 22022 23232 24442 25652 26862 28182 29392
363 3003 3333 3663 3993 31713 33033 36663 300003 303303 306603 309903 312213 315513 318813 321123 324423 327723 330033 333333
484 4004 4224 4444 4664 4884 40304 42724 44044 46464 48884 400004 401104 402204 403304 404404 405504 406604 407704 408804
5005 5115 5225 5335 5445 5555 5665 5775 5885 5995 50105 51315 52525 53735 54945 55055 56265 57475 58685 59895
6006 6336 6666 6996 61116 64746 66066 69696 600006 603306 606606 609906 612216 615516 618816 621126 624426 627726 630036 633336
7007 7777 77077 700007 707707 710017 717717 720027 727727 730037 737737 740047 747747 750057 757757 760067 767767 770077 777777 780087
8008 8448 8888 80608 86768 88088 800008 802208 804408 806608 808808 821128 823328 825528 827728 829928 840048 842248 844448 846648
9009 9999 94149 99099 900009 909909 918819 927729 936639 945549 954459 963369 972279 981189 990099 999999 9459549 9508059 9557559 9606069
|
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Lua | Lua |
-- Lua 5.3.5
-- Retrieved from: https://devforum.roblox.com/t/more-efficient-way-to-implement-shunting-yard/1328711
-- Modified slightly to ensure conformity with other code snippets posted here
local OPERATOR_PRECEDENCE = {
-- [operator] = { [precedence], [is left assoc.] }
['-'] = { 2, true };
['+'] = { 2, true };
['/'] = { 3, true };
['*'] = { 3, true };
['^'] = { 4, false };
}
local function shuntingYard(expression)
local outputQueue = { }
local operatorStack = { }
local number, operator, parenthesis, fcall
while #expression > 0 do
local nStartPos, nEndPos = string.find(expression, '(%-?%d+%.?%d*)')
if nStartPos == 1 and nEndPos > 0 then
number, expression = string.sub(expression, nStartPos, nEndPos), string.sub(expression, nEndPos + 1)
table.insert(outputQueue, tonumber(number))
print('token:', number)
print('queue:', unpack(outputQueue))
print('stack:', unpack(operatorStack))
else
local oStartPos, oEndPos = string.find(expression, '([%-%+%*/%^])')
if oStartPos == 1 and oEndPos > 0 then
operator, expression = string.sub(expression, oStartPos, oEndPos), string.sub(expression, oEndPos + 1)
if #operatorStack > 0 then
while operatorStack[1] ~= '(' do
local operator1Precedence = OPERATOR_PRECEDENCE[operator]
local operator2Precedence = OPERATOR_PRECEDENCE[operatorStack[1]]
if operator2Precedence and ((operator2Precedence[1] > operator1Precedence[1]) or (operator2Precedence[1] == operator1Precedence[1] and operator1Precedence[2])) then
table.insert(outputQueue, table.remove(operatorStack, 1))
else
break
end
end
end
table.insert(operatorStack, 1, operator)
print('token:', operator)
print('queue:', unpack(outputQueue))
print('stack:', unpack(operatorStack))
else
local pStartPos, pEndPos = string.find(expression, '[%(%)]')
if pStartPos == 1 and pEndPos > 0 then
parenthesis, expression = string.sub(expression, pStartPos, pEndPos), string.sub(expression, pEndPos + 1)
if parenthesis == ')' then
while operatorStack[1] ~= '(' do
assert(#operatorStack > 0)
table.insert(outputQueue, table.remove(operatorStack, 1))
end
assert(operatorStack[1] == '(')
table.remove(operatorStack, 1)
else
table.insert(operatorStack, 1, parenthesis)
end
print('token:', parenthesis)
print('queue:', unpack(outputQueue))
print('stack:', unpack(operatorStack))
else
local wStartPos, wEndPos = string.find(expression, '%s+')
if wStartPos == 1 and wEndPos > 0 then
expression = string.sub(expression, wEndPos + 1)
else
error('Invalid character set: '.. expression)
end
end
end
end
end
while #operatorStack > 0 do
assert(operatorStack[1] ~= '(')
table.insert(outputQueue, table.remove(operatorStack, 1))
end
return table.concat(outputQueue, ' ')
end
local goodmath = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'
print('infix:', goodmath)
print('postfix:', shuntingYard(goodmath))
|
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #Phix | Phix | with javascript_semantics
constant MAX_N = 32,
BRANCH = 4
sequence rooted = repeat(0,MAX_N+2),
unrooted = repeat(0,MAX_N+2)
procedure tree(integer br, n, l=n, tot=1, atom cnt=1)
atom c
for b=br+1 to BRANCH do
tot += n
if tot>=MAX_N+1
or (l*2>=tot and b>=BRANCH) then
return
end if
integer n1 = n+1,
t1 = tot+1
if b==br+1 then
c = rooted[n1]*cnt
else
c *= (rooted[n1]+(b-br-1))/(b-br)
end if
if l*2<tot then
unrooted[t1] += c
end if
if b<BRANCH then
rooted[t1] += c
for m=1 to n-1 do
tree(b,m,l,tot,c)
end for
end if
end for
end procedure
procedure bicenter(integer s)
if even(s) then
atom aux = rooted[s/2+1]
s += 1
unrooted[s] += aux*(aux+1)/2
end if
end procedure
rooted[1..2] = 1
unrooted[1..2] = 1
for n=1 to MAX_N do
tree(0, n)
bicenter(n)
if n<10 or n=MAX_N then
printf(1,"%d: %d\n",{n, unrooted[n+1]})
end if
end for
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #C.23 | C# | using System;
using System.Linq;
static class Program
{
static bool IsPangram(this string text, string alphabet = "abcdefghijklmnopqrstuvwxyz")
{
return alphabet.All(text.ToLower().Contains);
}
static void Main(string[] arguments)
{
Console.WriteLine(arguments.Any() && arguments.First().IsPangram());
}
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #C.2B.2B | C++ | #include <algorithm>
#include <cctype>
#include <string>
#include <iostream>
const std::string alphabet("abcdefghijklmnopqrstuvwxyz");
bool is_pangram(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
std::sort(s.begin(), s.end());
return std::includes(s.begin(), s.end(), alphabet.begin(), alphabet.end());
}
int main()
{
const auto examples = {"The quick brown fox jumps over the lazy dog",
"The quick white cat jumps over the lazy dog"};
std::cout.setf(std::ios::boolalpha);
for (auto& text : examples) {
std::cout << "Is \"" << text << "\" a pangram? - " << is_pangram(text) << std::endl;
}
}
|
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #Java | Java | import static java.lang.System.out;
import java.util.List;
import java.util.function.Function;
import java.util.stream.*;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public class PascalMatrix {
static int binomialCoef(int n, int k) {
int result = 1;
for (int i = 1; i <= k; i++)
result = result * (n - i + 1) / i;
return result;
}
static List<IntStream> pascal(int n, Function<Integer, IntStream> f) {
return range(0, n).mapToObj(i -> f.apply(i)).collect(toList());
}
static List<IntStream> pascalUpp(int n) {
return pascal(n, i -> range(0, n).map(j -> binomialCoef(j, i)));
}
static List<IntStream> pascalLow(int n) {
return pascal(n, i -> range(0, n).map(j -> binomialCoef(i, j)));
}
static List<IntStream> pascalSym(int n) {
return pascal(n, i -> range(0, n).map(j -> binomialCoef(i + j, i)));
}
static void print(String label, List<IntStream> result) {
out.println("\n" + label);
for (IntStream row : result) {
row.forEach(i -> out.printf("%2d ", i));
System.out.println();
}
}
public static void main(String[] a) {
print("Upper: ", pascalUpp(5));
print("Lower: ", pascalLow(5));
print("Symmetric:", pascalSym(5));
}
} |
http://rosettacode.org/wiki/Parameterized_SQL_statement | Parameterized SQL statement | SQL injection
Using a SQL update statement like this one (spacing is optional):
UPDATE players
SET name = 'Smith, Steve', score = 42, active = TRUE
WHERE jerseyNum = 99
Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either. | #Tcl | Tcl | package require Tcl 8.6
# These next two lines are the only ones specific to SQLite
package require tdbc::sqlite3
set db [tdbc::sqlite3::connection new /path/to/database.sql]
# Use a helper procedure to make a scope
proc setPlayer {db jersey -> playerName playerScore playerActive} {
# Note that the '->' above is just syntactic noise for readability
$db allrows {
UPDATE players
SET name = :playerName, score = :playerScore, active = :playerActive
WHERE jerseyNum = :jersey
}
# The named parameters are bound to local variables by default
}
# How to use...
setPlayer $db 99 -> "Smith, Steve" 42 true
# With apologies to http://xkcd.com/327/
setPlayer $db 76 -> "Robert'; DROP TABLE players--" 0 false
$db close |
http://rosettacode.org/wiki/Parameterized_SQL_statement | Parameterized SQL statement | SQL injection
Using a SQL update statement like this one (spacing is optional):
UPDATE players
SET name = 'Smith, Steve', score = 42, active = TRUE
WHERE jerseyNum = 99
Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either. | #Wren | Wren | import "./sql" for Connection
var db = Connection.open("rc.db")
var createSql = [
"DROP TABLE IF EXISTS players",
"CREATE table players (name, score, active, jerseyNum)",
"INSERT INTO players VALUES ('Roethlisberger, Ben', 94.1, TRUE, 7)",
"INSERT INTO players VALUES ('Smith, Alex', 85.3, TRUE, 11)",
"INSERT INTO players VALUES ('Doe, John', 15, FALSE, 99)",
"INSERT INTO players VALUES ('Manning, Payton', 96.5, FALSE, 123)"
]
for (sql in createSql) db.exec(sql)
var widths = [22, 7, 7, 9]
System.print("Before update:\n")
db.printTable("SELECT * FROM players", widths)
var updateSql = "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = 99"
var ps = db.prepare(updateSql)
ps.bindText(1, "Smith, Steve")
ps.bindDouble(2, 42)
ps.bindBool(3, true)
ps.bindInt(4, 99)
ps.step()
System.print("\nAfter update:\n")
db.printTable("SELECT * FROM players", widths) |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Component_Pascal | Component Pascal |
MODULE PascalTriangle;
IMPORT StdLog, DevCommanders, TextMappers;
TYPE
Expansion* = POINTER TO ARRAY OF LONGINT;
PROCEDURE Show*(e: Expansion);
VAR
i: INTEGER;
BEGIN
i := 0;
WHILE (i < LEN(e)) & (e[i] # 0) DO
StdLog.Int(e[i]);
INC(i)
END;
StdLog.Ln
END Show;
PROCEDURE GenFor*(p: LONGINT): Expansion;
VAR
expA,expB: Expansion;
i,j: LONGINT;
PROCEDURE Swap(VAR x,y: Expansion);
VAR
swap: Expansion;
BEGIN
swap := x; x := y; y := swap
END Swap;
BEGIN
ASSERT(p >= 0);
NEW(expA,p + 2);NEW(expB,p + 2);
FOR i := 0 TO p DO
IF i = 0 THEN expA[0] := 1
ELSE
FOR j := 0 TO i DO
IF j = 0 THEN
expB[j] := expA[j]
ELSE
expB[j] := expA[j - 1] + expA[j]
END
END;
Swap(expA,expB)
END;
END;
expB := NIL; (* for the GC *)
RETURN expA
END GenFor;
PROCEDURE Do*;
VAR
s: TextMappers.Scanner;
exp: Expansion;
BEGIN
s.ConnectTo(DevCommanders.par.text);
s.SetPos(DevCommanders.par.beg);
s.Scan;
WHILE (~s.rider.eot) DO
IF (s.type = TextMappers.char) & (s.char = '~') THEN
RETURN
ELSIF (s.type = TextMappers.int) THEN
exp := GenFor(s.int);
Show(exp)
END;
s.Scan
END
END Do;
END PascalTriangle.
|
http://rosettacode.org/wiki/Parse_an_IP_Address | Parse an IP Address | The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.
Taking the following as inputs:
127.0.0.1
The "localhost" IPv4 address
127.0.0.1:80
The "localhost" IPv4 address, with a specified port (80)
::1
The "localhost" IPv6 address
[::1]:80
The "localhost" IPv6 address, with a specified port (80)
2605:2700:0:3::4713:93e3
Rosetta Code's primary server's public IPv6 address
[2605:2700:0:3::4713:93e3]:80
Rosetta Code's primary server's public IPv6 address, with a specified port (80)
Task
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
Example
127.0.0.1 has the address number 7F000001 (2130706433 decimal)
in the ipv4 address space.
::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the
address number FFFF7F000001 (281472812449793 decimal).
::1 has address number 1 and serves the same purpose in the ipv6 address
space that 127.0.0.1 serves in the ipv4 address space.
| #Tcl | Tcl | package require Tcl 8.5
package require ip
proc parseIP {address} {
set result {}
set family [ip::version $address]
set port -1
if {$family == -1} {
if {[regexp {^\[(.*)\]:(\d+)$} $address -> address port]} {
dict set result port $port
set family [ip::version $address]
if {$family != 6} {
return -code error "bad address"
}
} elseif {[regexp {^(.*):(\d+)$} $address -> address port]} {
dict set result port $port
set family [ip::version $address]
if {$family != 4} {
return -code error "bad address"
}
} else {
return -code error "bad address"
}
}
# Only possible error in ports is to be too large an integer
if {$port > 65535} {
return -code error "bad port"
}
dict set result family $family
if {$family == 4} {
# IPv4 normalized form is dotted quad, but toInteger helps
dict set result addr [format %x [ip::toInteger $address]]
} else {
# IPv6 normalized form is colin-separated hex
dict set result addr [string map {: ""} [ip::normalize $address]]
}
# Return the descriptor dictionary
return $result
} |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #Phix | Phix | with javascript_semantics
bool show_workings = true
constant operators = {"^","*","/","+","-"},
precedence = { 4, 3, 3, 2, 2 },
rassoc = {'r', 0 ,'l', 0 ,'l'}
procedure parseRPN(string expr, expected)
sequence stack = {},
ops = split(expr)
string lhs, rhs
integer lprec,rprec
printf(1,"Postfix input: %-32s%s", {expr,iff(show_workings?'\n':' ')})
if length(ops)=0 then ?"error" return end if
for i=1 to length(ops) do
string op = ops[i]
integer k = find(op,operators)
if k=0 then
stack = append(stack,{9,op})
else
if length(stack)<2 then ?"error" return end if
{rprec,rhs} = stack[$]; stack = stack[1..$-1]
{lprec,lhs} = stack[$]
integer prec = precedence[k]
integer assoc = rassoc[k]
if lprec<prec or (lprec=prec and assoc='r') then
lhs = "("&lhs&")"
end if
if rprec<prec or (rprec=prec and assoc='l') then
rhs = "("&rhs&")"
end if
stack[$] = {prec,lhs&" "&op&" "&rhs}
end if
if show_workings then
?{op,stack}
end if
end for
string res = stack[1][2]
printf(1,"Infix result: %s [%s]\n", {res,iff(res=expected?"ok","**ERROR**")})
end procedure
parseRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +","3 + 4 * 2 / (1 - 5) ^ 2 ^ 3")
show_workings = false
parseRPN("1 2 + 3 4 + ^ 5 6 + ^","((1 + 2) ^ (3 + 4)) ^ (5 + 6)")
parseRPN("1 2 + 3 4 + 5 6 + ^ ^","(1 + 2) ^ (3 + 4) ^ (5 + 6)")
parseRPN("moon stars mud + * fire soup * ^","(moon * (stars + mud)) ^ (fire * soup)")
parseRPN("3 4 ^ 2 9 ^ ^ 2 5 ^ ^","((3 ^ 4) ^ 2 ^ 9) ^ 2 ^ 5")
parseRPN("5 6 * * + +","error")
parseRPN("","error")
parseRPN("1 4 + 5 3 + 2 3 * * *","(1 + 4) * (5 + 3) * 2 * 3")
parseRPN("1 2 * 3 4 * *","1 * 2 * 3 * 4")
parseRPN("1 2 + 3 4 + +","1 + 2 + 3 + 4")
parseRPN("1 2 + 3 4 + ^","(1 + 2) ^ (3 + 4)")
parseRPN("5 6 ^ 7 ^","(5 ^ 6) ^ 7")
parseRPN("5 4 3 2 ^ ^ ^","5 ^ 4 ^ 3 ^ 2")
parseRPN("1 2 3 + +","1 + 2 + 3")
parseRPN("1 2 + 3 +","1 + 2 + 3")
parseRPN("1 2 3 ^ ^","1 ^ 2 ^ 3")
parseRPN("1 2 ^ 3 ^","(1 ^ 2) ^ 3")
parseRPN("1 1 - 3 +","1 - 1 + 3")
parseRPN("3 1 1 - +","3 + 1 - 1") -- [txr says 3 + (1 - 1)]
parseRPN("1 2 3 + -","1 - (2 + 3)")
parseRPN("4 3 2 + +","4 + 3 + 2")
parseRPN("5 4 3 2 + + +","5 + 4 + 3 + 2")
parseRPN("5 4 3 2 * * *","5 * 4 * 3 * 2")
parseRPN("5 4 3 2 + - +","5 + 4 - (3 + 2)") -- [python says 5 + (4 - (3 + 2))]
parseRPN("3 4 5 * -","3 - 4 * 5")
parseRPN("3 4 5 - *","3 * (4 - 5)") -- [python says (3 - 4) * 5] [!!flagged!!]
parseRPN("3 4 - 5 *","(3 - 4) * 5")
parseRPN("4 2 * 1 5 - +","4 * 2 + 1 - 5") -- [python says 4 * 2 + (1 - 5)]
parseRPN("4 2 * 1 5 - 2 ^ /","4 * 2 / (1 - 5) ^ 2")
parseRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +","3 + 4 * 2 / (1 - 5) ^ 2 ^ 3")
|
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #PARI.2FGP | PARI/GP | fs=apply;
f1(x)=2*x;
f2(x)=x^2;
fsf1=any->=fs(f1,any);
fsf2=any->=fs(f2,any);
fsf1([0..3])
fsf1(2([1..4])
fsf2([0..3])
fsf2(2([1..4]) |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Perl | Perl | sub fs(&) {
my $func = shift;
sub { map $func->($_), @_ }
}
sub double($) { shift() * 2 }
sub square($) { shift() ** 2 }
my $fs_double = fs(\&double);
my $fs_square = fs(\&square);
my @s = 0 .. 3;
print "fs_double(@s): @{[ $fs_double->(@s) ]}\n";
print "fs_square(@s): @{[ $fs_square->(@s) ]}\n";
@s = (2, 4, 6, 8);
print "fs_double(@s): @{[ $fs_double->(@s) ]}\n";
print "fs_square(@s): @{[ $fs_square->(@s) ]}\n"; |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #Python | Python | import random
lowercase = 'abcdefghijklmnopqrstuvwxyz' # same as string.ascii_lowercase
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # same as string.ascii_uppercase
digits = '0123456789' # same as string.digits
punctuation = '!"#$%&\'()*+,-./:;<=>?@[]^_{|}~' # like string.punctuation but without backslash \ nor grave `
allowed = lowercase + uppercase + digits + punctuation
visually_similar = 'Il1O05S2Z'
def new_password(length:int, readable=True) -> str:
if length < 4:
print("password length={} is too short,".format(length),
"minimum length=4")
return ''
choice = random.SystemRandom().choice
while True:
password_chars = [
choice(lowercase),
choice(uppercase),
choice(digits),
choice(punctuation)
] + random.sample(allowed, length-4)
if (not readable or
all(c not in visually_similar for c in password_chars)):
random.SystemRandom().shuffle(password_chars)
return ''.join(password_chars)
def password_generator(length, qty=1, readable=True):
for i in range(qty):
print(new_password(length, readable))
|
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #PureBasic | PureBasic | UseSHA2Fingerprint()
NewList sha256fp.s()
AddElement(sha256fp()) : sha256fp() = "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"
AddElement(sha256fp()) : sha256fp() = "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"
AddElement(sha256fp()) : sha256fp() = "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"
Procedure PrintCode(n.i)
Shared sha256fp()
SelectElement(sha256fp(), n) : fp$ = sha256fp()
For c1 = 'a' To 'z'
For c2 = 'a' To 'z'
For c3 = 'a' To 'z'
For c4 = 'a' To 'z'
For c5 = 'a' To 'z'
If fp$ = StringFingerprint(Chr(c1) + Chr(c2) + Chr(c3) + Chr(c4) + Chr(c5), #PB_Cipher_SHA2, 256); maybe set enconding
PrintN(Chr(c1) + Chr(c2) + Chr(c3) + Chr(c4) + Chr(c5) + " => " + fp$)
Break(5)
EndIf
Next c5
Next c4
Next c3
Next c2
Next c1
EndProcedure
Dim mythread(ListSize(sha256fp()))
If OpenConsole("")
StartTime.q = ElapsedMilliseconds()
For i=0 To ListSize(sha256fp()) - 1
mythread(i)=CreateThread(@PrintCode(), i)
Next
For i=0 To ListSize(sha256fp()) - 1
WaitThread(mythread(i))
Next
PrintN("-----------")
PrintN(Str(ElapsedMilliseconds() - StartTime)+" Milliseconds needed")
Input()
EndIf
End
; EnableThread |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #Perl | Perl | use ntheory qw/factor vecmax/;
use threads;
use threads::shared;
my @results :shared;
my $tnum = 0;
$_->join() for
map { threads->create('tfactor', $tnum++, $_) }
(qw/576460752303423487 576460752303423487 576460752303423487 112272537195293
115284584522153 115280098190773 115797840077099 112582718962171 299866111963290359/);
my $lmf = vecmax( map { $_->[1] } @results );
print "Largest minimal factor of $lmf found in:\n";
print " $_->[0] = [@$_[1..$#$_]]\n" for grep { $_->[1] == $lmf } @results;
sub tfactor {
my($tnum, $n) = @_;
push @results, shared_clone([$n, factor($n)]);
} |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #Phix | Phix | --
-- demo\rosetta\ParallelCalculations.exw
-- =====================================
--
-- Proof that more threads can make things faster...
--
without js -- (threads)
include mpfr.e
sequence res
constant res_cs = init_cs() -- critical section
procedure athread()
mpz z = mpz_init()
while true do
integer found = 0
enter_cs(res_cs)
for i=1 to length(res) do
if integer(res[i])
and res[i]>0 then
found = i
res[i] = 0
exit
end if
end for
leave_cs(res_cs)
if not found then exit end if
mpz_ui_pow_ui(z,2,found)
mpz_add_ui(z,z,1)
object r = mpz_prime_factors(z, 1_000_000)
enter_cs(res_cs)
res[found] = r
r = 0
leave_cs(res_cs)
end while
exit_thread(0)
end procedure
for nthreads=1 to 5 do
progress("testing %d threads...",{nthreads})
atom t0 = time()
res = tagset(100)
sequence threads = {}
for i=1 to nthreads do
threads = append(threads,create_thread(routine_id("athread"),{}))
end for
wait_thread(threads)
integer k = largest(res,true)
string e = elapsed(time()-t0)
printf(1,"largest is 2^%d+1 with smallest factor of %d (%d threads, %s)\n",
{k,res[k][1][1],nthreads,e})
end for
delete_cs(res_cs)
|
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #FreeBASIC | FreeBASIC | #define NULL 0
type node
'implement the stack as a linked list
n as double
p as node ptr
end type
function spctok( byref s as string ) as string
'returns everything in the string up to the first space
'modifies the original string to begin at the fist non-space char after the first space
dim as string r
dim as double i = 1
while mid(s,i,1)<>" " and i<=len(s)
r += mid(s,i,1)
i+=1
wend
do
i+=1
loop until mid(s,i,1)<>" " or i >= len(s)
s = right(s,len(s)-i+1)
return r
end function
sub print_stack( byval S as node ptr )
'display everything on the stack
print "Stack <--- ";
while S->p <> NULL
S = S->p
print S->n;" ";
wend
print
end sub
sub push( byval S as node ptr, v as double )
'push a value onto the stack
dim as node ptr x
x = allocate(sizeof(node))
x->n = v
x->p = S->p
S->p = x
end sub
function pop( byval S as node ptr ) as double
'pop a value from the stack
if s->P = NULL then return -99999
dim as double r = S->p->n
dim as node ptr junk = S->p
S->p = S->p->p
deallocate(junk)
return r
end function
dim as string s = "3 4 2 * 1 5 - 2 3 ^ ^ / +", c
dim as node StackHead
while len(s) > 0
c = spctok(s)
print "Token: ";c;" ";
select case c
case "+"
push(@StackHead, pop(@StackHead) + pop(@StackHead))
print "Operation + ";
case "-"
push(@StackHead, -(pop(@StackHead) - pop(@StackHead)))
print "Operation - ";
case "/"
push(@StackHead, 1./(pop(@StackHead) / pop(@StackHead)))
print "Operation / ";
case "*"
push(@StackHead, pop(@StackHead) * pop(@StackHead))
print "Operation * ";
case "^"
push(@StackHead, pop(@StackHead) ^ pop(@StackHead))
print "Operation ^ ";
case else
push(@StackHead, val(c))
print "Operation push ";
end select
print_stack(@StackHead)
wend |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | # Iterative #
PROC palindrome = (STRING s)BOOL:(
FOR i TO UPB s OVER 2 DO
IF s[i] /= s[UPB s-i+1] THEN GO TO return false FI
OD;Power
else: TRUE EXIT
return false: FALSE
);
# Recursive #
PROC palindrome r = (STRING s)BOOL:
IF LWB s >= UPB s THEN TRUE
ELIF s[LWB s] /= s[UPB s] THEN FALSE
ELSE palindrome r(s[LWB s+1:UPB s-1])
FI
;
# Test #
main:
(
STRING t = "ingirumimusnocteetconsumimurigni";
FORMAT template = $"sequence """g""" "b("is","isnt")" a palindrome"l$;
printf((template, t, palindrome(t)));
printf((template, t, palindrome r(t)))
) |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Java | Java |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(15, 100));
System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(10, 1000));
}
private static void displayMap(Map<Integer,List<Long>> map) {
for ( int key = 1 ; key <= 9 ; key++ ) {
System.out.println(key + " : " + map.get(key));
}
}
public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {
Map<Integer,List<Long>> map = new HashMap<>();
Map<Integer,Integer> mapCount = new HashMap<>();
for ( int i = 1 ; i <= 9 ; i++ ) {
map.put(i, new ArrayList<>());
mapCount.put(i, 0);
}
boolean notPopulated = true;
for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {
if ( isGapful(n) ) {
int index = (int) (n % 10);
if ( mapCount.get(index) < firstHowMany ) {
map.get(index).add(n);
mapCount.put(index, mapCount.get(index) + 1);
if ( map.get(index).size() > countReturned ) {
map.get(index).remove(0);
}
}
boolean finished = true;
for ( int i = 1 ; i <= 9 ; i++ ) {
if ( mapCount.get(i) < firstHowMany ) {
finished = false;
break;
}
}
if ( finished ) {
notPopulated = false;
}
}
}
return map;
}
public static boolean isGapful(long n) {
String s = Long.toString(n);
return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0;
}
public static int length(long n) {
int length = 0;
while ( n > 0 ) {
length += 1;
n /= 10;
}
return length;
}
public static long nextPalindrome(long n) {
int length = length(n);
if ( length % 2 == 0 ) {
length /= 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/10));
}
return Long.parseLong(n + reverse(n));
}
length = (length - 1) / 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/100));
}
return Long.parseLong(n + reverse(n/10));
}
private static boolean powerTen(long n) {
while ( n > 9 && n % 10 == 0 ) {
n /= 10;
}
return n == 1;
}
private static String reverse(long n) {
return (new StringBuilder(n + "")).reverse().toString();
}
}
|
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | rpn[str_] :=
StringRiffle[
ToString /@
Module[{in = StringSplit[str], stack = {}, out = {}, next},
While[in != {}, next = in[[1]]; in = in[[2 ;;]];
Which[DigitQ[next], AppendTo[out, next], LetterQ[next],
AppendTo[stack, next], next == ",",
While[stack[[-1]] != "(", AppendTo[out, stack[[-1]]];
stack = stack[[;; -2]]], next == "^", AppendTo[stack, "^"],
next == "*",
While[stack != {} && MatchQ[stack[[-1]], "^" | "*" | "/"],
AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]];
AppendTo[stack, "*"], next == "/",
While[stack != {} && MatchQ[stack[[-1]], "^" | "*" | "/"],
AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]];
AppendTo[stack, "/"], next == "+",
While[stack != {} &&
MatchQ[stack[[-1]], "^" | "*" | "/" | "+" | "-"],
AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]];
AppendTo[stack, "+"], next == "-",
While[stack != {} &&
MatchQ[stack[[-1]], "^" | "*" | "/" | "+" | "-"],
AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]];
AppendTo[stack, "-"], next == "(", AppendTo[stack, "("],
next == ")",
While[stack[[-1]] =!= "(", AppendTo[out, stack[[-1]]];
stack = stack[[;; -2]]]; stack = stack[[;; -2]];
If[StringQ[stack[[-1]]], AppendTo[out, stack[[-1]]];
stack = stack[[;; -2]]]]];
While[stack != {}, AppendTo[out, stack[[-1]]];
stack = stack[[;; -2]]]; out]];
Print[rpn["3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"]]; |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Nim | Nim | import tables, strutils, strformat
type operator = tuple[prec:int, rassoc:bool]
let ops = newTable[string, operator](
[ ("^", (4, true )),
("*", (3, false)),
("/", (3, false)),
("+", (2, false)),
("-", (2, false)) ])
proc shuntRPN(tokens:seq[string]): string =
var stack: seq[string]
var op:string
for token in tokens:
case token
of "(": stack.add token
of ")":
while stack.len > 0:
op = stack.pop()
if op == "(": break
result &= op & " "
else:
if token in ops:
while stack.len > 0:
op = stack[^1] # peek stack top
if not (op in ops): break
if ops[token].prec > ops[op].prec or (ops[token].rassoc and (ops[token].prec == ops[op].prec)):
break
discard stack.pop()
result &= op & " "
stack.add token
else:
result &= token & " "
echo fmt"""{token:5} {join(stack," "):18} {result:25} """
while stack.len > 0:
result &= stack.pop() & " "
echo fmt""" {join(stack," "):18} {result:25} """
let input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
echo &"for infix expression: '{input}' \n", "\nTOKEN OP STACK RPN OUTPUT"
echo "postfix: ", shuntRPN(input.strip.split) |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #Pike | Pike | int MAX_N = 300;
int BRANCH = 4;
array ra = allocate(MAX_N);
array unrooted = allocate(MAX_N);
void tree(int br, int n, int l, int sum, int cnt)
{
int c;
for (int b = br + 1; b < BRANCH + 1; b++)
{
sum += n;
if (sum >= MAX_N)
return;
// prevent unneeded long math
if (l * 2 >= sum && b >= BRANCH)
return;
if (b == br + 1)
{
c = ra[n] * cnt;
}
else
{
c = c * (ra[n] + (b - br - 1)) / (b - br);
}
if (l * 2 < sum)
unrooted[sum] += c;
if (b < BRANCH)
{
ra[sum] += c;
for (int m=1; m < n; m++)
{
tree(b, m, l, sum, c);
}
}
}
}
void bicenter(int s)
{
if (!(s & 1))
{
int aux = ra[s / 2];
unrooted[s] += aux * (aux + 1) / 2;
}
}
void main()
{
ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1;
for (int n = 1; n < MAX_N; n++)
{
tree(0, n, n, 1, 1);
bicenter(n);
write("%d: %d\n", n, unrooted[n]);
}
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Ceylon | Ceylon | shared void run() {
function pangram(String sentence) =>
let(alphabet = set('a'..'z'),
letters = set(sentence.lowercased.filter(alphabet.contains)))
letters == alphabet;
value sentences = [
"The quick brown fox jumps over the lazy dog",
"""Watch "Jeopardy!", Alex Trebek's fun TV quiz game.""",
"Pack my box with five dozen liquor jugs.",
"blah blah blah"
];
for(sentence in sentences) {
print("\"``sentence``\" is a pangram? ``pangram(sentence)``");
}
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Clojure | Clojure | (defn pangram? [s]
(let [letters (into #{} "abcdefghijklmnopqrstuvwxyz")]
(= (->> s .toLowerCase (filter letters) (into #{})) letters))) |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #JavaScript | JavaScript | (() => {
'use strict';
// -------------------PASCAL MATRIX--------------------
// pascalMatrix :: ((Int, Int) -> (Int, Int)) ->
// Int -> [Int]
const pascalMatrix = f =>
n => map(compose(binomialCoefficient, f))(
range([0, 0], [n - 1, n - 1])
);
// binomialCoefficient :: (Int, Int) -> Int
const binomialCoefficient = nk => {
const [n, k] = Array.from(nk);
return enumFromThenTo(k)(
pred(k)
)(1).reduceRight((a, x) => quot(
a * succ(n - x)
)(x), 1);
};
// ------------------------TEST------------------------
// main :: IO ()
const main = () => {
const matrixSize = 5;
console.log(intercalate('\n\n')(
zipWith(
k => xs => k + ':\n' + showMatrix(matrixSize)(xs)
)(['Lower', 'Upper', 'Symmetric'])(
apList(
map(pascalMatrix)([
identity, // Lower
swap, // Upper
([a, b]) => [a + b, b] // Symmetric
])
)([matrixSize])
)
));
};
// ----------------------DISPLAY-----------------------
// showMatrix :: Int -> [Int] -> String
const showMatrix = n =>
xs => {
const
ks = map(str)(xs),
w = maximum(map(length)(ks));
return unlines(
map(unwords)(chunksOf(n)(
map(justifyRight(w)(' '))(ks)
))
);
};
// -----------------GENERIC FUNCTIONS------------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// apList (<*>) :: [(a -> b)] -> [a] -> [b]
const apList = fs =>
// The sequential application of each of a list
// of functions to each of a list of values.
xs => fs.flatMap(
f => xs.map(f)
);
// chunksOf :: Int -> [a] -> [[a]]
const chunksOf = n =>
xs => enumFromThenTo(0)(n)(
xs.length - 1
).reduce(
(a, i) => a.concat([xs.slice(i, (n + i))]),
[]
);
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
x => fs.reduceRight((a, f) => f(a), x);
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs =>
0 < xs.length ? (
xs.every(x => 'string' === typeof x) ? (
''
) : []
).concat(...xs) : xs;
// cons :: a -> [a] -> [a]
const cons = x =>
xs => [x].concat(xs);
// enumFromThenTo :: Int -> Int -> Int -> [Int]
const enumFromThenTo = x1 =>
x2 => y => {
const d = x2 - x1;
return Array.from({
length: Math.floor(y - x2) / d + 2
}, (_, i) => x1 + (d * i));
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// fst :: (a, b) -> a
const fst = tpl =>
// First member of a pair.
tpl[0];
// identity :: a -> a
const identity = x =>
// The identity function. (`id`, in Haskell)
x;
// intercalate :: String -> [String] -> String
const intercalate = s =>
// The concatenation of xs
// interspersed with copies of s.
xs => xs.join(s);
// justifyRight :: Int -> Char -> String -> String
const justifyRight = n =>
// The string s, preceded by enough padding (with
// the character c) to reach the string length n.
c => s => n > s.length ? (
s.padStart(n, c)
) : s;
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c]
const liftA2List = f => xs => ys =>
// The binary operator f lifted to a function over two
// lists. f applied to each pair of arguments in the
// cartesian product of xs and ys.
xs.flatMap(
x => ys.map(f(x))
);
// map :: (a -> b) -> [a] -> [b]
const map = f =>
// The list obtained by applying f to each element of xs.
// (The image of xs under f).
xs => (Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
// maximum :: Ord a => [a] -> a
const maximum = xs =>
// The largest value in a non-empty list.
0 < xs.length ? (
xs.slice(1).reduce(
(a, x) => x > a ? (
x
) : a, xs[0]
)
) : undefined;
// pred :: Enum a => a -> a
const pred = x =>
x - 1;
// quot :: Int -> Int -> Int
const quot = n => m => Math.floor(n / m);
// The list of values in the subrange defined by a bounding pair.
// range([0, 2]) -> [0,1,2]
// range([[0,0], [2,2]])
// -> [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
// range([[0,0,0],[1,1,1]])
// -> [[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]
// range :: Ix a => (a, a) -> [a]
function range() {
const
args = Array.from(arguments),
ab = 1 !== args.length ? (
args
) : args[0],
[as, bs] = [ab[0], ab[1]].map(
x => Array.isArray(x) ? (
x
) : (undefined !== x.type) &&
(x.type.startsWith('Tuple')) ? (
Array.from(x)
) : [x]
),
an = as.length;
return (an === bs.length) ? (
1 < an ? (
traverseList(x => x)(
as.map((_, i) => enumFromTo(as[i])(bs[i]))
)
) : enumFromTo(as[0])(bs[0])
) : [];
};
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// str :: a -> String
const str = x => x.toString();
// succ :: Enum a => a -> a
const succ = x =>
1 + x;
// swap :: (a, b) -> (b, a)
const swap = ab =>
// The pair ab with its order reversed.
Tuple(ab[1])(
ab[0]
);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => xs.slice(0, n);
// traverseList :: (Applicative f) => (a -> f b) -> [a] -> f [b]
const traverseList = f =>
// Collected results of mapping each element
// of a structure to an action, and evaluating
// these actions from left to right.
xs => 0 < xs.length ? (() => {
const
vLast = f(xs.slice(-1)[0]),
t = vLast.type || 'List';
return xs.slice(0, -1).reduceRight(
(ys, x) => liftA2List(cons)(f(x))(ys),
liftA2List(cons)(vLast)([
[]
])
);
})() : [
[]
];
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
// unwords :: [String] -> String
const unwords = xs =>
// A space-separated string derived
// from a list of words.
xs.join(' ');
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// A list constructed by zipping with a
// custom function, rather than with the
// default tuple constructor.
xs => ys => {
const
lng = Math.min(length(xs), length(ys)),
vs = take(lng)(ys);
return take(lng)(xs)
.map((x, i) => f(x)(vs[i]));
};
// MAIN ---
return main();
})(); |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #D | D | int[][] pascalsTriangle(in int rows) pure nothrow {
auto tri = new int[][rows];
foreach (r; 0 .. rows) {
int v = 1;
foreach (c; 0 .. r+1) {
tri[r] ~= v;
v = (v * (r - c)) / (c + 1);
}
}
return tri;
}
void main() {
immutable t = pascalsTriangle(10);
assert(t == [[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1],
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]);
} |
http://rosettacode.org/wiki/Parse_an_IP_Address | Parse an IP Address | The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.
Taking the following as inputs:
127.0.0.1
The "localhost" IPv4 address
127.0.0.1:80
The "localhost" IPv4 address, with a specified port (80)
::1
The "localhost" IPv6 address
[::1]:80
The "localhost" IPv6 address, with a specified port (80)
2605:2700:0:3::4713:93e3
Rosetta Code's primary server's public IPv6 address
[2605:2700:0:3::4713:93e3]:80
Rosetta Code's primary server's public IPv6 address, with a specified port (80)
Task
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
Example
127.0.0.1 has the address number 7F000001 (2130706433 decimal)
in the ipv4 address space.
::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the
address number FFFF7F000001 (281472812449793 decimal).
::1 has address number 1 and serves the same purpose in the ipv6 address
space that 127.0.0.1 serves in the ipv4 address space.
| #VBScript | VBScript | Function parse_ip(addr)
'ipv4 pattern
Set ipv4_pattern = New RegExp
ipv4_pattern.Global = True
ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}"
'ipv6 pattern
Set ipv6_pattern = New RegExp
ipv6_pattern.Global = True
ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}"
'test if address is ipv4
If ipv4_pattern.Test(addr) Then
port = Split(addr,":")
octet = Split(port(0),".")
ipv4_hex = ""
For i = 0 To UBound(octet)
If octet(i) <= 255 And octet(i) >= 0 Then
ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2)
Else
ipv4_hex = "Erroneous Address"
Exit For
End If
Next
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: " & ipv4_hex & vbCrLf
If UBound(port) = 1 Then
If port(1) <= 65535 And port(1) >= 0 Then
parse_ip = parse_ip & "Port: " & port(1) & vbCrLf
Else
parse_ip = parse_ip & "Port: Invalid" & vbCrLf
End If
End If
End If
'test if address is ipv6
If ipv6_pattern.Test(addr) Then
parse_ip = "Test Case: " & addr & vbCrLf
port_v6 = "Port: "
ipv6_hex = ""
'check and extract port information if any
If InStr(1,addr,"[") Then
'extract the port
port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1)))
'extract the address
addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1))
End If
word = Split(addr,":")
word_count = 0
For i = 0 To UBound(word)
If word(i) = "" Then
If i < UBound(word) Then
If Int((7-(i+1))/2) = 1 Then
k = 1
ElseIf UBound(word) < 6 Then
k = Int((7-(i+1))/2)
ElseIf UBound(word) >= 6 Then
k = Int((7-(i+1))/2)-1
End If
For j = 0 To k
ipv6_hex = ipv6_hex & "0000"
word_count = word_count + 1
Next
Else
For j = 0 To (7-word_count)
ipv6_hex = ipv6_hex & "0000"
Next
End If
Else
ipv6_hex = ipv6_hex & Right("0000" & word(i),4)
word_count = word_count + 1
End If
Next
parse_ip = parse_ip & "Address: " & ipv6_hex &_
vbCrLf & port_v6 & vbCrLf
End If
'test if the address in invalid
If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: Invalid Address" & vbCrLf
End If
End Function
'Testing the function
ip_arr = Array("127.0.0.1","127.0.0.1:80","::1",_
"[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80","RosettaCode")
For n = 0 To UBound(ip_arr)
WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf
Next |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #PicoLisp | PicoLisp | (de leftAssoc (Op)
(member Op '("*" "/" "+" "-")) )
(de precedence (Op)
(case Op
("\^" 4)
(("*" "/") 3)
(("+" "-") 2) ) )
(de rpnToInfix (Str)
(let Stack NIL
(prinl "Token Stack")
(for Token (str Str "_")
(cond
((num? Token) (push 'Stack (cons 9 @))) # Highest precedence
((not (cdr Stack)) (quit "Stack empty"))
(T
(let (X (pop 'Stack) P (precedence Token))
(set Stack
(cons P
(pack
(if ((if (leftAssoc Token) < <=) (caar Stack) P)
(pack "(" (cdar Stack) ")")
(cdar Stack) )
" " Token " "
(if ((if (leftAssoc Token) <= <) (car X) P)
(pack "(" (cdr X) ")")
(cdr X) ) ) ) ) ) ) )
(prin Token)
(space 6)
(println Stack) )
(prog1 (cdr (pop 'Stack))
(and Stack (quit "Garbage remained on stack")) ) ) ) |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Phix | Phix | with javascript_semantics
function fs(integer rid, sequence s)
sequence r = repeat(0,length(s))
for i=1 to length(s) do
r[i] = rid(s[i])
end for
return r
end function
function p_apply(sequence f, args)
integer {f1,f2} = f
return f1(f2,args)
end function
function f1(integer i)
return i+i
end function
function f2(integer i)
return i*i
end function
printf(1,"%v\n",{p_apply({fs,f1},{0,1,2,3})})
printf(1,"%v\n",{p_apply({fs,f2},{0,1,2,3})})
|
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #R | R |
passwords <- function(nl = 8, npw = 1, help = FALSE) {
if (help) return("gives npw passwords with nl characters each")
if (nl < 4) nl <- 4
spch <- c("!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "@", "[", "]", "^", "_", "{", "|", "}", "~")
for(i in 1:npw) {
pw <- c(sample(letters, 1), sample(LETTERS, 1), sample(0:9, 1), sample(spch, 1))
pw <- c(pw, sample(c(letters, LETTERS, 0:9, spch), nl-4, replace = TRUE))
cat(sample(pw), "\n", sep = "")
}
}
set.seed(123)
passwords(help = TRUE)
## [1] "gives npw passwords with nl characters each"
passwords(8)
## S2XnQoy*
passwords(14, 5)
## :.iJ=Q7_gP?Cio
## !yUu7OL|eH;}1p
## y2{DNvV^Zl^IFe
## Tj@T19L.q1;I*]
## 6M+{)xV?i|1UJ/
|
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #Python | Python | import multiprocessing
from hashlib import sha256
h1 = bytes().fromhex("1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad")
h2 = bytes().fromhex("3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b")
h3 = bytes().fromhex("74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f")
def brute(firstletterascii: int):
global h1, h2, h3
letters = bytearray(5)
letters[0] = firstletterascii
for letters[1] in range(97, 97 + 26):
for letters[2] in range(97, 97 + 26):
for letters[3] in range(97, 97 + 26):
for letters[4] in range(97, 97 + 26):
digest = sha256(letters).digest()
if digest == h1 or digest == h2 or digest == h3:
password = "".join(chr(x) for x in letters)
print(password + " => " + digest.hex())
return 0
def main():
with multiprocessing.Pool() as p:
p.map(brute, range(97, 97 + 26))
if __name__ == "__main__":
main() |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #PicoLisp | PicoLisp | (let Lst
(mapcan
'((N)
(later (cons) # When done,
(cons N (factor N)) ) ) # return the number and its factors
(quote
188573867500151328137405845301 # Process a collection of 12 numbers
3326500147448018653351160281
979950537738920439376739947
2297143294659738998811251
136725986940237175592672413
3922278474227311428906119
839038954347805828784081
42834604813424961061749793
2651919914968647665159621
967022047408233232418982157
2532817738450130259664889
122811709478644363796375689 ) )
(wait NIL (full Lst)) # Wait until all computations are done
(maxi '((L) (apply min L)) Lst) ) # Result: Number in CAR, factors in CDR |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #Prolog | Prolog | threaded_decomp(Number,ID):-
thread_create(
(prime_decomp(Number,Y),
thread_exit((Number,Y)))
,ID,[]).
threaded_decomp_list(List,Erg):-
maplist(threaded_decomp,List,IDs),
maplist(thread_join,IDs,Results),
maplist(pack_exit_out,Results,Smallest_Factors_List),
largest_min_factor(Smallest_Factors_List,Erg).
pack_exit_out(exited(X),X).
%Note that here some error handling should happen.
largest_min_factor([(N,Facs)|A],(N2,Fs2)):-
min_list(Facs,MF),
largest_min_factor(A,(N,MF,Facs),(N2,_,Fs2)).
largest_min_factor([],Acc,Acc).
largest_min_factor([(N1,Facs1)|Rest],(N2,MF2,Facs2),Goal):-
min_list(Facs1, MF1),
(MF1 > MF2->
largest_min_factor(Rest,(N1,MF1,Facs1),Goal);
largest_min_factor(Rest,(N2,MF2,Facs2),Goal)).
format_it(List):-
threaded_decomp_list(List,(Number,Factors)),
format('Number with largest minimal Factor is ~w\nFactors are ~w\n',
[Number,Factors]).
|
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #FunL | FunL | def evaluate( expr ) =
stack = []
for token <- expr.split( '''\s+''' )
case number( token )
Some( n ) ->
stack = n : stack
println( "push $token: ${stack.reversed()}" )
None ->
case {'+': (+), '-': (-), '*': (*), '/': (/), '^': (^)}.>get( token )
Some( op ) ->
stack = op( stack.tail().head(), stack.head() ) : stack.tail().tail()
println( "perform $token: ${stack.reversed()}" )
None -> error( "unrecognized operator '$token'" )
stack.head()
res = evaluate( '3 4 2 * 1 5 - 2 3 ^ ^ / +' )
println( res + (if res is Integer then '' else " or ${float(res)}") ) |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Go | Go | package main
import (
"fmt"
"math"
"strconv"
"strings"
)
var input = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
func main() {
fmt.Printf("For postfix %q\n", input)
fmt.Println("\nToken Action Stack")
var stack []float64
for _, tok := range strings.Fields(input) {
action := "Apply op to top of stack"
switch tok {
case "+":
stack[len(stack)-2] += stack[len(stack)-1]
stack = stack[:len(stack)-1]
case "-":
stack[len(stack)-2] -= stack[len(stack)-1]
stack = stack[:len(stack)-1]
case "*":
stack[len(stack)-2] *= stack[len(stack)-1]
stack = stack[:len(stack)-1]
case "/":
stack[len(stack)-2] /= stack[len(stack)-1]
stack = stack[:len(stack)-1]
case "^":
stack[len(stack)-2] =
math.Pow(stack[len(stack)-2], stack[len(stack)-1])
stack = stack[:len(stack)-1]
default:
action = "Push num onto top of stack"
f, _ := strconv.ParseFloat(tok, 64)
stack = append(stack, f)
}
fmt.Printf("%3s %-26s %v\n", tok, action, stack)
}
fmt.Println("\nThe final value is", stack[0])
} |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #APL | APL | {⍵≡⌽⍵} 'abc'
0
{⍵≡⌽⍵} '⍋racecar⍋'
1 |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Julia | Julia | import Base.iterate, Base.IteratorSize, Base.IteratorEltype
struct Palindrome x1::UInt8; x2::UInt8; outer::UInt8; end
Base.IteratorSize(p::Palindrome) = Base.IsInfinite()
Base.IteratorEltype(g::Palindrome) = Vector{Int8}
function Base.iterate(p::Palindrome, state=(UInt8[p.x1]))
arr, len = [p.outer; state; p.outer], length(state)
if all(c -> c == p.x2, state)
return arr, fill(p.x1, len + 1)
end
for i in (len+1)÷2:-1:1
if state[i] < p.x2
state[len - i + 1] = state[i] = state[i] + one(UInt8)
return arr, state
else
state[len - i + 1] = state[i] = p.x1
end
end
state[1] += one(UInt8)
push!(state, state[1])
return arr, state
end
asint(s) = foldl((i, j) -> 10i + j, s)
isgapful(a) = mod(asint(a), a[1] * 11) == 0
GapfulPalindrome(i) = Iterators.filter(isgapful, Iterators.take(Palindrome(0, 9, i), 100000000000))
function testpal()
for (lastones, outof) in [(20, 20), (15, 100), (10, 1000), (10, 10000), (10, 100000), (10, 1000000), (10, 10000000)]
@time begin
println("\nLast digit | Last $lastones of $outof palindromic gapful numbers from 100\n",
"-----------|----------------------------------------------------------------------------------------------------------------")
output = fill("", 9)
Threads.@threads for i in 1:9
gplist = sort!(asint.(collect(Iterators.take(GapfulPalindrome(i), outof))))
output[i] = " $i " * string(gplist[end-lastones+1:end]) * "\n"
end
foreach(print, output)
end
end
end
testpal()
|
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #OCaml | OCaml |
type associativity = Left | Right;;
let prec op =
match op with
| "^" -> 4
| "*" -> 3
| "/" -> 3
| "+" -> 2
| "-" -> 2
| _ -> -1;;
let assoc op =
match op with
| "^" -> Right
| _ -> Left;;
let split_while p =
let rec go ls xs =
match xs with
| x::xs' when p x -> go (x::ls) xs'
| _ -> List.rev ls, xs
in go [];;
let rec intercalate sep xs =
match xs with
| [] -> ""
| [x] -> x
| x::xs' -> x ^ sep ^ intercalate sep xs';;
let shunting_yard =
let rec pusher stack queue tkns =
match tkns with
| [] -> List.rev queue @ stack
| "("::tkns' -> pusher ("("::stack) queue tkns'
| ")"::tkns' ->
let mv, "("::stack' = split_while ((<>) "(") stack in
pusher stack' (mv @ queue) tkns'
| t::tkns' when prec t < 0 -> pusher stack (t::queue) tkns'
| op::tkns' ->
let mv_to_queue op2 =
(match assoc op with
| Left -> prec op <= prec op2
| Right -> prec op < prec op2)
in
let mv, stack' = split_while mv_to_queue stack in
pusher (op::stack') (mv @ queue) tkns'
in pusher [] [];;
let () =
let inp = read_line () in
let tkns = String.split_on_char ' ' inp in
let postfix = shunting_yard tkns in
print_endline (intercalate " " postfix);;
|
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #Python | Python | try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
# prevent unneeded long math
if l * 2 >= sum and b >= BRANCH:
return
if b == br + 1:
c = ra[n] * cnt
else:
c = c * (ra[n] + (b - br - 1)) / (b - br)
if l * 2 < sum:
unrooted[sum] += c
if b < BRANCH:
ra[sum] += c;
for m in range(1, n):
tree(b, m, l, sum, c)
def bicenter(s):
global ra, unrooted
if not (s & 1):
aux = ra[s / 2]
unrooted[s] += aux * (aux + 1) / 2
def main():
global ra, unrooted, MAX_N
ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1
for n in xrange(1, MAX_N):
tree(0, n, n)
bicenter(n)
print "%d: %d" % (n, unrooted[n])
main() |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #CLU | CLU | pangram = proc (s: string) returns (bool)
letters: array[bool] := array[bool]$fill(0,26,false)
for c: char in string$chars(s) do
if c>='a' & c<='z' then
c := char$i2c(char$c2i(c) - 32)
end
if c>='A' & c<='Z' then
letters[char$c2i(c) - 65] := true
end
end
for seen: bool in array[bool]$elements(letters) do
if ~seen then return(false) end
end
return(true)
end pangram
start_up = proc ()
po: stream := stream$primary_output()
examples: array[string] := array[string]$[
"The quick brown fox jumps over the lazy dog.",
"The five boxing wizards dump quickly.",
"abcdefghijklmnopqrstuvwxyz"
]
for example: string in array[string]$elements(examples) do
stream$puts(po, "\"" || example || "\" is")
if ~pangram(example) then
stream$puts(po, " not")
end
stream$putl(po, " a pangram.")
end
end start_up |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #COBOL | COBOL | identification division.
program-id. pan-test.
data division.
working-storage section.
1 text-string pic x(80).
1 len binary pic 9(4).
1 trailing-spaces binary pic 9(4).
1 pangram-flag pic x value "n".
88 is-not-pangram value "n".
88 is-pangram value "y".
procedure division.
begin.
display "Enter text string:"
accept text-string
set is-not-pangram to true
initialize trailing-spaces len
inspect function reverse (text-string)
tallying trailing-spaces for leading space
len for characters after space
call "pangram" using pangram-flag len text-string
cancel "pangram"
if is-pangram
display "is a pangram"
else
display "is not a pangram"
end-if
stop run
.
end program pan-test.
identification division.
program-id. pangram.
data division.
1 lc-alphabet pic x(26) value "abcdefghijklmnopqrstuvwxyz".
linkage section.
1 pangram-flag pic x.
88 is-not-pangram value "n".
88 is-pangram value "y".
1 len binary pic 9(4).
1 text-string pic x(80).
procedure division using pangram-flag len text-string.
begin.
inspect lc-alphabet converting
function lower-case (text-string (1:len))
to space
if lc-alphabet = space
set is-pangram to true
end-if
exit program
.
end program pangram. |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #jq | jq | # Generic functions
# Note: 'transpose' is defined in recent versions of jq
def transpose:
if (.[0] | length) == 0 then []
else [map(.[0])] + (map(.[1:]) | transpose)
end ;
# Create an m x n matrix with init as the initial value
def matrix(m; n; init):
if m == 0 then []
elif m == 1 then [range(0;n) | init]
elif m > 0 then
matrix(1;n;init) as $row
| [range(0;m) | $row ]
else error("matrix\(m);_;_) invalid")
end ;
# A simple pretty-printer for a 2-d matrix
def pp:
def pad(n): tostring | (n - length) * " " + .;
def row: reduce .[] as $x (""; . + ($x|pad(4)));
reduce .[] as $row (""; . + "\n\($row|row)"); |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Dart | Dart |
import 'dart:io';
pascal(n) {
if(n<=0) print("Not defined");
else if(n==1) print(1);
else {
List<List<int>> matrix = new List<List<int>>();
matrix.add(new List<int>());
matrix.add(new List<int>());
matrix[0].add(1);
matrix[1].add(1);
matrix[1].add(1);
for (var i = 2; i < n; i++) {
List<int> list = new List<int>();
list.add(1);
for (var j = 1; j<i; j++) {
list.add(matrix[i-1][j-1]+matrix[i-1][j]);
}
list.add(1);
matrix.add(list);
}
for(var i=0; i<n; i++) {
for(var j=0; j<=i; j++) {
stdout.write(matrix[i][j]);
stdout.write(' ');
}
stdout.write('\n');
}
}
}
void main() {
pascal(0);
pascal(1);
pascal(3);
pascal(6);
}
|
http://rosettacode.org/wiki/Parse_an_IP_Address | Parse an IP Address | The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.
Taking the following as inputs:
127.0.0.1
The "localhost" IPv4 address
127.0.0.1:80
The "localhost" IPv4 address, with a specified port (80)
::1
The "localhost" IPv6 address
[::1]:80
The "localhost" IPv6 address, with a specified port (80)
2605:2700:0:3::4713:93e3
Rosetta Code's primary server's public IPv6 address
[2605:2700:0:3::4713:93e3]:80
Rosetta Code's primary server's public IPv6 address, with a specified port (80)
Task
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
Example
127.0.0.1 has the address number 7F000001 (2130706433 decimal)
in the ipv4 address space.
::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the
address number FFFF7F000001 (281472812449793 decimal).
::1 has address number 1 and serves the same purpose in the ipv6 address
space that 127.0.0.1 serves in the ipv4 address space.
| #Wren | Wren | import "/dynamic" for Enum, Tuple
import "/big" for BigInt
import "/str" for Str
import "/fmt" for Conv, Fmt
var AddressSpace = Enum.create("AddressSpace", ["IPv4", "IPv6", "Invalid"])
// a port of -1 denotes 'not specified'
var IPAddressComponents = Tuple.create("IPAddressComponents", ["address", "addressSpace", "port"])
var INVALID = IPAddressComponents.new(BigInt.zero, AddressSpace.Invalid, 0)
var ipAddressParse = Fn.new { |ipAddress|
var addressSpace = AddressSpace.IPv4
var ipa = Str.lower(ipAddress)
var port = -1
var trans = false
if (ipa.startsWith("::ffff:") && ipa.contains(".")) {
addressSpace = AddressSpace.IPv6
trans = true
ipa = ipa[7..-1]
} else if (ipa.startsWith("[::ffff:") && ipa.contains(".")) {
addressSpace = AddressSpace.IPv6
trans = true
ipa = ipa[8..-1].replace("]", "")
}
var octets = ipa.split(".")[-1..0].toList
var address = BigInt.zero
if (octets.count == 4) {
var split = octets[0].split(":")
if (split.count == 2) {
var temp = Num.fromString(split[1])
if (!temp || temp < 0 || temp > 65535) return INVALID
port = temp
octets[0] = split[0]
}
for (i in 0..3) {
var num = Num.fromString(octets[i])
if (!num || num < 0 || num > 255) return INVALID
var bigNum = BigInt.new(num)
address = address | (bigNum << (i * 8))
}
if (trans) address = address + BigInt.fromBaseString("ffff00000000", 16)
} else if (octets.count == 1) {
addressSpace = AddressSpace.IPv6
if (ipa[0] == "[") {
ipa = ipa[1..-1]
var split = ipa.split("]:")
if (split.count != 2) return INVALID
var temp = Num.fromString(split[1])
if (!temp || temp < 0 || temp > 65535) return INVALID
port = temp
ipa = ipa[0...(-2 - split[1].count)]
}
var hextets = ipa.split(":")[-1..0].toList
var len = hextets.count
if (ipa.startsWith("::")) {
hextets[-1] = "0"
} else if (ipa.endsWith("::")) {
hextets[0] = "0"
}
if (ipa == "::") hextets[1] = "0"
if (len > 8 || (len == 8 && hextets.any { |h| h == "" }) || hextets.count { |h| h == "" } > 1) {
return INVALID
}
if (len < 8) {
var insertions = 8 - len
for (i in 0..7) {
if (hextets[i] == "") {
hextets[i] = "0"
while (insertions > 0) {
insertions = insertions - 1
hextets.insert(i, "0")
}
break
}
}
}
for (j in 0..7) {
var num = Conv.atoi(hextets[j], 16)
if (num > 0xFFFF) return INVALID
var bigNum = BigInt.new(num)
address = address | (bigNum << (j * 16))
}
} else return INVALID
return IPAddressComponents.new(address, addressSpace, port)
}
var ipas = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80",
"::ffff:192.168.173.22",
"[::ffff:192.168.173.22]:80",
"1::",
"::",
"256.0.0.0",
"::ffff:127.0.0.0.1"
]
for (ipa in ipas) {
var ipac = ipAddressParse.call(ipa)
Fmt.print("IP address : $s", ipa)
Fmt.print("Address : $s", Str.upper(ipac.address.toBaseString(16)))
Fmt.print("Address Space : $s", AddressSpace.members[ipac.addressSpace])
Fmt.print("Port : $s", (ipac.port == -1) ? "not specified" : ipac.port.toString)
System.print()
} |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #PL.2FI | PL/I |
/* Uses a push-down pop-up stack for the stack (instead of array) */
cvt: procedure options (main); /* 10 Sept. 2012 */
declare (true initial ('1'b), false initial ('0'b) ) bit (1);
declare list character (1) controlled, written bit (1) controlled;
declare (RPN, out) character (100) varying;
declare s character (1);
declare input_priority (5) fixed (1) static initial (1, 1, 2, 2, 3);
declare stack_priority (5) fixed (1) static initial (1, 1, 2, 2, 4);
declare (i, ki, kl) fixed binary;
put ('Convert a Reverse Polish expression to orthodox.');
put skip list ('Enclose the expression in apostrophes:');
get list (RPN);
put skip list ('The original Reverse Polish expression = ' || RPN);
out = '';
allocate list, written;
list = substr(RPN, length(RPN), 1); written = false;
translation:
do i = length (RPN)-1 to 1 by -1;
s = substr(RPN, i, 1);
if s = ' ' then iterate;
ki = index('+-*/^', s);
kl = index('+-*/^', list);
if ki > 0 then /* we have an operator */
do;
if input_priority (ki) < stack_priority (kl) then
do; /* transfer ')' to list, then operator. */
allocate list, written;
list = '('; written = false;
out = ')' || out;
end;
allocate list, written;
list = s; written = false;
end;
else /* It's a variable name */
do;
out = s || out;
next_list:
if allocation(list) > 0 then if written then free written, list;
if allocation(list) > 0 then if list = '(' then
do; out = list || out; free written, list; end;
if allocation (list) = 0 then leave translation;
if written then go to next_list;
written = true;
out = list || out; /* Output an operator. */
end;
put skip edit ('INPUT=' || s) (a); call show_stack;
put edit (' OUTPUT=', out) (col(30), 2 a);
end;
put skip list ('ALGEBRAIC EXPRESSION=', out);
end cvt;
|
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #Python | Python |
"""
>>> # EXAMPLE USAGE
>>> result = rpn_to_infix('3 4 2 * 1 5 - 2 3 ^ ^ / +', VERBOSE=True)
TOKEN STACK
3 ['3']
4 ['3', '4']
2 ['3', '4', '2']
* ['3', Node('2','*','4')]
1 ['3', Node('2','*','4'), '1']
5 ['3', Node('2','*','4'), '1', '5']
- ['3', Node('2','*','4'), Node('5','-','1')]
2 ['3', Node('2','*','4'), Node('5','-','1'), '2']
3 ['3', Node('2','*','4'), Node('5','-','1'), '2', '3']
^ ['3', Node('2','*','4'), Node('5','-','1'), Node('3','^','2')]
^ ['3', Node('2','*','4'), Node(Node('3','^','2'),'^',Node('5','-','1'))]
/ ['3', Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4'))]
+ [Node(Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4')),'+','3')]
"""
prec_dict = {'^':4, '*':3, '/':3, '+':2, '-':2}
assoc_dict = {'^':1, '*':0, '/':0, '+':0, '-':0}
class Node:
def __init__(self,x,op,y=None):
self.precedence = prec_dict[op]
self.assocright = assoc_dict[op]
self.op = op
self.x,self.y = x,y
def __str__(self):
"""
Building an infix string that evaluates correctly is easy.
Building an infix string that looks pretty and evaluates
correctly requires more effort.
"""
# easy case, Node is unary
if self.y == None:
return '%s(%s)'%(self.op,str(self.x))
# determine left side string
str_y = str(self.y)
if self.y < self or \
(self.y == self and self.assocright) or \
(str_y[0] is '-' and self.assocright):
str_y = '(%s)'%str_y
# determine right side string and operator
str_x = str(self.x)
str_op = self.op
if self.op is '+' and not isinstance(self.x, Node) and str_x[0] is '-':
str_x = str_x[1:]
str_op = '-'
elif self.op is '-' and not isinstance(self.x, Node) and str_x[0] is '-':
str_x = str_x[1:]
str_op = '+'
elif self.x < self or \
(self.x == self and not self.assocright and \
getattr(self.x, 'op', 1) != getattr(self, 'op', 2)):
str_x = '(%s)'%str_x
return ' '.join([str_y, str_op, str_x])
def __repr__(self):
"""
>>> repr(Node('3','+','4')) == repr(eval(repr(Node('3','+','4'))))
True
"""
return 'Node(%s,%s,%s)'%(repr(self.x), repr(self.op), repr(self.y))
def __lt__(self, other):
if isinstance(other, Node):
return self.precedence < other.precedence
return self.precedence < prec_dict.get(other,9)
def __gt__(self, other):
if isinstance(other, Node):
return self.precedence > other.precedence
return self.precedence > prec_dict.get(other,9)
def __eq__(self, other):
if isinstance(other, Node):
return self.precedence == other.precedence
return self.precedence > prec_dict.get(other,9)
def rpn_to_infix(s, VERBOSE=False):
"""
converts rpn notation to infix notation for string s
"""
if VERBOSE : print('TOKEN STACK')
stack=[]
for token in s.replace('^','^').split():
if token in prec_dict:
stack.append(Node(stack.pop(),token,stack.pop()))
else:
stack.append(token)
# can't use \t in order to make global docstring pass doctest
if VERBOSE : print(token+' '*(7-len(token))+repr(stack))
return str(stack[0])
strTest = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
strResult = rpn_to_infix(strTest, VERBOSE=False)
print ("Input: ",strTest)
print ("Output:",strResult)
print()
strTest = "1 2 + 3 4 + ^ 5 6 + ^"
strResult = rpn_to_infix(strTest, VERBOSE=False)
print ("Input: ",strTest)
print ("Output:",strResult)
|
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #PicoLisp | PicoLisp | (def 'fs mapcar)
(de f1 (N) (* 2 N))
(de f2 (N) (* N N))
(de partial (F1 F2)
(curry (F1 F2) @
(pass F1 F2) ) )
(def 'fsf1 (partial fs f1))
(def 'fsf2 (partial fs f2))
(for S '((0 1 2 3) (2 4 6 8))
(println (fsf1 S))
(println (fsf2 S)) ) |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Prolog | Prolog | fs(P, S, S1) :-
maplist(P, S, S1).
f1(X, Y) :-
Y is 2 * X.
f2(X, Y) :-
Y is X * X.
create_partial(P, fs(P)).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fs :-
% partial functions
create_partial(f1, FSF1),
create_partial(f2, FSF2),
S1 = [0,1,2,3],
call(FSF1,S1, S11), format('~w : ~w ==> ~w~n',[FSF1, S1, S11]),
call(FSF1,S1, S12), format('~w : ~w ==> ~w~n',[FSF2, S1, S12]),
S2 = [2,4,6,8],
call(FSF1,S2, S21), format('~w : ~w ==> ~w~n',[FSF2, S2, S21]),
call(FSF2,S2, S22), format('~w : ~w ==> ~w~n',[FSF1, S2, S22]).
|
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #Racket | Racket |
#lang racket
(require racket/cmdline)
(define valid-uppercase '(#\A #\B #\C #\D #\E #\F #\G #\H #\I #\J
#\K #\L #\M #\N #\O #\P #\Q #\R #\S #\T
#\U #\V #\W #\X #\Y #\Z))
(define valid-lowercase '(#\a #\b #\c #\d #\e #\f #\g #\h #\i #\j
#\k #\l #\m #\n #\o #\p #\q #\r #\s #\t
#\u #\v #\w #\x #\y #\z))
(define valid-numbers '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))
(define valid-symbols '(#\! #\\ #\" #\# #\$ #\% #\& #\' #\( #\)
#\* #\+ #\, #\- #\. #\/ #\: #\; #\< #\=
#\> #\? #\@ #\[ #\] #\^ #\_ #\{ #\| #\}
#\~))
(define visual-invalid '(#\0 #\O #\1 #\I #\l #\| #\5 #\S #\2 #\Z))
(define (is-readable? c)
(empty? (filter (lambda (x) (eq? x c)) visual-invalid)))
(define (random-selection lst)
(list-ref lst (random (length lst))))
(define (generate len readable)
(let ([upper (if readable (filter is-readable? valid-uppercase) valid-uppercase)]
[lower (if readable (filter is-readable? valid-lowercase) valid-lowercase)]
[numbers (if readable (filter is-readable? valid-numbers) valid-numbers)]
[symbols (if readable (filter is-readable? valid-symbols) valid-symbols)])
(let loop ([lst (map random-selection (list upper lower numbers symbols))])
(cond
[(<= len (length lst)) (shuffle lst)]
[else (match (random 4)
[0 (loop (cons (random-selection upper) lst))]
[1 (loop (cons (random-selection lower) lst))]
[2 (loop (cons (random-selection numbers) lst))]
[3 (loop (cons (random-selection symbols) lst))])]))))
(define (run len cnt seed readable)
(random-seed seed)
(let loop ([x cnt])
(unless (zero? x)
(display (list->string (generate len readable)))
(newline)
(loop (- x 1)))))
(define len (make-parameter 10))
(define cnt (make-parameter 1))
(define seed (make-parameter (random 1 1000000)))
(define readable? (make-parameter #f))
(command-line #:program "passwdgen"
#:once-each
[("-l" "--length") integer "password length" (len (string->number integer))]
[("-c" "--count") integer "number of password" (cnt (string->number integer))]
[("-s" "--seed") integer "random generator seed" (seed (string->number integer))]
[("-r" "--readable") "safe characters" (readable? #t)])
(run (len) (cnt) (seed) (readable?))
|
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #Racket | Racket | #lang racket/base
(require racket/place
racket/list
racket/match
;; requires sha package. install it in DrRacket's "File/Install Package..."
;; or with raco:
;; % raco pkg install sha
sha
(only-in openssl/sha1 hex-string->bytes))
(define (brute css targs)
(define (sub-work i) (let ((cs (list-ref css i))) (in-range (car cs) (cdr cs))))
(define-values (as bs cs ds es) (apply values (map sub-work (range 5))))
(define s (make-bytes 5))
(for*/list ((a as) #:when (bytes-set! s 0 a)
(b bs) #:when (bytes-set! s 1 b)
(c cs) #:when (bytes-set! s 2 c)
(d ds) #:when (bytes-set! s 3 d)
(e es) #:when (bytes-set! s 4 e)
(h (in-value (sha256 s)))
(t (in-list targs))
#:when (bytes=? t h))
(eprintf "found ~s -> ~s~%" t s)
(cons (bytes-copy s) t)))
;; ---------------------------------------------------------------------------------------------------
(unless (place-enabled?) (error "We're using places... they're not enabled!"))
(define target-list
(map hex-string->bytes
(list "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f")))
(define (run-place/assign-task sub-task)
(define there (place here
(match-define (cons work targs) (place-channel-get here))
(place-channel-put here (brute work targs))))
(place-channel-put there (cons sub-task target-list))
there)
(define (task->subtasks css n-tasks)
(match css
[(list (and initial-range (cons A Z+)) common-tail ...)
(define step (quotient (+ n-tasks (- Z+ A)) n-tasks))
(for/list ((a (in-range A Z+ step)))
;; replace the head with a sub-task head
(cons (cons a (min (+ a step) Z+)) common-tail))]))
(define readable-pair (match-lambda [(cons x (app bytes->hex-string s)) (cons x s)]))
(define (parallel-brute css (n-tasks (processor-count)))
(define the-places (map run-place/assign-task (task->subtasks css n-tasks)))
(define collected-results (append* (map place-channel-get the-places)))
(map readable-pair collected-results))
(define 5-char-lowercase-work
(make-list 5 (cons (char->integer #\a) (add1 (char->integer #\z)))))
;; ---------------------------------------------------------------------------------------------------
(module+ main
(time (parallel-brute 5-char-lowercase-work)))
;; ---------------------------------------------------------------------------------------------------
(module+ test
(require rackunit)
(check-equal?
(bytes->hex-string (sha256 #"mmmmm"))
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"
"SHA-256 works as expected")
(check-equal?
(hex-string->bytes "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f")
#"t\341\273b\370\332\273\201%\245\210R\266;\337n\256\366g\313V\254\177|\333\246\3270\\P\242/"
"This is the raw value we'll be hashing to")
(define m-idx (char->integer #\m))
(define m-idx+ (add1 m-idx))
(check-equal?
(brute (make-list 5 (cons m-idx m-idx+)) target-list)
(list
(cons
#"mmmmm"
#"t\341\273b\370\332\273\201%\245\210R\266;\337n\256\366g\313V\254\177|\333\246\3270\\P\242/")))
;; Brute works without parallelism
;; check when you have the time... it takes a minute (literally)
(check-equal?
(time
(brute 5-char-lowercase-work target-list))
'((#"apple"
. #":{\323\3426\n=)\356\2446\374\373~D\3075\321\27\304-\34\0305B\vk\231B\335O\e")
(#"mmmmm"
.
#"t\341\273b\370\332\273\201%\245\210R\266;\337n\256\366g\313V\254\177|\333\246\3270\\P\242/")
(#"zyzzx"
.
#"\21\25\335\200\17\352\254\357\337H\37\37\220p7J*\201\342x\200\361\2079m\266yX\262\a\313\255"))
"without parallelism, it works")) |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #Raku | Raku | use Digest::SHA256::Native;
constant @alpha2 = [X~] <a m p y z> xx 2;
constant @alpha3 = [X~] <e l m p x z> xx 3;
my %WANTED = set <
3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
>;
sub find_it ( $first_two ) {
for $first_two «~« @alpha3 -> \password {
my \digest_hex = sha256-hex(password);
return "{password} => {digest_hex}" if %WANTED{digest_hex}
}
()
}
.say for flat @alpha2.race(:1batch).map: { find_it($_) }; |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #PureBasic | PureBasic | Structure IO_block
ThreadID.i
StartSeamaphore.i
Value.q
MinimumFactor.i
List Factors.i()
EndStructure
;\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Declare Factorize(*IO.IO_block)
Declare main()
;\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Main()
End
;\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Procedure Main()
Protected AvailableCpu, MainSemaphore
Protected i, j, qData.q, Title$, Message$
NewList T.IO_block()
;
AvailableCpu = Val(GetEnvironmentVariable("NUMBER_OF_PROCESSORS"))
If AvailableCpu<1: AvailableCpu=1: EndIf
MainSemaphore = CreateSemaphore(AvailableCpu)
;
Restore Start_of_data
For i=1 To (?end_of_data-?Start_of_data) / SizeOf(Quad)
; Start all threads at ones, they will then be let to
; self-oganize according to the availiable Cores.
AddElement(T())
Read.q qData
T()\Value = qData
T()\StartSeamaphore = MainSemaphore
T()\ThreadID = CreateThread(@Factorize(), @T())
Next
;
ForEach T()
; Wait for all threads to complete their work and
; find the smallest factor from eact task.
WaitThread(T()\ThreadID)
Next
;
i = OffsetOf(IO_block\MinimumFactor)
SortStructuredList(T(), #PB_Sort_Integer, i, #PB_Sort_Descending)
FirstElement(T())
Title$="Info"
Message$="Number "+Str(T()\Value)+" has largest minimal factor:"+#CRLF$
ForEach T()\Factors()
Message$ + Str(T()\Factors())+" "
Next
MessageRequester(Title$, Message$)
EndProcedure
ProcedureDLL Factorize(*IO.IO_block) ; Fill list Factors() with the factor parts of Number
;Based on http://rosettacode.org/wiki/Prime_decomposition#PureBasic
With *IO
Protected Value.q=\Value
WaitSemaphore(\StartSeamaphore)
Protected I = 3
ClearList(\Factors())
While Value % 2 = 0
AddElement(\Factors())
\Factors() = 2
Value / 2
Wend
Protected Max = Value
While I <= Max And Value > 1
While Value % I = 0
AddElement(\Factors())
\Factors() = I
Value / I
Wend
I + 2
Wend
SortList(\Factors(), #PB_Sort_Ascending)
FirstElement(\Factors())
\MinimumFactor=\Factors()
SignalSemaphore(\StartSeamaphore)
EndWith ;*IO
EndProcedure
DataSection
Start_of_data: ; Same numbers as Ada
Data.q 12757923, 12878611, 12757923, 15808973, 15780709, 197622519
end_of_data:
EndDataSection
|
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Groovy | Groovy | def evaluateRPN(expression) {
def stack = [] as Stack
def binaryOp = { action -> return { action.call(stack.pop(), stack.pop()) } }
def actions = [
'+': binaryOp { a, b -> b + a },
'-': binaryOp { a, b -> b - a },
'*': binaryOp { a, b -> b * a },
'/': binaryOp { a, b -> b / a },
'^': binaryOp { a, b -> b ** a }
]
expression.split(' ').each { item ->
def action = actions[item] ?: { item as BigDecimal }
stack.push(action.call())
println "$item: $stack"
}
assert stack.size() == 1 : "Unbalanced Expression: $expression ($stack)"
stack.pop()
} |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AppleScript | AppleScript | use framework "Foundation"
------ CASE-INSENSITIVE PALINDROME, IGNORING SPACES ? ----
-- isPalindrome :: String -> Bool
on isPalindrome(s)
s = intercalate("", reverse of characters of s)
end isPalindrome
-- toSpaceFreeLower :: String -> String
on spaceFreeToLower(s)
script notSpace
on |λ|(s)
s is not space
end |λ|
end script
intercalate("", filter(notSpace, characters of toLower(s)))
end spaceFreeToLower
--------------------------- TEST -------------------------
on run
isPalindrome(spaceFreeToLower("In girum imus nocte et consumimur igni"))
--> true
end run
-------------------- GENERIC FUNCTIONS -------------------
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- toLower :: String -> String
on toLower(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[GapfulQ, GetFirstPalindromicGapfulNumbers]
GapfulQ[n_Integer] := Divisible[n, FromDigits[IntegerDigits[n][[{1, -1}]]]]
GetFirstPalindromicGapfulNumbers[startend_, n_Integer] :=
Module[{out = {}, i, new, digs, id},
digs = 1;
While[Length[out] < n,
Do[
id = IntegerDigits[i, 10, Ceiling[digs/2]];
If[OddQ[digs],
new = Join[{startend}, id, Rest@Reverse[id], {startend}]
,
new = Join[{startend}, id, Reverse[id], {startend}]
];
new //= FromDigits;
If[GapfulQ[new],
AppendTo[out, new]
];
i++;
,
{i, 0, 10^Ceiling[digs/2] - 1}
];
digs += 1;
];
Take[out, n]
]
Print["First 20 palindromic gapful numbers >100 ending with each digit from 1 to 9:"]
Print[GetFirstPalindromicGapfulNumbers[#, 20]] & /@ Range[9];
Print["86th to 100th:"]
Print[GetFirstPalindromicGapfulNumbers[#, 100][[86 ;; 100]]] & /@ Range[9];
Print["991st to 1000th:"]
Print[GetFirstPalindromicGapfulNumbers[#, 1000][[991 ;; 1000]]] & /@ Range[9]; |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Perl | Perl | my %prec = (
'^' => 4,
'*' => 3,
'/' => 3,
'+' => 2,
'-' => 2,
'(' => 1
);
my %assoc = (
'^' => 'right',
'*' => 'left',
'/' => 'left',
'+' => 'left',
'-' => 'left'
);
sub shunting_yard {
my @inp = split ' ', $_[0];
my @ops;
my @res;
my $report = sub { printf "%25s %-7s %10s %s\n", "@res", "@ops", $_[0], "@inp" };
my $shift = sub { $report->("shift @_"); push @ops, @_ };
my $reduce = sub { $report->("reduce @_"); push @res, @_ };
while (@inp) {
my $token = shift @inp;
if ( $token =~ /\d/ ) { $reduce->($token) }
elsif ( $token eq '(' ) { $shift->($token) }
elsif ( $token eq ')' ) {
while ( @ops and "(" ne ( my $x = pop @ops ) ) { $reduce->($x) }
} else {
my $newprec = $prec{$token};
while (@ops) {
my $oldprec = $prec{ $ops[-1] };
last if $newprec > $oldprec;
last if $newprec == $oldprec and $assoc{$token} eq 'right';
$reduce->( pop @ops );
}
$shift->($token);
}
}
$reduce->( pop @ops ) while @ops;
@res;
}
local $, = " ";
print shunting_yard '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3';
|
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #Racket | Racket |
#lang racket
(define MAX_N 33)
(define BRANCH 4)
(define rooted (make-vector MAX_N 0))
(define unrooted (make-vector MAX_N 0))
(for ([i 2]) (vector-set! rooted i 1) (vector-set! unrooted i 1))
(define (vector-inc! v i d) (vector-set! v i (+ d (vector-ref v i))))
(define (choose m k)
(if (= k 1) m
(for/fold ([r m]) ([i (in-range 1 k)]) (/ (* r (+ m i)) (add1 i)))))
(define (tree br n cnt sum l)
(let/ec return
(for ([b (in-range (add1 br) (add1 BRANCH))])
(define s (+ sum (* (- b br) n)))
(when (>= s MAX_N) (return))
(define c (* (choose (vector-ref rooted n) (- b br)) cnt))
(when (< (* l 2) s) (vector-inc! unrooted s c))
(when (= b BRANCH) (return))
(vector-inc! rooted s c)
(for ([m (in-range (sub1 n) 0 -1)]) (tree b m c s l)))))
(define (bicenter s)
(when (even? s)
(vector-inc! unrooted s (* (vector-ref rooted (/ s 2))
(add1 (vector-ref rooted (/ s 2)))
1/2))))
(for ([n (in-range 1 MAX_N)])
(tree 0 n 1 1 n)
(bicenter n)
(printf "~a: ~a\n" n (vector-ref unrooted n)))
|
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #Raku | Raku | sub count-unrooted-trees(Int $max-branches, Int $max-weight) {
my @rooted = flat 1,1,0 xx $max-weight - 1;
my @unrooted = flat 1,1,0 xx $max-weight - 1;
sub count-trees-with-centroid(Int $radius) {
sub add-branches(
Int $branches, # number of branches to add
Int $w, # weight of heaviest branch to add
Int $weight is copy, # accumulated weight of tree
Int $choices is copy, # number of choices so far
) {
$choices *= @rooted[$w];
for 1 .. $branches -> $b {
($weight += $w) <= $max-weight or last;
@unrooted[$weight] += $choices if $weight > 2*$radius;
if $b < $branches {
@rooted[$weight] += $choices;
add-branches($branches - $b, $_, $weight, $choices) for 1 ..^ $w;
$choices = $choices * (@rooted[$w] + $b) div ($b + 1);
}
}
}
add-branches($max-branches, $radius, 1, 1);
}
sub count-trees-with-bicentroid(Int $weight) {
if $weight %% 2 {
my \halfs = @rooted[$weight div 2];
@unrooted[$weight] += (halfs * (halfs + 1)) div 2;
}
}
gather {
take 1;
for 1 .. $max-weight {
count-trees-with-centroid($_);
count-trees-with-bicentroid($_);
take @unrooted[$_];
}
}
}
my constant N = 100;
my @paraffins = count-unrooted-trees(4, N);
say .fmt('%3d'), ': ', @paraffins[$_] for flat 1 .. 30, N; |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #CoffeeScript | CoffeeScript |
is_pangram = (s) ->
# This is optimized for longish strings--as soon as all 26 letters
# are encountered, we will be done. Our worst case scenario is a really
# long non-pangram, or a really long pangram with at least one letter
# only appearing toward the end of the string.
a_code = 'a'.charCodeAt(0)
required_letters = {}
for i in [a_code...a_code+26]
required_letters[String.fromCharCode(i)] = true
cnt = 0
for c in s
c = c.toLowerCase()
if required_letters[c]
cnt += 1
return true if cnt == 26
delete required_letters[c]
false
do ->
tests = [
["is this a pangram", false]
["The quick brown fox jumps over the lazy dog", true]
]
for test in tests
[s, exp_value] = test
throw Error("fail") if is_pangram(s) != exp_value
# try long strings
long_str = ''
for i in [1..500000]
long_str += s
throw Error("fail") if is_pangram(long_str) != exp_value
console.log "Passed tests: #{s}"
|
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #Julia | Julia | julia> [binomial(j,i) for i in 0:4, j in 0:4]
5×5 Array{Int64,2}:
1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1
julia> [binomial(i,j) for i in 0:4, j in 0:4]
5×5 Array{Int64,2}:
1 0 0 0 0
1 1 0 0 0
1 2 1 0 0
1 3 3 1 0
1 4 6 4 1
julia> [binomial(j+i,i) for i in 0:4, j in 0:4]
5×5 Array{Int64,2}:
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
|
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Delphi | Delphi | program PascalsTriangle;
procedure Pascal(r:Integer);
var
i, c, k:Integer;
begin
for i := 0 to r - 1 do
begin
c := 1;
for k := 0 to i do
begin
Write(c:3);
c := c * (i - k) div (k + 1);
end;
Writeln;
end;
end;
begin
Pascal(9);
end. |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #Racket | Racket |
#lang racket
(require racket/dict)
(define (RPN->infix expr)
(define-values (res _)
(for/fold ([stack '()] [prec '()]) ([t expr])
(show t stack prec)
(cond
[(dict-has-key? operators t)
(match-define (list pt at) (dict-ref operators t))
(match-define (list y x ss ...) stack)
(match-define (list py px ps ...) prec)
(define fexpr
(cond
[(> pt (max px py)) "(~a) ~a (~a)"]
[(or (< px pt) (and (= pt px) (eq? at 'r))) "(~a) ~a ~a"]
[(or (< py pt) (and (= pt py) (eq? at 'l))) "~a ~a (~a)"]
[else "~a ~a ~a"]))
(define term (format fexpr x t y))
(values (cons term ss) (cons pt ps))]
[else (values (cons t stack) (cons +inf.0 prec))])))
(car res))
;; the list of operators and their properties
(define operators '((+ 2 l) (- 2 l) (* 3 l) (/ 3 l) (^ 4 r)))
;; printing out the intermediate stages
(define (show t stack prec)
(printf "~a\t" t)
(for ([s stack] [p prec])
(if (eq? +inf.0 p) (printf "[~a] " s) (printf "[~a {~a}] " s p)))
(newline))
|
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #Raku | Raku | sub p ($pair, $prec) { $pair.key < $prec ?? "( {$pair.value} )" !! $pair.value }
sub rpm-to-infix($string) {
my @stack;
for $string.words {
when /\d/ { @stack.push: 9 => $_ }
my ($y,$x) = @stack.pop, @stack.pop;
when '^' { @stack.push: 4 => ~(p($x,5), $_, p($y,4)) }
when '*' | '/' { @stack.push: 3 => ~(p($x,3), $_, p($y,3)) }
when '+' | '-' { @stack.push: 2 => ~(p($x,2), $_, p($y,2)) }
}
($string, @stack».value).join("\n") ~ "\n";
}
say rpm-to-infix $_ for
'3 4 2 * 1 5 - 2 3 ^ ^ / +',
'1 2 + 3 4 + ^ 5 6 + ^'; |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Python | Python | from functools import partial
def fs(f, s): return [f(value) for value in s]
def f1(value): return value * 2
def f2(value): return value ** 2
fsf1 = partial(fs, f1)
fsf2 = partial(fs, f2)
s = [0, 1, 2, 3]
assert fs(f1, s) == fsf1(s) # == [0, 2, 4, 6]
assert fs(f2, s) == fsf2(s) # == [0, 1, 4, 9]
s = [2, 4, 6, 8]
assert fs(f1, s) == fsf1(s) # == [4, 8, 12, 16]
assert fs(f2, s) == fsf2(s) # == [4, 16, 36, 64] |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Quackery | Quackery | [ [] unrot
swap nested
' join nested
join nested
' witheach nested
swap join
do ] is fs ( f s --> [ )
[ 2 * ] is f1 ( n --> n )
[ 2 ** ] is f2 ( n --> n )
[ ' f1 swap fs ] is fsf1 ( s --> [ )
[ ' f2 swap fs ] is fsf2 ( s --> [ )
' [ 0 1 2 3 ] fsf1 echo cr
' [ 0 1 2 3 ] fsf2 echo cr
' [ 2 4 6 8 ] fsf1 echo cr
' [ 2 4 6 8 ] fsf2 echo cr
( ... or, using Quackery's partial applicator "witheach",
which applies the word or nest following it to each
item in a nest on the top of the stack ... )
cr
' [ [ 0 1 2 3 ] [ 2 4 6 8 ] ]
witheach
[ dup ' [ fsf1 fsf2 ]
witheach [ do echo cr ] ] |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #Raku | Raku | my @chars =
set('a' .. 'z'),
set('A' .. 'Z'),
set('0' .. '9'),
set(<!"#$%&'()*+,-./:;<=>?@[]^_{|}~>.comb);
# bleh. unconfuse syntax highlighter. '"
sub MAIN ( Int :$l = 8, Int :$c = 1, Str :$x = '' ) {
note 'Password length must be >= 4' and exit if $l < 4;
note 'Can not generate fewer than 0 passwords' and exit if $c < 0;
my $chars = [∪] @chars».=&filter;
note 'Can not exclude an entire required character group' and exit
if any(@chars».elems) == 0;
for ^$c {
my @pswd;
@pswd.push( @chars[$_].roll ) for ^4;
@pswd.push( $chars .roll ) for 4 ..^ $l;
say [~] @pswd.pick(*);
}
sub filter (Set $set) { $set ∖ set($x.comb) }
}
sub USAGE() {
say qq:to/END/;
Specify a length: --l=8 (default 8),
Specify a count: --c=1 (default 1),
Specify characters to exclude: --x=
(must escape characters significant to the shell)
E.G.
{$*PROGRAM-NAME} --l=14 --c=5 --x=0O\\\"\\\'1l\\\|I
END
} |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #Rust | Rust | // [dependencies]
// rust-crypto = "0.2.36"
// num_cpus = "1.7.0"
// hex = "0.2.0"
extern crate crypto;
extern crate num_cpus;
extern crate hex;
use std::thread;
use std::cmp::min;
use crypto::sha2::Sha256;
use crypto::digest::Digest;
use hex::{FromHex, ToHex};
fn main() {
let hashes = vec![
decode("1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"),
decode("3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"),
decode("74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"),
];
let mut threads = Vec::new();
let mut ranges = distribute_work();
while let Some(range) = ranges.pop() {
let hashes = hashes.clone();
threads.push(thread::spawn(
move || search(range.0, range.1, hashes.clone()),
));
}
while let Some(t) = threads.pop() {
t.join().ok();
}
}
fn search(from: [u8; 5], to: [u8; 5], hashes: Vec<[u8; 256 / 8]>) {
let mut password = from.clone();
while password <= to {
let mut sha256 = Sha256::new();
sha256.input(&password);
let mut result = [0u8; 256 / 8];
sha256.result(&mut result);
for hash in hashes.iter() {
if *hash == result {
println!(
"{}{}{}{}{} {}",
password[0] as char,
password[1] as char,
password[2] as char,
password[3] as char,
password[4] as char,
hash.to_hex()
);
}
}
password = next(&password);
}
}
fn next(password: &[u8; 5]) -> [u8; 5] {
let mut result = password.clone();
for i in (0..result.len()).rev() {
if result[i] == b'z' {
if i == 0 {
result[i] = b'z' + 1;
} else {
result[i] = b'a';
}
} else {
result[i] += 1;
break;
}
}
result.clone()
}
fn distribute_work() -> Vec<([u8; 5], [u8; 5])> {
let mut ranges = Vec::new();
let num_cpus = min(num_cpus::get(), 26) as u8;
let div = 25 / num_cpus;
let mut remainder = 25 % num_cpus;
let mut from = b'a';
while from < b'z' {
let to = from + div +
if remainder > 0 {
remainder -= 1;
1
} else {
0
};
ranges.push((
[from, from, from, from, from + 1].clone(),
[to, to, to, to, to].clone(),
));
from = to;
}
ranges[0].0[4] = b'a';
ranges.clone()
}
fn decode(string: &str) -> [u8; 256 / 8] {
let mut result = [0; 256 / 8];
let vec = Vec::from_hex(string).unwrap();
for i in 0..result.len() {
result[i] = vec[i];
}
result.clone()
} |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #Scala | Scala | import java.security.MessageDigest
import scala.collection.parallel.immutable.ParVector
object EncryptionCracker {
def main(args: Array[String]): Unit = {
val hash1 = "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"
val hash2 = "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"
val hash3 = "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"
val charSet = ('a' to 'z').toVector
val num = 5
for(tmp <- List(hash1, hash2, hash3)){
println(tmp)
crack(tmp, charSet, num) match{
case Some(s) => println(s"String: $s\n")
case None => println("Failed\n")
}
}
}
def crack(hash: String, charSet: Vector[Char], num: Int): Option[String] = {
val perms = charSet
.flatMap(c => Vector.fill(num)(c)).combinations(num) //Generate distinct sets of letters
.to(ParVector) //Convert to ParVector
.flatMap(_.permutations.map(_.mkString)) //Finish generating candidates
perms.find(str => getHash(str).equalsIgnoreCase(hash)) //Search for a matching string
}
def getHash(str: String): String = {
val digester = MessageDigest.getInstance("SHA-256")
digester.digest(str.getBytes("UTF-8")).map("%02x".format(_)).mkString
}
} |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #Python | Python | from concurrent import futures
from math import floor, sqrt
NUMBERS = [
112272537195293,
112582718962171,
112272537095293,
115280098190773,
115797840077099,
1099726829285419]
# NUMBERS = [33, 44, 55, 275]
def lowest_factor(n, _start=3):
if n % 2 == 0:
return 2
search_max = int(floor(sqrt(n))) + 1
for i in range(_start, search_max, 2):
if n % i == 0:
return i
return n
def prime_factors(n, lowest):
pf = []
while n > 1:
pf.append(lowest)
n //= lowest
lowest = lowest_factor(n, max(lowest, 3))
return pf
def prime_factors_of_number_with_lowest_prime_factor(NUMBERS):
with futures.ProcessPoolExecutor() as executor:
low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) )
all_factors = prime_factors(number, low_factor)
return number, all_factors
def main():
print('For these numbers:')
print('\n '.join(str(p) for p in NUMBERS))
number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS)
print(' The one with the largest minimum prime factor is {}:'.format(number))
print(' All its prime factors in order are: {}'.format(all_factors))
if __name__ == '__main__':
main() |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Haskell | Haskell | calcRPN :: String -> [Double]
calcRPN = foldl interprete [] . words
interprete s x
| x `elem` ["+","-","*","/","^"] = operate x s
| otherwise = read x:s
where
operate op (x:y:s) = case op of
"+" -> x + y:s
"-" -> y - x:s
"*" -> x * y:s
"/" -> y / x:s
"^" -> y ** x:s |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Applesoft_BASIC | Applesoft BASIC | 100 DATA"MY DOG HAS FLEAS"
110 DATA"MADAM, I'M ADAM."
120 DATA"1 ON 1"
130 DATA"IN GIRUM IMUS NOCTE ET CONSUMIMUR IGNI"
140 DATA"A man, a plan, a canal: Panama!"
150 DATA"KAYAK"
160 DATA"REDDER"
170 DATA"H"
180 DATA""
200 FOR L1 = 1 TO 9
210 READ W$ : GOSUB 300" IS PALINDROME?
220 PRINT CHR$(34); W$; CHR$(34); " IS ";
230 IF NOT PALINDROME THEN PRINT "NOT ";
240 PRINT "A PALINDROME"
250 NEXT
260 END
300 REMIS PALINDROME?
310 PA = 1
320 L = LEN(W$)
330 IF L = 0 THEN RETURN
340 FOR L0 = 1 TO L / 2 + .5
350 PA = MID$(W$, L0, 1) = MID$(W$, L - L0 + 1, 1)
360 IF PALINDROME THEN NEXT L0
370 RETURN |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Nim | Nim | Forms palindromes using number<->string conversions.
|
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Phix | Phix | with javascript_semantics
bool show_workings = true
constant operators = {"^","*","/","+","-"},
precedence = { 4, 3, 3, 2, 2 }
procedure shunting_yard(string infix, rpn)
string res = "", sep = "", stack_top
sequence stack = {},
ops = split(substitute_all(infix,{"(",")"},{" ( "," ) "}),' ')
printf(1,"Infix input: %-32s%s", {infix,iff(show_workings?'\n':' ')})
for i=1 to length(ops) do
string op = ops[i]
if op="(" then
stack = append(stack,op)
elsif op=")" then
while 1 do
stack_top = stack[$]
stack = stack[1..$-1]
if stack_top="(" then exit end if
res &= sep&stack_top
sep = " "
end while
else
integer k = find(op,operators)
if k!=0 then
integer prec = precedence[k]
while length(stack) do
stack_top = stack[$]
k = find(stack_top,operators)
if k=0 or prec>precedence[k]
or (prec=precedence[k] and stack_top="^") then
exit
end if
stack = stack[1..$-1]
res &= sep&stack_top
sep = " "
end while
stack = append(stack,op)
else
res &= sep&op
sep = " "
end if
end if
if show_workings then
?{op,stack,res}
end if
end for
for i=length(stack) to 1 by -1 do
string op = stack[i]
res &= sep&op
sep = " "
end for
printf(1,"result: %-22s [%s]\n", {res,iff(res=rpn?"ok","**ERROR**")})
end procedure
shunting_yard("3 + 4 * 2 / (1 - 5) ^ 2 ^ 3","3 4 2 * 1 5 - 2 3 ^ ^ / +")
show_workings = false
shunting_yard("((1 + 2) ^ (3 + 4)) ^ (5 + 6)","1 2 + 3 4 + ^ 5 6 + ^")
shunting_yard("(1 + 2) ^ (3 + 4) ^ (5 + 6)","1 2 + 3 4 + 5 6 + ^ ^")
shunting_yard("((3 ^ 4) ^ 2 ^ 9) ^ 2 ^ 5","3 4 ^ 2 9 ^ ^ 2 5 ^ ^")
shunting_yard("(1 + 4) * (5 + 3) * 2 * 3","1 4 + 5 3 + * 2 * 3 *")
shunting_yard("1 * 2 * 3 * 4","1 2 * 3 * 4 *")
shunting_yard("1 + 2 + 3 + 4","1 2 + 3 + 4 +")
shunting_yard("(1 + 2) ^ (3 + 4)","1 2 + 3 4 + ^")
shunting_yard("(5 ^ 6) ^ 7","5 6 ^ 7 ^")
shunting_yard("5 ^ 4 ^ 3 ^ 2","5 4 3 2 ^ ^ ^")
shunting_yard("1 + 2 + 3","1 2 + 3 +")
shunting_yard("1 ^ 2 ^ 3","1 2 3 ^ ^")
shunting_yard("(1 ^ 2) ^ 3","1 2 ^ 3 ^")
shunting_yard("1 - 1 + 3","1 1 - 3 +")
shunting_yard("3 + 1 - 1","3 1 + 1 -")
shunting_yard("1 - (2 + 3)","1 2 3 + -")
shunting_yard("4 + 3 + 2","4 3 + 2 +")
shunting_yard("5 + 4 + 3 + 2","5 4 + 3 + 2 +")
shunting_yard("5 * 4 * 3 * 2","5 4 * 3 * 2 *")
shunting_yard("5 + 4 - (3 + 2)","5 4 + 3 2 + -")
shunting_yard("3 - 4 * 5","3 4 5 * -")
shunting_yard("3 * (4 - 5)","3 4 5 - *")
shunting_yard("(3 - 4) * 5","3 4 - 5 *")
shunting_yard("4 * 2 + 1 - 5","4 2 * 1 + 5 -")
shunting_yard("4 * 2 / (1 - 5) ^ 2","4 2 * 1 5 - 2 ^ /")
|
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #REXX | REXX | /*REXX pgm enumerates (without repetition) the number of paraffins with N carbon atoms. */
parse arg nodes . /*obtain optional argument from the CL.*/
if nodes=='' | nodes=="," then nodes= 100 /*Not specified? Then use the default.*/
rooted. = 0; rooted.0= 1; rooted.1= 1 /*define the base rooted numbers.*/
unrooted. = 0; unrooted.0= 1; unrooted.1= 1 /* " " " unrooted " */
numeric digits max(9, nodes % 2) /*this program may use gihugeic numbers*/
w= length(nodes) /*W: used for aligning formatted nodes*/
say right(0, w) unrooted.0 /*show enumerations of 0 carbon atoms*/
/* [↓] process all nodes (up to NODES)*/
do C=1 for nodes; h= C % 2 /*C: is the number of carbon atoms. */
call tree 0, C, C, 1, 1 /* [↓] if # of carbon atoms is even···*/
if \(C//2) then unrooted.C= unrooted.C + rooted.h * (rooted.h + 1) % 2
say right(C, w) unrooted.C /*display an aligned formatted number. */
end /*C*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tree: procedure expose rooted. unrooted. nodes #. /*this function is recursive.*/
parse arg br,n,L,sum,cnt; nm= n - 1; LL= L + L
brp= br + 1
do b=brp to 4; sum= sum + n
if sum>nodes then leave
if b==4 then if LL>=sum then leave
if b==brp then #.br= rooted.n * cnt
else #.br= #.br * (rooted.n + b - brp) % (b - br)
if LL<sum then unrooted.sum= unrooted.sum + #.br
if b==4 then leave
rooted.sum= rooted.sum + #.br
do m=nm by -1 for nm; call tree b, m, L, sum, #.br
end /*m*/
end /*b*/ /* ↑↑↑↑↑↑↑↑↑ recursive. */
return |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Comal | Comal | 0010 FUNC pangram#(s$) CLOSED
0020 FOR i#:=ORD("A") TO ORD("Z") DO
0030 IF NOT (CHR$(i#) IN s$ OR CHR$(i#+32) IN s$) THEN RETURN FALSE
0040 ENDFOR i#
0050 RETURN TRUE
0060 ENDFUNC
0070 //
0080 WHILE NOT EOD DO
0090 READ s$
0100 PRINT "'",s$,"' is ",
0110 IF NOT pangram#(s$) THEN PRINT "not ",
0120 PRINT "a pangram"
0130 ENDWHILE
0140 END
0150 DATA "The quick brown fox jumps over the lazy dog."
0160 DATA "The five boxing wizards dump quickly." |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Common_Lisp | Common Lisp | (defun pangramp (s)
(null (set-difference
(loop for c from (char-code #\A) upto (char-code #\Z) collect (code-char c))
(coerce (string-upcase s) 'list)))) |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #Kotlin | Kotlin | // version 1.1.3
fun binomial(n: Int, k: Int): Int {
if (n < k) return 0
if (n == 0 || k == 0) return 1
val num = (k + 1..n).fold(1) { acc, i -> acc * i }
val den = (2..n - k).fold(1) { acc, i -> acc * i }
return num / den
}
fun pascalUpperTriangular(n: Int) = List(n) { i -> IntArray(n) { j -> binomial(j, i) } }
fun pascalLowerTriangular(n: Int) = List(n) { i -> IntArray(n) { j -> binomial(i, j) } }
fun pascalSymmetric(n: Int) = List(n) { i -> IntArray(n) { j -> binomial(i + j, i) } }
fun printMatrix(title: String, m: List<IntArray>) {
val n = m.size
println(title)
print("[")
for (i in 0 until n) {
if (i > 0) print(" ")
print(m[i].contentToString())
if (i < n - 1) println(",") else println("]\n")
}
}
fun main(args: Array<String>) {
printMatrix("Pascal upper-triangular matrix", pascalUpperTriangular(5))
printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
printMatrix("Pascal symmetric matrix", pascalSymmetric(5))
} |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #DWScript | DWScript | procedure Pascal(r : Integer);
var
i, c, k : Integer;
begin
for i:=0 to r-1 do begin
c:=1;
for k:=0 to i do begin
Print(Format('%4d', [c]));
c:=(c*(i-k)) div (k+1);
end;
PrintLn('');
end;
end;
Pascal(9); |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #REXX | REXX | /*REXX program converts Reverse Polish Notation (RPN) ───► an infix notation. */
showAction = 1 /* 0 if no showActions wanted. */
# = 0 /*initialize stack pointer to 0 (zero).*/
oS = '+ - / * ^' /*the operator symbols. */
oP = '2 2 3 3 4' /*the operator priorities. */
oA = '◄ ◄ ◄ ◄ ►' /*the operator associations. */
say "infix: " toInfix( "3 4 2 * 1 5 - 2 3 ^ ^ / +" )
say "infix: " toInfix( "1 2 + 3 4 + ^ 5 6 + ^" ) /* [↓] Sprechen Sie Deutsch? */
say "infix: " toInfix( "Mond Sterne Schlamm + * Feur Suppe * ^" )
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
pop: pop= #; #= # - 1; return @.pop
push: #= # + 1; @.#= arg(1); return
/*──────────────────────────────────────────────────────────────────────────────────────*/
stack2str: $=; do j=1 for #; _ = @.j; y= left(_, 1)
if pos(' ', _)==0 then _ = '{'strip( substr(_, 2) )"}"
else _ = substr(_, 2)
$=$ '{'strip(y _)"}"
end /*j*/
return space($)
/*──────────────────────────────────────────────────────────────────────────────────────*/
toInfix: parse arg rpn; say copies('─', 80 - 1); say 'RPN: ' space(rpn)
do N=1 for words(RPN) /*process each of the RPN tokens.*/
?= word(RPN, N) /*obtain next item in the list. */
if pos(?,oS)==0 then call push '¥' ? /*when in doubt, add a Yen to it.*/
else do; g= pop(); gp= left(g, 1); g= substr(g, 2)
h= pop(); hp= left(h, 1); h= substr(h, 2)
tp= substr(oP, pos(?, oS), 1)
ta= substr(oA, pos(?, oS), 1)
if hp<tp | (hp==tp & ta=='►') then h= "("h")"
if gp<tp | (gp==tp & ta=='◄') then g= "("g")"
call push tp || h ? g
end
if showAction then say right(?, 25) "──►" stack2str()
end /*N*/
return space( substr( pop(), 2) ) |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #R | R | partially.apply <- function(f, ...) {
capture <- list(...)
function(...) {
do.call(f, c(capture, list(...)))
}
}
fs <- function(f, ...) sapply(list(...), f)
f1 <- function(x) 2*x
f2 <- function(x) x^2
fsf1 <- partially.apply(fs, f1)
fsf2 <- partially.apply(fs, f2)
fsf1(0:3)
fsf2(0:3)
fsf1(seq(2,8,2))
fsf2(seq(2,8,2)) |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Racket | Racket |
#lang racket
(define (fs f s) (map f s))
(define (f1 n) (* n 2))
(define (f2 n) (* n n))
(define fsf1 (curry fs f1))
(define fsf2 (curry fs f2))
(fsf1 '(0 1 2 3))
(fsf1 '(2 4 6 8))
(fsf2 '(0 1 2 3))
(fsf2 '(2 4 6 8))
|
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #REXX | REXX | /*REXX program generates a random password according to the Rosetta Code task's rules.*/
@L='abcdefghijklmnopqrstuvwxyz'; @U=@L; upper @U /*define lower-, uppercase Latin chars.*/
@#= 0123456789 /* " " string of base ten numerals.*/
@@= '!"#$%&()+,-./:;<=>?@[]^{|}~' || "'" /*define a bunch of special characters.*/
parse arg L N seed xxx yyy . /*obtain optional arguments from the CL*/
if L=='?' then signal help /*does user want documentation shown? */
if L=='' | L=="," then L=8 /*Not specified? Then use the default.*/
if N=='' | N=="," then N=1 /* " " " " " " */
if xxx\=='' then call weed xxx /*Any chars to be ignored? Scrub lists*/
if yyy\=='' then call weed x2c(yyy) /*Hex " " " " " " */
if datatype(seed,'W') then call random ,,seed /*the seed for repeatable RANDOM BIF #s*/
if \datatype(L, 'W') then call serr "password length, it isn't an integer: " L
if L<4 then call serr "password length, it's too small (< 4): " L
if L>80 then call serr "password length, it's too large (> 80): " L
if \datatype(N, 'W') then call serr "number of passwords, it isn't an integer: " N
do g=1 to N; $= /*generate N passwords (default is one)*/
do k=1 for L; z=k; if z>4 then z=random(1,4) /*1st four parts │ random*/
if z==1 then $=$ || substr(@L,random(1,length(@L)),1) /*append lowercase letter*/
if z==2 then $=$ || substr(@U,random(1,length(@U)),1) /* " uppercase " */
if z==3 then $=$ || substr(@#,random(1,length(@#)),1) /* " numeral */
if z==4 then $=$ || substr(@@,random(1,length(@@)),1) /* " special character*/
end /*k*/
/* [↓] scrambles PW, hides gen order. */
do a=1 for L; b=random(1, L) /*swap every character with another. */
parse var $ =(a) x +1 =(b) y +1 /*≡ x=substr($,a,1); y=substr($,b,1) */
$=overlay(x,$,b); $=overlay(y,$,a) /*(both statements) swap two characters*/
end /*L+L*/ /* [↑] more swaps obfuscates gen order*/
say right(g, length(N)) 'password is: ' $ /*display the Nth password to console*/
/* call lineout 'GENPW.PW', $ */ /*and also write the password to a file*/ /*or not.*/
end /*g*/ /* [↑] {a comment} fileID= GENPW.PW */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
weed: parse arg ig; @L=dont(@L); @U=dont(@U); @#=dont(@#); @@=dont(@@); return
dont: return space( translate(arg(1), , ig), 0) /*remove chars from a list*/
serr: say; say '***error*** invalid' arg(1); exit 13 /*display an error message*/
help: signal .; .: do j=sigL+1 to sourceline(); say strip(left(sourceline(j),79)); end /*
╔═════════════════════════════════════════════════════════════════════════════╗
║ GENPW ? ◄─── shows this documentation. ║
║ GENPW ◄─── generates 1 password (with length 8). ║
║ GENPW len ◄─── generates (all) passwords with this length║
║ GENPW , n ◄─── generates N number of passwords. ║
║ GENPW , , seed ◄─── generates passwords using a random seed. ║
║ GENPW , , , xxx ◄─── generates passwords that don't contain xxx║
║ GENPW , , , , yyy ◄─── generates passwords that don't contain yyy║
║ ║
╟──────────── where [if a comma (,) is specified, the default is used]: ║
║ len is the length of the passwords to be generated. The default is 8.║
║ The minimum is 4, the maximum is 80. ║
║ n is the number of passwords to be generated. The default is 1.║
║ seed is an integer seed used for the RANDOM BIF. (Default is random.)║
║ xxx are characters to NOT be used for generating passwords. ║
║ The default is to use all the (normal) available characters. ║
║ yyy (same as XXX, except the chars are expressed as hexadecimal pairs).║
╚═════════════════════════════════════════════════════════════════════════════╝ */ |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #Sidef | Sidef | func invert_sha256(hash) {
var letters = @('a'..'z')
var job = func (prefix, hash) {
variations_with_repetition(letters, 4, {|*a|
var s = join('', prefix, a...)
return s if (s.sha256 == hash)
})
return nil
}
letters.map {|prefix|
job.ffork(prefix, hash)
}.each {|f|
with (f.wait) { return _ }
}
}
var tests = %w(
1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
)
tests.each {|t|
var phrase = invert_sha256(t)
say "#{t} : #{phrase}"
} |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #Swift | Swift | import Foundation
import CryptoKit
extension String {
func hexdata() -> Data {
Data(stride(from: 0, to: count, by: 2).map {
let a = index(startIndex, offsetBy: $0)
let b = index(after: a)
return UInt8(self[a ... b], radix: 16)!
})
}
}
DispatchQueue.concurrentPerform(iterations: 26) { (a) in
let goal1 = "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad".hexdata()
let goal2 = "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b".hexdata()
let goal3 = "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f".hexdata()
var letters: [UInt8] = [(UInt8)(a + 97), 0, 0, 0, 0]
for b: UInt8 in 97...122 {
letters[1] = b
for c: UInt8 in 97...122 {
letters[2] = c
for d: UInt8 in 97...122 {
letters[3] = d
for e: UInt8 in 97...122 {
letters[4] = e
let digest = SHA256.hash(data: letters)
if digest == goal1 || digest == goal2 || digest == goal3 {
let password = String(bytes: letters, encoding: .ascii)!
let hexhash = digest.map { String(format: "%02x", $0) }.joined()
print("\(password) => \(hexhash)")
}
}
}
}
}
} |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #Racket | Racket |
#lang racket
(require math)
(provide main)
(define (smallest-factor n)
(list (first (first (factorize n))) n))
(define numbers
'(112272537195293 112582718962171 112272537095293
115280098190773 115797840077099 1099726829285419))
(define (main)
; create as many instances of Racket as
; there are numbers:
(define ps
(for/list ([_ numbers])
(place ch
(place-channel-put
ch
(smallest-factor
(place-channel-get ch))))))
; send the numbers to the instances:
(map place-channel-put ps numbers)
; get the results and find the maximum:
(argmax first (map place-channel-get ps)))
|
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #Raku | Raku | my @nums = 64921987050997300559, 70251412046988563035, 71774104902986066597,
83448083465633593921, 84209429893632345702, 87001033462961102237,
87762379890959854011, 89538854889623608177, 98421229882942378967,
259826672618677756753, 262872058330672763871, 267440136898665274575,
278352769033314050117, 281398154745309057242, 292057004737291582187;
my @factories = @nums.hyper(:3batch).map: &prime-factors;
printf "%21d factors: %s\n", |$_ for @nums Z @factories;
my $gmf = {}.append(@factories»[0] »=>« @nums).max: +*.key;
say "\nGreatest minimum factor: ", $gmf.key;
say "from: { $gmf.value }\n";
say 'Run time: ', now - INIT now;
say '-' x 80;
# For amusements sake and for relative comparison, using the same 100
# numbers as in the SequenceL example, testing with different numbers of threads.
@nums = <625070029 413238785 815577134 738415913 400125878 967798656 830022841
774153795 114250661 259366941 571026384 522503284 757673286 509866901 6303092
516535622 177377611 520078930 996973832 148686385 33604768 384564659 95268916
659700539 149740384 320999438 822361007 701572051 897604940 2091927 206462079
290027015 307100080 904465970 689995756 203175746 802376955 220768968 433644101
892007533 244830058 36338487 870509730 350043612 282189614 262732002 66723331
908238109 635738243 335338769 461336039 225527523 256718333 277834108 430753136
151142121 602303689 847642943 538451532 683561566 724473614 422235315 921779758
766603317 364366380 60185500 333804616 988528614 933855820 168694202 219881490
703969452 308390898 567869022 719881996 577182004 462330772 770409840 203075270
666478446 351859802 660783778 503851023 789751915 224633442 347265052 782142901
43731988 246754498 736887493 875621732 594506110 854991694 829661614 377470268
984990763 275192380 39848200 892766084 76503760>».Int;
for 1..8 -> $degree {
my $start = now;
my \factories = @nums.hyper(:degree($degree), :3batch).map: &prime-factors;
my $gmf = {}.append(factories»[0] »=>« @nums).max: +*.key;
say "\nFactoring {+@nums} numbers, greatest minimum factor: {$gmf.key}";
say "Using: $degree thread{ $degree > 1 ?? 's' !! ''}";
my $end = now;
say 'Run time: ', $end - $start, ' seconds.';
}
# Prime factoring routines from the Prime decomposition task
sub prime-factors ( Int $n where * > 0 ) {
return $n if $n.is-prime;
return [] if $n == 1;
my $factor = find-factor( $n );
sort flat prime-factors( $factor ), prime-factors( $n div $factor );
}
sub find-factor ( Int $n, $constant = 1 ) {
return 2 unless $n +& 1;
if (my $gcd = $n gcd 6541380665835015) > 1 {
return $gcd if $gcd != $n
}
my $x = 2;
my $rho = 1;
my $factor = 1;
while $factor == 1 {
$rho *= 2;
my $fixed = $x;
for ^$rho {
$x = ( $x * $x + $constant ) % $n;
$factor = ( $x - $fixed ) gcd $n;
last if 1 < $factor;
}
}
$factor = find-factor( $n, $constant + 1 ) if $n == $factor;
$factor;
} |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.