code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import java.io.{File, PrintWriter}
object GloballyReplaceText extends App {
val (charsetName, fileNames) = ("UTF8", Seq("file1.txt", "file2.txt"))
for (fileHandle <- fileNames.map(new File(_)))
new PrintWriter(fileHandle, charsetName) {
print(scala.io.Source.fromFile(fileHandle, charsetName).mkString
.replace("Goodbye London!", "Hello New York!"))
close()
}
} | 781Globally replace text in several files
| 16scala
| etvab |
def rand = new Random() | 776Guess the number/With feedback
| 7groovy
| t5qfh |
import java.util.HashSet;
public class Happy{
public static boolean happy(long number){
long m = 0;
int digit = 0;
HashSet<Long> cycle = new HashSet<Long>();
while(number != 1 && cycle.add(number)){
m = 0;
while(number > 0){
digit = (int)(number % 10);
m += digit*digit;
number /= 10;
}
number = m;
}
return number == 1;
}
public static void main(String[] args){
for(long num = 1,count = 0;count<8;num++){
if(happy(num)){
System.out.println(num);
count++;
}
}
}
} | 771Happy numbers
| 9java
| z4ntq |
struct Harshad: Sequence, IteratorProtocol {
private var i = 0
mutating func next() -> Int? {
while true {
i += 1
if i% Array(String(i)).map(String.init).compactMap(Int.init).reduce(0, +) == 0 {
return i
}
}
}
}
print("First 20: \(Array(Harshad().prefix(20)))")
print("First over a 1000: \(Harshad().first(where: { $0 > 1000 })!)") | 762Harshad or Niven series
| 17swift
| gqb49 |
use strict;
use warnings;
use Tk;
my $main = MainWindow->new;
$main->Label(-text => 'Goodbye, World')->pack;
MainLoop(); | 767Hello world/Graphical
| 2perl
| sm0q3 |
import java.math.BigInteger;
import java.util.PriorityQueue;
final class Hamming {
private static BigInteger THREE = BigInteger.valueOf(3);
private static BigInteger FIVE = BigInteger.valueOf(5);
private static void updateFrontier(BigInteger x,
PriorityQueue<BigInteger> pq) {
pq.offer(x.shiftLeft(1));
pq.offer(x.multiply(THREE));
pq.offer(x.multiply(FIVE));
}
public static BigInteger hamming(int n) {
if (n <= 0)
throw new IllegalArgumentException("Invalid parameter");
PriorityQueue<BigInteger> frontier = new PriorityQueue<BigInteger>();
updateFrontier(BigInteger.ONE, frontier);
BigInteger lowest = BigInteger.ONE;
for (int i = 1; i < n; i++) {
lowest = frontier.poll();
while (frontier.peek().equals(lowest))
frontier.poll();
updateFrontier(lowest, frontier);
}
return lowest;
}
public static void main(String[] args) {
System.out.print("Hamming(1 .. 20) =");
for (int i = 1; i < 21; i++)
System.out.print(" " + hamming(i));
System.out.println("\nHamming(1691) = " + hamming(1691));
System.out.println("Hamming(1000000) = " + hamming(1000000));
}
} | 780Hamming numbers
| 9java
| och8d |
import Control.Monad
import System.Random
until_ act pred = act >>= pred >>= flip unless (until_ act pred)
answerIs ans guess =
case compare ans guess of
LT -> putStrLn "Too high. Guess again." >> return False
EQ -> putStrLn "You got it!" >> return True
GT -> putStrLn "Too low. Guess again." >> return False
ask = do line <- getLine
case reads line of
((num,_):_) -> return num
otherwise -> putStrLn "Please enter a number." >> ask
main = do
ans <- randomRIO (1,100) :: IO Int
putStrLn "Try to guess my secret number between 1 and 100."
ask `until_` answerIs ans | 776Guess the number/With feedback
| 8haskell
| kovh0 |
function happy(number) {
var m, digit ;
var cycle = [] ;
while(number != 1 && cycle[number] !== true) {
cycle[number] = true ;
m = 0 ;
while (number > 0) {
digit = number % 10 ;
m += digit * digit ;
number = (number - digit) / 10 ;
}
number = m ;
}
return (number == 1) ;
}
var cnt = 8 ;
var number = 1 ;
while(cnt-- > 0) {
while(!happy(number))
number++ ;
document.write(number + " ") ;
number++ ;
} | 771Happy numbers
| 10javascript
| 9h3ml |
if (!class_exists('gtk'))
{
die();
}
$wnd = new GtkWindow();
$wnd->set_title('Goodbye world');
$wnd->connect_simple('destroy', array('gtk', 'main_quit'));
$lblHello = new GtkLabel();
$wnd->add($lblHello);
$wnd->show_all();
Gtk::main(); | 767Hello world/Graphical
| 12php
| ue5v5 |
local _M = {}
local bit = require('bit')
local math = require('math')
_M.encode = function(number)
return bit.bxor(number, bit.rshift(number, 1));
end
_M.decode = function(gray_code)
local value = 0
while gray_code > 0 do
gray_code, value = bit.rshift(gray_code, 1), bit.bxor(gray_code, value)
end
return value
end
return _M | 783Gray code
| 1lua
| 4wn5c |
function hamming() {
var queues = {2: [], 3: [], 5: []};
var base;
var next_ham = 1;
while (true) {
yield next_ham;
for (base in queues) {queues[base].push(next_ham * base)}
next_ham = [ queue[0] for each (queue in queues) ].reduce(function(min, val) {
return Math.min(min,val)
});
for (base in queues) {if (queues[base][0] == next_ham) queues[base].shift()}
}
}
var ham = hamming();
var first20=[], i=1;
for (; i <= 20; i++)
first20.push(ham.next());
print(first20.join(', '));
print('...');
for (; i <= 1690; i++)
ham.next();
print(i + " => " + ham.next()); | 780Hamming numbers
| 10javascript
| t5afm |
(max 1 2 3 4)
(apply max [1 2 3 4]) | 784Greatest element of a list
| 6clojure
| ckx9b |
use strict;
sub max_sub(\@) {
my ($a, $maxs, $maxe, $s, $sum, $maxsum) = shift;
foreach (0 .. $
my $t = $sum + $a->[$_];
($s, $sum) = $t > 0 ? ($s, $t) : ($_ + 1, 0);
if ($maxsum < $sum) {
$maxsum = $sum;
($maxs, $maxe) = ($s, $_ + 1)
}
}
@$a[$maxs .. $maxe - 1]
}
my @a = map { int(rand(20) - 10) } 1 .. 10;
my @b = (-1) x 10;
print "seq: @a\nmax: [ @{[max_sub @a]} ]\n";
print "seq: @b\nmax: [ @{[max_sub @b]} ]\n"; | 774Greatest subsequential sum
| 2perl
| z48tb |
(defn hailstone-seq [n]
{:pre [(pos? n)]}
(lazy-seq
(cond (= n 1) '(1)
(even? n) (cons n (hailstone-seq (/ n 2)))
:else (cons n (hailstone-seq (+ (* n 3) 1))))))
(let [hseq (hailstone-seq 27)]
(-> hseq count (= 112) assert)
(->> hseq (take 4) (= [27 82 41 124]) assert)
(->> hseq (drop 108) (= [8 4 2 1]) assert))
(let [{max-i:num, max-len:len}
(reduce #(max-key:len %1 %2)
(for [i (range 1 100000)]
{:num i,:len (count (hailstone-seq i))}))]
(println "Maximum length" max-len "was found for hailstone(" max-i ").")) | 785Hailstone sequence
| 6clojure
| bi3kz |
let radians = function (degree: number) { | 766Haversine formula
| 20typescript
| hobjt |
import java.math.BigInteger
import java.util.*
val Three = BigInteger.valueOf(3)!!
val Five = BigInteger.valueOf(5)!!
fun updateFrontier(x : BigInteger, pq : PriorityQueue<BigInteger>) {
pq.add(x.shiftLeft(1))
pq.add(x.multiply(Three))
pq.add(x.multiply(Five))
}
fun hamming(n : Int) : BigInteger {
val frontier = PriorityQueue<BigInteger>()
updateFrontier(BigInteger.ONE, frontier)
var lowest = BigInteger.ONE
for (i in 1 .. n-1) {
lowest = frontier.poll() ?: lowest
while (frontier.peek() == lowest)
frontier.poll()
updateFrontier(lowest, frontier)
}
return lowest
}
fun main(args : Array<String>) {
System.out.print("Hamming(1 .. 20) =")
for (i in 1 .. 20)
System.out.print(" ${hamming(i)}")
System.out.println("\nHamming(1691) = ${hamming(1691)}")
System.out.println("Hamming(1000000) = ${hamming(1000000)}")
} | 780Hamming numbers
| 11kotlin
| x34ws |
<?php
function max_sum_seq($sequence) {
$sum_start = 0;
$sum = 0;
$max_sum = 0;
$max_start = 0;
$max_len = 0;
for ($i = 0; $i < count($sequence); $i += 1) {
$n = $sequence[$i];
$sum += $n;
if ($sum > $max_sum) {
$max_sum = $sum;
$max_start = $sum_start;
$max_len = $i + 1 - $max_start;
}
if ($sum < 0) {
$sum = 0;
$sum_start = $i + 1;
}
}
return array_slice($sequence, $max_start, $max_len);
}
function print_array($arr) {
if (count($arr) > 0) {
echo join(, $arr);
} else {
echo ;
}
echo '<br>';
}
print_array(max_sum_seq(array(-1, 0, 15, 3, -9, 12, -4)));
print_array(max_sum_seq(array(-1)));
print_array(max_sum_seq(array(4, -10, 3)));
?> | 774Greatest subsequential sum
| 12php
| bi4k9 |
import java.util.Random;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Random random = new Random();
long from = 1;
long to = 100;
int randomNumber = random.nextInt(to - from + 1) + from;
int guessedNumber = 0;
System.out.printf("The number is between%d and%d.\n", from, to);
do
{
System.out.print("Guess what the number is: ");
guessedNumber = scan.nextInt();
if (guessedNumber > randomNumber)
System.out.println("Your guess is too high!");
else if (guessedNumber < randomNumber)
System.out.println("Your guess is too low!");
else
System.out.println("You got it!");
} while (guessedNumber != randomNumber);
}
} | 776Guess the number/With feedback
| 9java
| 4wy58 |
null | 771Happy numbers
| 11kotlin
| ilso4 |
<p>Pick a number between 1 and 100.</p>
<form id="guessNumber">
<input type="text" name="guess">
<input type="submit" value="Submit Guess">
</form>
<p id="output"></p>
<script type="text/javascript"> | 776Guess the number/With feedback
| 10javascript
| h82jh |
my $number = 1 + int rand 10;
do { print "Guess a number between 1 and 10: " } until <> == $number;
print "You got it!\n"; | 773Guess the number
| 2perl
| 4wc5d |
import bpy
bpy.data.objects['Cube'].select_set(True)
bpy.ops.object.delete(True)
bpy.data.curves.new(type=, name=).body =
font_obj = bpy.data.objects.new(name=, object_data=bpy.data.curves[])
bpy.context.scene.collection.objects.link(font_obj)
bpy.context.scene.camera.location = (2.5,0.3,10)
bpy.context.scene.camera.rotation_euler = (0,0,0)
area = next(area for area in bpy.context.screen.areas if area.type == 'VIEW_3D')
area.spaces[0].region_3d.view_perspective = 'CAMERA' | 767Hello world/Graphical
| 3python
| 098sq |
sub bin2gray
{
return $_[0] ^ ($_[0] >> 1);
}
sub gray2bin
{
my ($num)= @_;
my $bin= $num;
while( $num >>= 1 ) {
$bin ^= $num;
}
return $bin;
}
for (0..31) {
my $gr= bin2gray($_);
printf "%d\t%b\t%b\t%b\n", $_, $_, $gr, gray2bin($gr);
} | 783Gray code
| 2perl
| ocr8x |
void swap(void *va, void *vb, size_t s)
{
char t, *a = (char*)va, *b = (char*)vb;
while(s--)
t = a[s], a[s] = b[s], b[s] = t;
} | 786Generic swap
| 5c
| 89u04 |
function hiter()
hammings = {1}
prev, vals = {1, 1, 1}
index = 1
local function nextv()
local n, v = 1, hammings[prev[1]]*2
if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end
if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end
prev[n] = prev[n] + 1
if hammings[index] == v then return nextv() end
index = index + 1
hammings[index] = v
return v
end
return nextv
end
j = hiter()
for i = 1, 20 do
print(j())
end
n, l = 0, 0
while n < 2^31 do n, l = j(), n end
print(l) | 780Hamming numbers
| 1lua
| q6gx0 |
<?php
session_start();
if(isset($_SESSION['number']))
{
$number = $_SESSION['number'];
}
else
{
$_SESSION['number'] = rand(1,10);
}
if(isset($_POST[])){
if($_POST[]){
$guess = htmlspecialchars($_POST['guess']);
echo $guess . ;
if ($guess != $number)
{
echo ;
}
elseif($guess == $number)
{
echo ;
}
}
}
?>
<!DOCTYPE html PUBLIC >
<html xmlns=>
<head>
<meta http-equiv= content= />
<title>Guess A Number</title>
</head>
<body>
<form action= method= name=>
<label for=>Guess number:</label><br/ >
<input type= name= />
<input name= type= value= />
<input name= type= />
</form>
</body>
</html> | 773Guess the number
| 12php
| ilxov |
import kotlin.random.Random
fun main() {
val n = 1 + rand.nextInt(20)
println("Guess which number I've chosen in the range 1 to 20\n")
while (true) {
print(" Your guess: ")
val guess = readLine()?.toInt()
when (guess) {
n -> { println("Correct, well guessed!"); return }
in n + 1 .. 20 -> println("Your guess is higher than the chosen number, try again")
in 1 .. n - 1 -> println("Your guess is lower than the chosen number, try again")
else -> println("Your guess is inappropriate, try again")
}
}
} | 776Guess the number/With feedback
| 11kotlin
| lbfcp |
library(RGtk2)
w <- gtkWindowNew()
l <- gtkLabelNew("Goodbye, World!")
w$add(l) | 767Hello world/Graphical
| 13r
| w3xe5 |
<?php
function gray_encode($binary){
return $binary ^ ($binary >> 1);
}
function gray_decode($gray){
$binary = $gray;
while($gray >>= 1) $binary ^= $gray;
return $binary;
}
for($i=0;$i<32;$i++){
$gray_encoded = gray_encode($i);
printf(,$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
} | 783Gray code
| 12php
| gxd42 |
int
gcd_iter(int u, int v) {
if (u < 0) u = -u;
if (v < 0) v = -v;
if (v) while ((u %= v) && (v %= u));
return (u + v);
} | 787Greatest common divisor
| 5c
| sylq5 |
def maxsubseq(seq):
return max((seq[begin:end] for begin in xrange(len(seq)+1)
for end in xrange(begin, len(seq)+1)),
key=sum) | 774Greatest subsequential sum
| 3python
| 3gozc |
max.subseq <- function(x) {
cumulative <- cumsum(x)
min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
end <- which.max(cumulative-min.cumulative.so.far)
begin <- which.min(c(0, cumulative[1:end]))
if (end >= begin) x[begin:end] else x[c()]
} | 774Greatest subsequential sum
| 13r
| dvqnt |
function digits(n)
if n > 0 then return n % 10, digits(math.floor(n/10)) end
end
function sumsq(a, ...)
return a and a ^ 2 + sumsq(...) or 0
end
local happy = setmetatable({true, false, false, false}, {
__index = function(self, n)
self[n] = self[sumsq(digits(n))]
return self[n]
end } )
i, j = 0, 1
repeat
i, j = happy[j] and (print(j) or i+1) or i, j + 1
until i == 8 | 771Happy numbers
| 1lua
| n20i8 |
(defn swap [pair] (reverse pair))
(defn swap [[a b]] '(b a))
(defn swap [[a b]] [b a]) | 786Generic swap
| 6clojure
| fu7dm |
List<int> hailstone(int n) {
if(n<=0) {
throw new IllegalArgumentException("start value must be >=1)");
}
Queue<int> seq=new Queue<int>();
seq.add(n);
while(n!=1) {
n=n%2==0?(n/2).toInt():3*n+1;
seq.add(n);
}
return new List<int>.from(seq);
} | 785Hailstone sequence
| 18dart
| 2pqlp |
num findGreatestElement(List<num> list){
num greatestElement = list[0];
for (num element in list){
if (element>greatestElement) {
greatestElement = element;
}
}
return greatestElement;
}
import 'dart:math';
num findGreatestElement(List<num> list){
return list.reduce(max);
} | 784Greatest element of a list
| 18dart
| ilro7 |
(defn gcd
"(gcd a b) computes the greatest common divisor of a and b."
[a b]
(if (zero? b)
a
(recur b (mod a b)))) | 787Greatest common divisor
| 6clojure
| n24ik |
import random
t,g=random.randint(1,10),0
g=int(input())
while t!=g:g=int(input())
print() | 773Guess the number
| 3python
| gxl4h |
def subarray_sum(arr)
max, slice = 0, []
arr.each_index do |i|
(i...arr.length).each do |j|
sum = arr[i..j].inject(0,:+)
max, slice = sum, arr[i..j] if sum > max
end
end
[max, slice]
end | 774Greatest subsequential sum
| 14ruby
| y7n6n |
def gray_encode(n):
return n ^ n >> 1
def gray_decode(n):
m = n >> 1
while m:
n ^= m
m >>= 1
return n
if __name__ == '__main__':
print()
for i in range(32):
gray = gray_encode(i)
dec = gray_decode(gray)
print(f) | 783Gray code
| 3python
| il7of |
fn main() {
let nums = [1,2,39,34,20, -20, -16, 35, 0];
let mut max = 0;
let mut boundaries = 0..0;
for length in 0..nums.len() {
for start in 0..nums.len()-length {
let sum = (&nums[start..start+length]).iter()
.fold(0, |sum, elem| sum+elem);
if sum > max {
max = sum;
boundaries = start..start+length;
}
}
}
println!("Max subsequence sum: {} for {:?}", max, &nums[boundaries]);;
} | 774Greatest subsequential sum
| 15rust
| mjdya |
require 'gtk2'
window = Gtk::Window.new
window.title = 'Goodbye, World'
window.signal_connect(:delete-event) { Gtk.main_quit }
window.show_all
Gtk.main | 767Hello world/Graphical
| 14ruby
| oli8v |
GrayEncode <- function(binary) {
gray <- substr(binary,1,1)
repeat {
if (substr(binary,1,1)!= substr(binary,2,2)) gray <- paste(gray,"1",sep="")
else gray <- paste(gray,"0",sep="")
binary <- substr(binary,2,nchar(binary))
if (nchar(binary) <=1) {
break
}
}
return (gray)
}
GrayDecode <- function(gray) {
binary <- substr(gray,1,1)
repeat {
if (substr(binary,nchar(binary),nchar(binary))!= substr(gray,2,2)) binary <- paste(binary ,"1",sep="")
else binary <- paste(binary ,"0",sep="")
gray <- substr(gray,2,nchar(gray))
if (nchar(gray) <=1) {
break
}
}
return (binary)
} | 783Gray code
| 13r
| sy5qy |
f <- function() {
print("Guess a number between 1 and 10 until you get it right.")
n <- sample(10, 1)
while (as.numeric(readline())!= n) {
print("Try again.")
}
print("You got it!")
} | 773Guess the number
| 13r
| v1y27 |
def maxSubseq(l: List[Int]) = l.scanRight(Nil : List[Int]) {
case (el, acc) if acc.sum + el < 0 => Nil
case (el, acc) => el :: acc
} max Ordering.by((_: List[Int]).sum)
def biggestMaxSubseq(l: List[Int]) = l.scanRight(Nil : List[Int]) {
case (el, acc) if acc.sum + el < 0 => Nil
case (el, acc) => el :: acc
} max Ordering.by((ss: List[Int]) => (ss.sum, ss.length))
def biggestMaxSubseq[N](l: List[N])(implicit n: Numeric[N]) = {
import n._
l.scanRight(Nil : List[N]) {
case (el, acc) if acc.sum + el < zero => Nil
case (el, acc) => el :: acc
} max Ordering.by((ss: List[N]) => (ss.sum, ss.length))
}
def linearBiggestMaxSubseq[N](l: List[N])(implicit n: Numeric[N]) = {
import n._
l.scanRight((zero, Nil : List[N])) {
case (el, (acc, _)) if acc + el < zero => (zero, Nil)
case (el, (acc, ss)) => (acc + el, el :: ss)
} max Ordering.by((t: (N, List[N])) => (t._1, t._2.length)) _2
} | 774Greatest subsequential sum
| 16scala
| lbzcq |
math.randomseed(os.time())
me_win=false
my_number=math.random(1,10)
while me_win==false do
print "Guess my number from 1 to 10:"
your_number = io.stdin:read'*l'
if type(tonumber(your_number))=="number" then
your_number=tonumber(your_number)
if your_number>10 or your_number<1 then
print "Your number was not between 1 and 10, try again."
elseif your_number>my_number then
print "Your number is greater than mine, try again."
elseif your_number<my_number then
print "Your number is smaller than mine, try again."
elseif your_number==my_number then
print "That was correct."
me_win=true
end
else
print "Your input was not a number, try again."
end
end | 776Guess the number/With feedback
| 1lua
| 2ptl3 |
null | 767Hello world/Graphical
| 15rust
| i2nod |
swing.Dialog.showMessage(message = "Goodbye, World!") | 767Hello world/Graphical
| 16scala
| f5td4 |
class Integer
def to_gray
raise Math::DomainError, if self < 0
self ^ (self >> 1)
end
def from_gray
raise Math::DomainError, if self < 0
recurse = proc do |i|
next 0 if i == 0
o = recurse[i >> 1] << 1
o | (i[0] ^ o[1])
end
recurse[self]
end
end
(0..31).each do |number|
encoded = number.to_gray
decoded = encoded.from_gray
printf ,
number, number, encoded, decoded, decoded
end | 783Gray code
| 14ruby
| dvhns |
use strict;
use warnings;
use List::Util 'min';
sub ham_gen {
my @s = ([1], [1], [1]);
my @m = (2, 3, 5);
return sub {
my $n = min($s[0][0], $s[1][0], $s[2][0]);
for (0 .. 2) {
shift @{$s[$_]} if $s[$_][0] == $n;
push @{$s[$_]}, $n * $m[$_]
}
return $n
}
}
my $h = ham_gen;
my $i = 0;
++$i, print $h->(), " " until $i > 20;
print "...\n";
++$i, $h->() until $i == 1690;
print ++$i, "-th: ", $h->(), "\n"; | 780Hamming numbers
| 2perl
| 2pilf |
WITH
FUNCTION greatest_subsequential_sum(p_list IN varchar2, p_delimiter IN varchar2) RETURN varchar2 IS
-- Variablen
v_list varchar2(32767):= TRIM(BOTH p_delimiter FROM p_list);
v_substr_i varchar2(32767);
v_substr_j varchar2(32767);
v_substr_out varchar2(32767);
v_res INTEGER:= 0;
v_res_out INTEGER:= 0;
--
BEGIN
--
v_list:= regexp_replace(v_list,''||chr(92)||p_delimiter||'{2,}',p_delimiter);
--
FOR i IN 1..nvl(regexp_count(v_list,'[^'||p_delimiter||']+'),0)
loop
v_substr_i:= substr(v_list,regexp_instr(v_list,'[^'||p_delimiter||']+',1,i));
--
FOR j IN reverse 1..regexp_count(v_substr_i,'[^'||p_delimiter||']+')
loop
--
v_substr_j:= TRIM(BOTH p_delimiter FROM substr(v_substr_i,1,regexp_instr(v_substr_i,'[^'||p_delimiter||']+',1,j,1)));
EXECUTE immediate 'select sum('||REPLACE(v_substr_j,p_delimiter,'+')||') from dual' INTO v_res;
--
IF v_res > v_res_out THEN
v_res_out:= v_res;
v_substr_out:= '{'||v_substr_j||'}';
elsif v_res = v_res_out THEN
v_res_out:= v_res;
v_substr_out:= v_substr_out||',{'||v_substr_j||'}';
END IF;
--
END loop;
--
END loop;
--
v_substr_out:= TRIM(BOTH ',' FROM nvl(v_substr_out,'{}'));
v_substr_out:= CASE WHEN regexp_count(v_substr_out,'},{')>0 THEN 'subsequences '||v_substr_out ELSE 'a subsequence '||v_substr_out END;
RETURN 'The maximum sum '||v_res_out||' belongs to '||v_substr_out||' of the main sequence {'||p_list||'}';
END;
--Test
SELECT greatest_subsequential_sum('-1|-2|-3|-4|-5|', '|') AS FROM dual
UNION ALL
SELECT greatest_subsequential_sum('', '') FROM dual
UNION ALL
SELECT greatest_subsequential_sum(' ', ' ') FROM dual
UNION ALL
SELECT greatest_subsequential_sum(';;;;;;+1;;;;;;;;;;;;;2;+3;4;;;;-5;;;;', ';') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('-1,-2,+3,,,,,,,,,,,,+5,+6,-2,-1,+4,-4,+2,-1', ',') FROM dual
UNION ALL
SELECT greatest_subsequential_sum(',+7,-6,-8,+5,-2,-6,+7,+4,+8,-9,-3,+2,+6,-4,-6,,', ',') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('01 +2 3 +4 05 -8 -9 -20 40 25 -5', ' ') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('1 2 3 0 0 -99 02 03 00001 -99 3 2 1 -99 3 1 2 0', ' ') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('0,0,1,0', ',') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('0,0,0', ',') FROM dual
UNION ALL
SELECT greatest_subsequential_sum('1,-1,+1', ',') FROM dual; | 774Greatest subsequential sum
| 19sql
| uayvq |
fn gray_encode(integer: u64) -> u64 {
(integer >> 1) ^ integer
}
fn gray_decode(integer: u64) -> u64 {
match integer {
0 => 0,
_ => integer ^ gray_decode(integer >> 1)
}
}
fn main() {
for i in 0..32 {
println!("{:2} {:0>5b} {:0>5b} {:2}", i, i, gray_encode(i),
gray_decode(i));
}
} | 783Gray code
| 15rust
| fukd6 |
func maxSubseq(sequence: [Int]) -> (Int, Int, Int) {
var maxSum = 0, thisSum = 0, i = 0
var start = 0, end = -1
for (j, seq) in sequence.enumerated() {
thisSum += seq
if thisSum < 0 {
i = j + 1
thisSum = 0
} else if (thisSum > maxSum) {
maxSum = thisSum
start = i
end = j
}
}
return start <= end && start >= 0 && end >= 0
? (start, end + 1, maxSum): (0, 0, 0)
}
let a = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
let (start, end, maxSum) = maxSubseq(sequence: a)
print("Max sum = \(maxSum)")
print(a[start..<end]) | 774Greatest subsequential sum
| 17swift
| 6ri3j |
def encode(n: Int) = (n ^ (n >>> 1)).toBinaryString
def decode(s: String) = Integer.parseInt( s.scanLeft(0)(_ ^ _.asDigit).tail.mkString , 2)
println("decimal binary gray decoded")
for (i <- 0 to 31; g = encode(i))
println("%7d %6s %5s %7s".format(i, i.toBinaryString, g, decode(g))) | 783Gray code
| 16scala
| 3g1zy |
n = rand(1..10)
puts 'Guess the number: '
puts 'Wrong! Guess again: ' until gets.to_i == n
puts 'Well guessed!' | 773Guess the number
| 14ruby
| 7svri |
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello world!");
}
} | 755Hello world/Text
| 9java
| f55dv |
DECLARE @BINARY AS NVARCHAR(MAX) = '001010111'
DECLARE @gray AS NVARCHAR(MAX) = ''
--Encoder
SET @gray = LEFT(@BINARY, 1)
WHILE LEN(@BINARY) > 1
BEGIN
IF LEFT(@BINARY, 1)!= SUBSTRING(@BINARY, 2, 1)
SET @gray = @gray + '1'
ELSE
SET @gray = @gray + '0'
SET @BINARY = RIGHT(@BINARY, LEN(@BINARY) - 1)
END
SELECT @gray
--Decoder
SET @BINARY = LEFT(@gray, 1)
WHILE LEN(@gray) > 1
BEGIN
IF RIGHT(@BINARY, 1)!= SUBSTRING(@gray, 2, 1)
SET @BINARY = @BINARY + '1'
ELSE
SET @BINARY = @BINARY + '0'
SET @gray = RIGHT(@gray, LEN(@gray) - 1)
END
SELECT @BINARY | 783Gray code
| 19sql
| mjwyl |
extern crate rand;
fn main() {
println!("Type in an integer between 1 and 10 and press enter.");
let n = rand::random::<u32>()% 10 + 1;
loop {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let option: Result<u32,_> = line.trim().parse();
match option {
Ok(guess) => {
if guess < 1 || guess > 10 {
println!("Guess is out of bounds; try again.");
} else if guess == n {
println!("Well guessed!");
break;
} else {
println!("Wrong! Try again.");
}
},
Err(_) => println!("Invalid input; try again.")
}
}
} | 773Guess the number
| 15rust
| j0u72 |
val n = (math.random * 10 + 1).toInt
print("Guess the number: ")
while(readInt != n) print("Wrong! Guess again: ")
println("Well guessed!") | 773Guess the number
| 16scala
| bigk6 |
document.write("Hello world!"); | 755Hello world/Text
| 10javascript
| yjj6r |
func grayEncode(_ i: Int) -> Int {
return (i >> 1) ^ i
}
func grayDecode(_ i: Int) -> Int {
switch i {
case 0:
return 0
case _:
return i ^ grayDecode(i >> 1)
}
}
for i in 0..<32 {
let iStr = String(i, radix: 2)
let encode = grayEncode(i)
let encodeStr = String(encode, radix: 2)
let decode = grayDecode(encode)
let decodeStr = String(decode, radix: 2)
print("\(i) (\(iStr)) => \(encode) (\(encodeStr)) => \(decode) (\(decodeStr))")
} | 783Gray code
| 17swift
| n2jil |
null | 783Gray code
| 20typescript
| uaova |
import Cocoa
let alert = NSAlert()
alert.messageText = "Goodbye, World!"
alert.runModal() | 767Hello world/Graphical
| 17swift
| 8co0v |
from itertools import islice
def hamming2():
'''\
This version is based on a snippet from:
https:
/index.php?option=com_content&task=view&id=913&Itemid=85
http:
Hamming problem
Written by Will Ness
December 07, 2008
When expressed in some imaginary pseudo-C with automatic
unlimited storage allocation and BIGNUM arithmetics, it can be
expressed as:
hamming = h where
array h;
n=0; h[0]=1; i=0; j=0; k=0;
x2=2*h[ i ]; x3=3*h[j]; x5=5*h[k];
repeat:
h[++n] = min(x2,x3,x5);
if (x2==h[n]) { x2=2*h[++i]; }
if (x3==h[n]) { x3=3*h[++j]; }
if (x5==h[n]) { x5=5*h[++k]; }
'''
h = 1
_h=[h]
multipliers = (2, 3, 5)
multindeces = [0 for i in multipliers]
multvalues = [x * _h[i] for x,i in zip(multipliers, multindeces)]
yield h
while True:
h = min(multvalues)
_h.append(h)
for (n,(v,x,i)) in enumerate(zip(multvalues, multipliers, multindeces)):
if v == h:
i += 1
multindeces[n] = i
multvalues[n] = x * _h[i]
mini = min(multindeces)
if mini >= 1000:
del _h[:mini]
multindeces = [i - mini for i in multindeces]
yield h | 780Hamming numbers
| 3python
| v1n29 |
import Cocoa
var found = false
let randomNum = Int(arc4random_uniform(10) + 1)
println("Guess a number between 1 and 10\n")
while (!found) {
var fh = NSFileHandle.fileHandleWithStandardInput()
println("Enter a number: ")
let data = fh.availableData
var str = NSString(data: data, encoding: NSUTF8StringEncoding)
if (str?.integerValue == randomNum) {
found = true
println("Well guessed!")
}
} | 773Guess the number
| 17swift
| rq2gg |
hamming=function(hamms,limit) {
tmp=hamms
for(h in c(2,3,5)) {
tmp=c(tmp,h*hamms)
}
tmp=unique(tmp[tmp<=limit])
if(length(tmp)>length(hamms)) {
hamms=hamming(tmp,limit)
}
hamms
}
h <- sort(hamming(1,limit=2^31-1))
print(h[1:20])
print(h[length(h)]) | 780Hamming numbers
| 13r
| 9h0mg |
use List::Util qw(sum);
sub ishappy {
my $s = shift;
while ($s > 6 && $s != 89) {
$s = sum(map { $_*$_ } split(//,$s));
}
$s == 1;
}
my $n = 0;
print join(" ", map { 1 until ishappy(++$n); $n; } 1..8), "\n"; | 771Happy numbers
| 2perl
| rqugd |
sub prompt {
my $prompt = shift;
while (1) {
print "\n", $prompt, ": ";
defined($_ = <STDIN>) and !/^\s*q/ or exit;
return $_ if /^\s*\d+\s*$/s;
$prompt = "Please give a non-negative integer";
}
}
my $tgt = int(rand prompt("Hola! Please tell me the upper bound") + 1);
my $tries = 1;
$tries++, print "You guessed too ", ($_ == -1 ? "high" : "low"), ".\n"
while ($_ = $tgt <=> prompt "Your guess");
print "Correct! You guessed it after $tries tries.\n"; | 776Guess the number/With feedback
| 2perl
| q6hx6 |
function isHappy($n) {
while (1) {
$total = 0;
while ($n > 0) {
$total += pow(($n % 10), 2);
$n /= 10;
}
if ($total == 1)
return true;
if (array_key_exists($total, $past))
return false;
$n = $total;
$past[$total] = 0;
}
}
$i = $cnt = 0;
while ($cnt < 8) {
if (isHappy($i)) {
echo ;
$cnt++;
}
$i++;
} | 771Happy numbers
| 12php
| dv8n8 |
hamming = Enumerator.new do |yielder|
next_ham = 1
queues = [[ 2, []], [3, []], [5, []] ]
loop do
yielder << next_ham
queues.each {|m,queue| queue << next_ham * m}
next_ham = queues.collect{|m,queue| queue.first}.min
queues.each {|m,queue| queue.shift if queue.first==next_ham}
end
end | 780Hamming numbers
| 14ruby
| 5efuj |
<?php
session_start();
if(isset($_SESSION['number']))
{
$number = $_SESSION['number'];
}
else
{
$_SESSION['number'] = rand(1,10);
}
if($_POST[]){
$guess = htmlspecialchars($_POST['guess']);
echo $guess . ;
if ($guess < $number)
{
echo ;
}
elseif($guess > $number)
{
echo ;
}
elseif($guess == $number)
{
echo ;
}
}
?>
<!DOCTYPE html PUBLIC >
<html xmlns=>
<head>
<meta http-equiv= content= />
<title>Guess A Number</title>
</head>
<body>
<form action= method= name=>
<label for=>Guess A Number:</label><br/ >
<input type= name= />
<input name= type= value= />
<input name= type= />
</form>
</body>
</html> | 776Guess the number/With feedback
| 12php
| v1z2v |
extern crate num;
num::bigint::BigUint;
use std::time::Instant;
fn basic_hamming(n: usize) -> BigUint {
let two = BigUint::from(2u8);
let three = BigUint::from(3u8);
let five = BigUint::from(5u8);
let mut h = vec![BigUint::from(0u8); n];
h[0] = BigUint::from(1u8);
let mut x2 = BigUint::from(2u8);
let mut x3 = BigUint::from(3u8);
let mut x5 = BigUint::from(5u8);
let mut i = 0usize; let mut j = 0usize; let mut k = 0usize; | 780Hamming numbers
| 15rust
| 4wt5u |
class Hamming extends Iterator[BigInt] {
import scala.collection.mutable.Queue
val qs = Seq.fill(3)(new Queue[BigInt])
def enqueue(n: BigInt) = qs zip Seq(2, 3, 5) foreach { case (q, m) => q enqueue n * m }
def next = {
val n = qs map (_.head) min;
qs foreach { q => if (q.head == n) q.dequeue }
enqueue(n)
n
}
def hasNext = true
qs foreach (_ enqueue 1)
} | 780Hamming numbers
| 16scala
| 7s6r9 |
package main
import (
"fmt"
"math/rand"
"time"
) | 784Greatest element of a list
| 0go
| bi6kh |
fun main() {
println("Hello world!")
} | 755Hello world/Text
| 11kotlin
| 8cc0q |
println ([2,4,0,3,1,2,-12].max()) | 784Greatest element of a list
| 7groovy
| rqdgh |
my_max = maximum | 784Greatest element of a list
| 8haskell
| dvjn4 |
package main
import "fmt" | 785Hailstone sequence
| 0go
| n2ri1 |
import random
inclusive_range = (1, 100)
print(
% inclusive_range)
target = random.randint(*inclusive_range)
answer, i = None, 0
while answer != target:
i += 1
txt = input(% i)
try:
answer = int(txt)
except ValueError:
print(% txt)
continue
if answer < inclusive_range[0] or answer > inclusive_range[1]:
print()
continue
if answer == target:
print()
break
if answer < target: print()
if answer > target: print()
print() | 776Guess the number/With feedback
| 3python
| sykq9 |
def hailstone = { long start ->
def sequence = []
while (start != 1) {
sequence << start
start = (start % 2l == 0l) ? start / 2l: 3l * start + 1l
}
sequence << start
} | 785Hailstone sequence
| 7groovy
| syvq1 |
guessANumber <- function(low, high)
{
boundryErrorCheck(low, high)
goal <- sample(low:high, size = 1)
guess <- getValidInput(paste0("I have a whole number between ", low, " and ", high, ". What's your guess? "))
while(guess != goal)
{
if(guess < low || guess > high){guess <- getValidInput("Out of range! Try again "); next}
if(guess > goal){guess <- getValidInput("Too high! Try again "); next}
if(guess < goal){guess <- getValidInput("Too low! Try again "); next}
}
"Winner!"
}
boundryErrorCheck <- function(low, high)
{
if(!is.numeric(low) || as.integer(low) != low) stop("Lower bound must be an integer. Try again.")
if(!is.numeric(high) || as.integer(high) != high) stop("Upper bound must be an integer. Try again.")
if(high < low) stop("Upper bound must be strictly greater than lower bound. Try again.")
if(low == high) stop("This game is impossible to lose. Try again.")
invisible()
}
getValidInput <- function(requestText)
{
guess <- type.convert(readline(requestText))
while(!is.numeric(guess) || as.integer(guess) != guess){guess <- type.convert(readline("That wasn't an integer! Try again "))}
as.integer(guess)
} | 776Guess the number/With feedback
| 13r
| etrad |
import Data.List (maximumBy)
import Data.Ord (comparing)
collatz :: Int -> Int
collatz n
| even n = n `div` 2
| otherwise = 1 + 3 * n
hailstone :: Int -> [Int]
hailstone = takeWhile (1 /=) . iterate collatz
longestChain :: Int
longestChain =
fst $
maximumBy (comparing snd) $
(,) <*> (length . hailstone) <$> [1 .. 100000]
main :: IO ()
main =
mapM_
putStrLn
[ "Collatz sequence for 27: ",
(show . hailstone) 27,
"The number " <> show longestChain,
"has the longest hailstone sequence",
"for any number less then 100000. ",
"The sequence has length: "
<> (show . length . hailstone $ longestChain)
] | 785Hailstone sequence
| 8haskell
| ua0v2 |
CREATE TEMPORARY TABLE factors(n INT);
INSERT INTO factors VALUES(2);
INSERT INTO factors VALUES(3);
INSERT INTO factors VALUES(5);
CREATE TEMPORARY TABLE hamming AS
WITH RECURSIVE ham AS (
SELECT 1 AS h
UNION
SELECT h*n x FROM ham JOIN factors ORDER BY x
LIMIT 1700
)
SELECT h FROM ham;
sqlite> SELECT h FROM hamming ORDER BY h LIMIT 20;
1
2
3
4
5
6
8
9
10
12
15
16
18
20
24
25
27
30
32
36
sqlite> SELECT h FROM hamming ORDER BY h LIMIT 1 OFFSET 1690;
2125764000 | 780Hamming numbers
| 19sql
| ko9hb |
a, b = b, a | 786Generic swap
| 0go
| 5e0ul |
>>> def happy(n):
past = set()
while n != 1:
n = sum(int(i)**2 for i in str(n))
if n in past:
return False
past.add(n)
return True
>>> [x for x in xrange(500) if happy(x)][:8]
[1, 7, 10, 13, 19, 23, 28, 31] | 771Happy numbers
| 3python
| 7s5rm |
number = rand(1..10)
puts
loop do
begin
user_number = Integer(gets)
if user_number == number
puts
break
elsif user_number > number
puts
else
puts
end
rescue ArgumentError
puts
end
end | 776Guess the number/With feedback
| 14ruby
| 89p01 |
(a, b) = [b, a] | 786Generic swap
| 7groovy
| cke9i |
public static float max(float[] values) throws NoSuchElementException {
if (values.length == 0)
throw new NoSuchElementException();
float themax = values[0];
for (int idx = 1; idx < values.length; ++idx) {
if (values[idx] > themax)
themax = values[idx];
}
return themax;
} | 784Greatest element of a list
| 9java
| syuq0 |
use rand::Rng;
use std::cmp::Ordering;
use std::io;
const LOWEST: u32 = 1;
const HIGHEST: u32 = 100;
fn main() {
let secret_number = rand::thread_rng().gen_range(1..101);
println!("I have chosen my number between {} and {}. Guess the number!", LOWEST, HIGHEST);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
} | 776Guess the number/With feedback
| 15rust
| oc183 |
import java.util.Random
import java.util.Scanner
val scan = new Scanner(System.in)
val random = new Random
val (from , to) = (1, 100)
val randomNumber = random.nextInt(to - from + 1) + from
var guessedNumber = 0
printf("The number is between%d and%d.\n", from, to)
do {
print("Guess what the number is: ")
guessedNumber = scan.nextInt
if (guessedNumber > randomNumber) println("Your guess is too high!")
else if (guessedNumber < randomNumber) println("Your guess is too low!")
else println("You got it!")
} while (guessedNumber != randomNumber) | 776Guess the number/With feedback
| 16scala
| dvwng |
is.happy <- function(n)
{
stopifnot(is.numeric(n) && length(n)==1)
getdigits <- function(n)
{
as.integer(unlist(strsplit(as.character(n), "")))
}
digits <- getdigits(n)
previous <- c()
repeat
{
sumsq <- sum(digits^2, na.rm=TRUE)
if(sumsq==1L)
{
happy <- TRUE
break
} else if(sumsq%in% previous)
{
happy <- FALSE
attr(happy, "cycle") <- previous
break
} else
{
previous <- c(previous, sumsq)
digits <- getdigits(sumsq)
}
}
happy
} | 771Happy numbers
| 13r
| 5eluy |
Math.max.apply(null, [ 0, 1, 2, 5, 4 ]); | 784Greatest element of a list
| 10javascript
| n27iy |
swap :: (a, b) -> (b, a)
swap (x, y) = (y, x) | 786Generic swap
| 8haskell
| x3cw4 |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Hailstone {
public static List<Long> getHailstoneSequence(long n) {
if (n <= 0)
throw new IllegalArgumentException("Invalid starting sequence number");
List<Long> list = new ArrayList<Long>();
list.add(Long.valueOf(n));
while (n != 1) {
if ((n & 1) == 0)
n = n / 2;
else
n = 3 * n + 1;
list.add(Long.valueOf(n));
}
return list;
}
public static void main(String[] args) {
List<Long> sequence27 = getHailstoneSequence(27);
System.out.println("Sequence for 27 has " + sequence27.size() + " elements: " + sequence27);
long MAX = 100000; | 785Hailstone sequence
| 9java
| mjaym |
null | 784Greatest element of a list
| 11kotlin
| af913 |
function hailstone (n) {
var seq = [n];
while (n > 1) {
n = n % 2 ? 3 * n + 1 : n / 2;
seq.push(n);
}
return seq;
} | 785Hailstone sequence
| 10javascript
| v1s25 |
import Cocoa
var found = false
let randomNum = Int(arc4random_uniform(100) + 1)
println("Guess a number between 1 and 100\n")
while (!found) {
var fh = NSFileHandle.fileHandleWithStandardInput()
println("Enter a number: ")
let data = fh.availableData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
if (str?.integerValue == randomNum) {
found = true
println("Well guessed!")
} else if (str?.integerValue < randomNum) {
println("Good try but the number is more than that!")
} else if (str?.integerValue > randomNum) {
println("Good try but the number is less than that!")
}
} | 776Guess the number/With feedback
| 17swift
| 0mbs6 |
package main
import "fmt"
func gcd(a, b int) int {
var bgcd func(a, b, res int) int
bgcd = func(a, b, res int) int {
switch {
case a == b:
return res * a
case a % 2 == 0 && b % 2 == 0:
return bgcd(a/2, b/2, 2*res)
case a % 2 == 0:
return bgcd(a/2, b, res)
case b % 2 == 0:
return bgcd(a, b/2, res)
case a > b:
return bgcd(a-b, b, res)
default:
return bgcd(a, b-a, res)
}
}
return bgcd(a, b, 1)
}
func main() {
type pair struct {
a int
b int
}
var testdata []pair = []pair{
pair{33, 77},
pair{49865, 69811},
}
for _, v := range testdata {
fmt.Printf("gcd(%d,%d) =%d\n", v.a, v.b, gcd(v.a, v.b))
}
} | 787Greatest common divisor
| 0go
| v1x2m |
require 'set'
@seen_numbers = Set.new
@happy_numbers = Set.new
def happy?(n)
return true if n == 1
return @happy_numbers.include?(n) if @seen_numbers.include?(n)
@seen_numbers << n
digit_squared_sum = n.to_s.each_char.inject(0) { |sum, c| sum + c.to_i**2 }
if happy?(digit_squared_sum)
@happy_numbers << n
true
else
false
end
end | 771Happy numbers
| 14ruby
| h8gjx |
class Pair<T> {
T first;
T second;
}
public static <T> void swap(Pair<T> p) {
T temp = p.first;
p.first = p.second;
p.second = temp;
} | 786Generic swap
| 9java
| bizk3 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.