'BEGIN'
    OUTSTRING(1,'('Hello world!')');
    SYSACT(1,14,1)
'END'


import "ecere"
MessageBox goodBye { contents = "Goodbye, World!" };


import org.eclipse.edt.rui.widgets.*;
import dojo.widgets.*;

handler HelloWorld type RUIhandler{initialUI =[ui]}

    ui Box {columns=1, children=[nameField, helloLabel, goButton]};

    nameField DojoTextField {placeHolder = "What's your name?", text = "World"};
    helloLabel TextLabel {};
    goButton DojoButton {text = "Say Goodbye", onClick ::= onClick_goButton};

    function onClick_goButton(e Event in)
        helloLabel.text = "Goodbye, " + nameField.text + "!";
    end

end


import forms;

public class MainWindow : SDIDialog
{
    Label goodByeWorldLabel;
    Button closeButton;

    constructor new()
       <= new()
    {
        self.Caption := "ELENA";

        goodByeWorldLabel := Label.new();
        closeButton       := Button.new();

        self
            .appendControl(goodByeWorldLabel)
            .appendControl(closeButton);

        self.setRegion(250, 200, 200, 110);

        goodByeWorldLabel.Caption := "Goodbye, World!";
        goodByeWorldLabel.setRegion(40, 10, 150, 30);

        closeButton.Caption := "Close";
        closeButton.setRegion(20, 40, 150, 30);
        closeButton.onClick := (args){ forward program.stop() };
    }
}


include msgbox.e

integer response
response = message_box("Goodbye, World!","Bye",MB_OK)


#light
open System
open System.Windows.Forms
[<EntryPoint>]
let main _ =
    MessageBox.Show("Hello World!") |> ignore
    0


main:
   {"Hello world!\n"}print
exit(0)


   USING: ui ui.gadgets.labels ;
   [ "Goodbye World" <label> "Rosetta Window" open-window ] with-ui


using fwt

class Hello
{
  public static Void main ()
  {
    Dialog.openInfo (null, "Goodbye world")
  }
}


HWND z" Goodbye, World!" z" (title)" MB_OK MessageBox


PROC main()
  WriteF('Hello world!\n')
ENDPROC


program hello
    use windows
    integer :: res
    res = MessageBoxA(0, LOC("Hello, World"), LOC("Window Title"), MB_OK)
end program


(fn love.load []
  (love.window.setMode 300 300 {"resizable" false})
  (love.window.setTitle "Hello world/Graphical in Fennel!"))

(let [str "Goodbye, World!"]
  (fn love.draw []
    (love.graphics.print str 95 150)))


screen 1 'Mode 320x200
locate 12,15
? "Goodbye, World!"
sleep


There was a guy called Hello World
"Ow!" it said.
That's all folks!


package HelloWorldGraphical where

import Java.Swing

main _ = do
    frame <- JFrame.new "Goodbye, world!"
    frame.setDefaultCloseOperation(JFrame.dispose_on_close)
    label <- JLabel.new "Goodbye, world!"
    cp <- frame.getContentPane
    cp.add label
    frame.pack
    frame.setVisible true


g = new graphics
g.font["SansSerif", 10]
g.text["Goodbye, World!", 0, 0, 10 degrees]
g.show[]

g.print[]                           // Optional: render to printer
g.write["GoodbyeWorld.png", 400, 300] // Optional: write to graphics file


native javax.swing.{SwingUtilities, JPanel, JLabel, JFrame}
native java.awt.Font

def createAndShowGUI( msg ) =
  f = JFrame()
  f.setTitle( msg )
  f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE )
  p = JPanel()
  l = JLabel( msg )
  l.setFont( Font.decode(Font.SERIF + ' 150') )
  p.add( l )
  f.add( p )
  f.pack()
  f.setResizable( false )
  f.setVisible( true )

SwingUtilities.invokeLater( createAndShowGUI.runnable('Goodbye, World!') )


alert 1, NSWarningAlertStyle, @"Goodbye, World!", @"It's been real.", @"See ya!", YES

HandleEvents


Message.Info("Goodbye, World!")    ' Display a simple message box


[indent=4]
/*
  Genie GTK+ hello
  valac --pkg gtk+-3.0 hello-gtk.gs
  ./hello-gtk
*/
uses Gtk

init
    Gtk.init (ref args)
    var window = new Window (WindowType.TOPLEVEL)
    var label = new Label("Goodbye, World!")
    window.add(label)
    window.set_default_size(160, 100)
    window.show_all()
    window.destroy.connect(Gtk.main_quit)
    Gtk.main()


debug="⡧⢼⣟⣋⣇⣀⣇⣀⣏⣹⠀⠀⣇⣼⣏⣹⡯⡽⣇⣀⣏⡱⢘⠀"


package main

import "github.com/mattn/go-gtk/gtk"

func main() {
   gtk.Init(nil)
   win := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
   win.SetTitle("Goodbye, World!")
   win.SetSizeRequest(300, 200)
   win.Connect("destroy", gtk.MainQuit)
   button := gtk.NewButtonWithLabel("Goodbye, World!")
   win.Add(button)
   button.Connect("clicked", gtk.MainQuit)
   win.ShowAll()
   gtk.Main()
}


import groovy.swing.SwingBuilder
import javax.swing.JFrame

new SwingBuilder().edt {
  optionPane().showMessageDialog(null, "Goodbye, World!")
  frame(title:'Goodbye, World!', defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true, show: true) {
    flowLayout()
    button(text:'Goodbye, World!')
    textArea(text:'Goodbye, World!')
  }
}


PROCEDURE Main()
   RETURN wapi_MessageBox(,"Goodbye, World!","")


.global main

message:
    .asciz "Hello world!\n"
    .align 4

main:
    ldr r0, =message
    bl printf

    mov r7, #1
    swi 0


import Graphics.UI.Gtk
import Control.Monad

messDialog = do
  initGUI
  dialog <- messageDialogNew Nothing [] MessageInfo ButtonsOk "Goodbye, World!"

  rs <- dialogRun dialog
  when (rs == ResponseOk || rs == ResponseDeleteEvent) $ widgetDestroy dialog

  dialog `onDestroy` mainQuit

  mainGUI


IT'S SHOWTIME
TALK TO THE HAND "Hello world!"
YOU HAVE BEEN TERMINATED


link graphics
procedure main()
   WOpen("size=100,20") | stop("No window")
   WWrites("Goodbye, World!")
   WDone()
end


graphics {
	display("Goodbye, World!")
}


import(
  :javax:swing, :JOptionPane, :JFrame, :JTextArea, :JButton
)
import java:awt:FlowLayout

JOptionPane showMessageDialog(nil, "Goodbye, World!")
button = JButton new("Goodbye, World!")
text = JTextArea new("Goodbye, World!")
window = JFrame new("Goodbye, World!") do(
  layout = FlowLayout new
  add(button)
  add(text)
  pack
  setDefaultCloseOperation(JFrame field:EXIT_ON_CLOSE)
  visible = true
)


DEF Win:WINDOW
DEF Close:CHAR
DEF ScreenSizeX,ScreenSizeY:UINT

GETSCREENSIZE(ScreenSizeX,ScreenSizeY)

OPENWINDOW Win,0,0,ScreenSizeX,ScreenSizeY,NULL,NULL,"Goodbye program",&MainHandler

PRINT Win,"Goodbye, World!"
'Prints in upper left corner of the window (position 0,0).

WAITUNTIL Close=1

CLOSEWINDOW Win

END

SUB MainHandler

    IF @[email protected] THEN Close=1

RETURN
ENDSUB


implement main0 () = print "Hello world!\n"


import javax.swing.*;
import java.awt.*;

public class OutputSwing {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JOptionPane.showMessageDialog (null, "Goodbye, World!"); // in alert box
                JFrame frame = new JFrame("Goodbye, World!");            // on title bar
                JTextArea text = new JTextArea("Goodbye, World!");       // in editable area
                JButton button = new JButton("Goodbye, World!");         // on button

                frame.setLayout(new FlowLayout());
                frame.add(button);
                frame.add(text);
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}


DllCall("AllocConsole")
FileAppend, Goodbye`, World!, CONOUT$
FileReadLine, _, CONIN$, 1


# Convert a JSON object to a string suitable for use as a CSS style value
# e.g: "font-size: 40px; text-align: center;" (without the quotation marks)
def to_s:
  reduce to_entries[] as $pair (""; . + "\($pair.key): \($pair.value); ");

# Defaults: 100%, 100%
def svg(width; height):
  "<svg width='\(width // "100%")' height='\(height // "100%")'
           xmlns='http://www.w3.org/2000/svg'>";

# Defaults:
#  id: "linearGradient"
#  color1: rgb(0,0,0)
#  color2: rgb(255,255,255)
def linearGradient(id; color1; color2):
  "<defs>
    <linearGradient id='\(id//"linearGradient")' x1='0%' y1='0%' x2='100%' y2='0%'>
      <stop offset='0%' style='stop-color:\(color1//"rgb(0,0,0)");stop-opacity:1' />
      <stop offset='100%' style='stop-color:\(color2//"rgb(255,255,255)");stop-opacity:1' />
    </linearGradient>
  </defs>";

# input: the text string
# "style" should be a JSON object (see for example the default ($dstyle));
# the style actually used is (default + style), i.e. whatever is specified in "style" wins.
# Defaults:
#  x: 0
#  y: 0
def text(x; y; style):
  . as $in
  | {"font-size": "40px", "text-align": "center", "text-anchor": "left", "fill": "black"} as $dstyle
  | (($dstyle + style) | to_s) as $style
  | "<text x='\(x//0)' y='\(y//0)' style='\($style)'>
       \(.)",
     "</text>";


prompt$ jsish
Jsish interactive: see 'help [cmd]'.  \ cancels > input.  ctrl-c aborts running script.
# require('JsiAgarGUI')
1
# JsiAgarGUI.alert("Goodbye, World!");
#


using Tk

window = Toplevel("Hello World", 200, 100, false)
pack_stop_propagate(window)

fr = Frame(window)
pack(fr, expand=true, fill="both")

txt = Label(fr, "Hello World")
pack(txt, expand=true)

set_visible(window, true)

# sleep(7)


print "Goodbye, World!"
'Prints in the upper left corner of the default text window: mainwin, a window with scroll bars.


function main() {
  Konsol:Message("Goodbye, World!", "")
}


import java.awt.*
import javax.swing.*

fun main(args: Array<String>) {
    JOptionPane.showMessageDialog(null, "Goodbye, World!") // in alert box
    with(JFrame("Goodbye, World!")) {                      // on title bar
        layout = FlowLayout()
        add(JButton("Goodbye, World!"))                    // on button
        add(JTextArea("Goodbye, World!"))                  // in editable area
        pack()
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        isVisible = true
    }
}


main()
{
    putstr("Hello world!*n");
    return(0);
}


sys_process('/usr/bin/osascript', (: '-e', 'display dialog "Goodbye, World!"'))->wait


gl_window("graphical hello world", 800, 600)
gl_setfontname("data/fonts/Droid_Sans/DroidSans.ttf")
gl_setfontsize(30)

while gl_frame():
    gl_clear([ 0.0, 0.0, 0.0, 1.0 ])
    gl_text("Goodbye, World!")


LABEL [Hello, World!]
SETLABELHEIGHT 2 * last LABELSIZE
LABEL [Goodbye, World!]


require "iuplua"

dlg = iup.dialog{iup.label{title="Goodbye, World!"}; title="test"}
dlg:show()

if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then
  iup.MainLoop()
end


const hello = "Hello world!\n"

print(hello)


Module CheckIt {
      Declare Simple Form
      \\ we can define form before open
      Layer Simple {
            \\ center Window with 12pt font, 12000 twips width and 6000 twips height
            \\ ; at the end command to center the form in current screen
            Window 12, 12000, 6000;
            \\ make layer gray and split screen 0
            Cls #333333, 0
            \\   set split screen to 3rd line, like Cls ,2 without clear screen
            Scroll Split 2
            Cursor 0, 2
      }
      With Simple, "Title", "Hello Form"
      Function Simple.Click {
            Layer Simple {
                  \\ open msgbox
                  Print Ask("Hello World")
                  Refresh
            }
      }
      \\ now open as modal
      Method Simple, "Show", 1
      \\ now form deleted
      Declare Simple Nothing
}
CheckIt


Maplets:-Display( Maplets:-Elements:-Maplet( [ "Goodbye, World!" ] ) );


alias goodbyegui {
  dialog -m Goodbye Goodbye
}

dialog Goodbye {
  title "Goodbye, World!"
  size -1 -1 80 20
  option dbu
  text "Goodbye, World!", 1, 20 6 41 7
}


GET "libhdr"

LET start() = VALOF
{ writef("Hello world!")
  RESULTIS 0
}


MODULE GUIHello EXPORTS Main;

IMPORT TextVBT, Trestle;

<*FATAL ANY*>

VAR v := TextVBT.New("Goodbye, World!");

BEGIN
  Trestle.Install(v);
  Trestle.AwaitDelete(v);
END GUIHello.


/*
  Tectonics:
    gcc -shared -fPIC -o nekoagar.ndll nekoagar.c `agar-config --cflags --libs`
*/

/* Neko primitives for libAgar http://www.libagar.org */
#include <stdio.h>
#include <neko.h>
#include <agar/core.h>
#include <agar/gui.h>

#define val_widget(v)       ((AG_Widget *)val_data(v))
DEFINE_KIND(k_agar_widget);

/* Initialize Agar Core given appname and flags */
value agar_init_core(value appname, value flags) {
#ifdef DEBUG
  if (!val_is_null(appname))  val_check(appname, string);
  val_check(flags, int);
#endif
  if (AG_InitCore(val_string(appname), val_int(flags)) == -1)  return alloc_bool(0);
  return alloc_bool(1);
}
DEFINE_PRIM(agar_init_core, 2);

/* Initialize Agar GUI given graphic engine driver */
value agar_init_gui(value driver) {
#ifdef DEBUG
  if (!val_is_null(driver))  val_check(driver, string);
#endif
  if (AG_InitGraphics(val_string(driver)) == -1)  return alloc_bool(0);
  AG_BindStdGlobalKeys();
  return alloc_bool(1);
}
DEFINE_PRIM(agar_init_gui, 1);

/* Initialize Agar given appname, flags and GUI driver */
value agar_init(value appname, value flags, value driver) {
#ifdef DEBUG
  if (!val_is_null(appname))  val_check(appname, string);
  val_check(flags, int);
  if (!val_is_null(driver))  val_check(driver, string);
#endif
  if (!val_bool(agar_init_core(appname, flags)))  return alloc_bool(0);
  if (!val_bool(agar_init_gui(driver)))  return alloc_bool(0);
  return alloc_bool(1);
}
DEFINE_PRIM(agar_init, 3);

/* end the Agar event loop on window-close */
void rundown(AG_Event *event) {
  AG_Terminate(0);
}

/* Create an Agar window, given UInt flags (which might use 32 bits...) */
value agar_window(value flags) {
#ifdef DEBUG
  val_check(flags, int);
#endif
  AG_Window *win;
  win = AG_WindowNew(val_int(flags));
  AG_SetEvent(win, "window-close", rundown, "%p", win);

  if ( win == NULL) return alloc_bool(0);
  return alloc_abstract(k_agar_widget, win);
}
DEFINE_PRIM(agar_window, 1);

/* Show a window */
value agar_window_show(value w) {
  AG_Window *win;

#ifdef DEBUG
  val_check_kind(w, k_agar_widget);
#endif
  win = (AG_Window *)val_widget(w);
  AG_WindowShow(win);
  return alloc_bool(1);
}
DEFINE_PRIM(agar_window_show, 1);

/* New box */
value agar_box(value parent, value type, value flags) {
  AG_Box *b;

#ifdef DEBUG
  val_check_kind(parent, k_agar_widget);
#endif
  b = AG_BoxNew(val_widget(parent), val_int(type), val_int(flags));
  return alloc_abstract(k_agar_widget, b);
}
DEFINE_PRIM(agar_box, 3);

/* New label */
value agar_label(value parent, value flags, value text) {
  AG_Label *lw;

#ifdef DEBUG
  val_check_kind(parent, k_agar_widget);
#endif
  lw = AG_LabelNewS(val_widget(parent), val_int(flags), val_string(text));
  return alloc_abstract(k_agar_widget, lw);
}
DEFINE_PRIM(agar_label, 3);

/* Event Loop */
value agar_eventloop(void) {
  int rc;
  rc = AG_EventLoop();
  return alloc_int(rc);
}
DEFINE_PRIM(agar_eventloop, 0);


/* NetRexx */
options replace format comments java crossref symbols binary

import javax.swing.

msgText = 'Goodbye, World!'
JOptionPane.showMessageDialog(null, msgText)


; hello-gui.lsp
; oofoe 2012-01-18

; Initialize GUI server.
(load (append (env "NEWLISPDIR") "/guiserver.lsp"))
(gs:init)

; Create window frame.
(gs:frame 'Goodbye 100 100 300 200 "Goodbye!")
(gs:set-resizable 'Goodbye nil)
(gs:set-flow-layout 'Goodbye "center")

; Add final message.
(gs:label 'Message "Goodbye, World!" "center")
(gs:add-to 'Goodbye 'Message)

; Show frame.
(gs:set-visible 'Goodbye true)

; Start event loop.
(gs:listen)

(exit) ; NewLisp normally goes to listener after running script.


use Console

define Main
    Console.Println "Hello world"
end


import dialogs, gtk2
gtk2.nim_init()

info(nil, "Hello World")


10 LOCATE 6,11
20 PRINT "GOODBYE, WORLD!"


;nyquist plug-in
;version 4
;type tool
;name "Goodbye World"

(print "Goodbye, World!")


# This will display a goodbye message on the terminal screen
.begin
display "Hello world!"
return
# This is the end of the script.


use Qt;

bundle Default {
  class QtExample {
    function : Main(args : String[]) ~ Nil {
      app := QAppliction->New();
      win := QWidget->New();
      win->Resize(400, 300);
      win->SetWindowTitle("Goodbye, World!");
      win->Show();
      app->Exec();
      app->Delete();
    }
  }
}


NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:@"Goodbye, World!"];
[alert runModal];


global _start

: syscall ( num:eax -- result:eax ) syscall ;

: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;

1 const stdout

: write ( buf:esi len:edx fd:edi -- ) 1 syscall drop ;
: print ( buf len -- ) stdout write ;

: greet ( -- ) s" Hello world!\n" print ;

: _start ( -- noret ) greet bye ;


let delete_event evt = false

let destroy () = GMain.Main.quit ()

let main () =
  let window = GWindow.window in
  let _ = window#set_title "Goodbye, World" in
  let _ = window#event#connect#delete ~callback:delete_event in
  let _ = window#connect#destroy ~callback:destroy in
  let _ = window#show () in
  GMain.Main.main ()
;;

let _ = main () ;;


(import (lib winapi))
(MessageBox #f (c-string "Hello, World!") (c-string "Rosettacode") #x40)


MESSAGE "Goodbye, World!" VIEW-AS ALERT-BOX.


<?xml version="1.0" standalone="no"?> <!--*- mode: xml -*-->
<!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.24.dtd">

<glade-interface>

<widget class="GtkWindow" id="hworld">
  <property name="visible">True</property>
  <property name="title">Hello World</property>
  <property name="modal">False</property>
  <property name="resizable">True</property>
  <property name="default_width">200</property>
  <property name="default_height">100</property>
  <signal name="delete_event" handler="on_hworld_delete_event"/>
  <child>
    <widget class="GtkLabel" id="label1">
      <property name="visible">True</property>
      <property name="can_focus">False</property>
      <property name="label" translatable="yes">Farewell, cruel world.</property>
    </widget>
  </child>
</widget>

</glade-interface>


declare
  [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
  Window = {QTk.build td(label(text:"Goodbye, World!"))}
in
  {Window show}


print "Goodbye, World!"
'Prints in the upper left corner of the window.


plotinit(1, 1, 1, 1);
plotstring(1, "Goodbye, World!");
plotdraw([1, 0, 15]);


#!/usr/bin/env bx
use b
Main:
	say("Hello world!")


program HelloWorldGraphical;

uses
  glib2, gdk2, gtk2;

var
  window: PGtkWidget;

begin
  gtk_init(@argc, @argv);

  window := gtk_window_new (GTK_WINDOW_TOPLEVEL);

  gtk_window_set_title (GTK_WINDOW (window), 'Goodbye, World');
  g_signal_connect (G_OBJECT (window),
                    'delete-event',
        G_CALLBACK (@gtk_main_quit),
        NULL);
  gtk_widget_show_all (window);

  gtk_main();
end.


use strict;
use warnings;
use Tk;

my $main = MainWindow->new;
$main->Label(-text => 'Goodbye, World')->pack;
MainLoop();


10	close to newline and carriage return
30	close to ! and SPACE
40	close to COMMA
70	close to G
80	close to W
90	close to b
100	is d and close to e and l
110	close to o
120	close to y


include pGUI.e
IupOpen()
IupMessage("Bye","Goodbye, World!")
IupClose()


if (!class_exists('gtk'))
{
    die("Please load the php-gtk2 module in your php.ini\r\n");
}

$wnd = new GtkWindow();
$wnd->set_title('Goodbye world');
$wnd->connect_simple('destroy', array('gtk', 'main_quit'));

$lblHello = new GtkLabel("Goodbye, World!");
$wnd->add($lblHello);

$wnd->show_all();
Gtk::main();


(call 'dialog "--msgbox" "Goodbye, World!" 5 20)


To run:
Start up.
Clear the screen.
Write "Goodbye, World!".
Refresh the screen.
Wait for the escape key.
Shut down.


programa {
    // includes graphics library and use an alias
    inclua biblioteca Graficos --> g

    // define WIDTH and HEIGHT integer constants
    const inteiro WIDTH = 200
    const inteiro HEIGHT = 100

    // main entry
    funcao inicio() {
        // begin graphical mode (verdadeiro = true)
        g.iniciar_modo_grafico(verdadeiro)

        // define window title
        g.definir_titulo_janela("Hello")

        // define window dimesions
        g.definir_dimensoes_janela(WIDTH, HEIGHT)

        // while loop
        enquanto (verdadeiro) {
            // define color to black(preto) and clear window
            g.definir_cor(g.COR_PRETO)
            g.limpar()

            // define color to white(branco)
            g.definir_cor(g.COR_BRANCO)
            // set text font size
            g.definir_tamanho_texto(32.0)
            // draws text
            g.desenhar_texto(0, HEIGHT / 3, "Hello, world!")

            // calls render function
            g.renderizar()
        }

        // end graphical mode
        g.encerrar_modo_grafico()
    }
}


%!PS
% render in Helvetica, 12pt:
/Helvetica findfont 12 scalefont setfont
% somewhere in the lower left-hand corner:
50 dup moveto
% render text
(Goodbye, World!) show
% wrap up page display:
showpage


FUNCTION PBMAIN() AS LONG
    MSGBOX "Goodbye, World!"
END FUNCTION


#include <stdlib.h>
#include <stdio.h>

int main(void)
{
  printf("Hello world!\n");
  return EXIT_SUCCESS;
}


namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("Hello world!");
        }
    }
}


New-Label "Goodbye, World!" -FontSize 24 -Show


fill(0, 0, 0);
text("Goodbye, World!",0,height/2);


send(@display, inform, 'Goodbye, World !').


#N canvas 321 432 450 300 10;
#X obj 100 52 loadbang;
#X msg 100 74 Goodbye\, World!;
#X obj 100 96 print -n;
#X connect 0 0 1 0;
#X connect 1 0 2 0;


#include <iostream>

int main () {
  std::cout << "Hello world!" << std::endl;
}


using namespace System;
int main()
{
  Console::WriteLine("Hello world!");
}


import bpy

# select default cube
bpy.data.objects['Cube'].select_set(True)

# delete default cube
bpy.ops.object.delete(True)

# add text to Blender scene
bpy.data.curves.new(type="FONT", name="Font Curve").body = "Hello World"
font_obj = bpy.data.objects.new(name="Font Object", object_data=bpy.data.curves["Font Curve"])
bpy.context.scene.collection.objects.link(font_obj)

# camera center to text
bpy.context.scene.camera.location = (2.5,0.3,10)

# camera orient angle to text
bpy.context.scene.camera.rotation_euler = (0,0,0)

# change 3D scene to view from the camera
area = next(area for area in bpy.context.screen.areas if area.type == 'VIEW_3D')
area.spaces[0].region_3d.view_perspective = 'CAMERA'


module hello_world;
import stdio as io;

func i32 main(i32 argc, char** argv) {
    io.printf("Hello World!\n");
    return 0;
}


library(RGtk2)   # bindings to Gtk
w <- gtkWindowNew()
l <- gtkLabelNew("Goodbye, World!")
w$add(l)


 #lang racket/gui
(require racket/gui/base)

; Make a frame by instantiating the frame% class
(define frame (new frame% [label "Goodbye, World!"]))

; Make a static text message in the frame
(define msg (new message% [parent frame]
                          [label "No events so far..."]))

; Make a button in the frame
(new button% [parent frame]
             [label "Click Me"]
             ; Callback procedure for a button click:
             (callback (lambda (button event)
                         (send msg set-label "Button click"))))

; Show the frame by calling its show method
(send frame show #t)


use GTK::Simple;
use GTK::Simple::App;

my GTK::Simple::App $app .= new;
$app.border-width = 20;
$app.set-content( GTK::Simple::Label.new(text => "Goodbye, World!") );
$app.run;


import std::io;

fn int main()
{
    io::println("Hello, World!");
    return 0;
}


MessageBox("Goodbye, World!", "RapidQ example", 0)


import vis::Figure;
import vis::Render;

public void GoodbyeWorld() =
  render(box(text("Goodbye World")));


/*REXX (using PC/REXX)  to display a message in a window (which is bordered). */
if fcnPkg('rxWindow') ¬== 1  then do
                                  say 'RXWINDOW function package not loaded.'
                                  exit 13
                                  end
if pcVideo()==3  then normal= 7
                 else normal=13

window#=w_open(1, 1, 3, 80, normal)
call w_border  window#
call w_put     window#, 2, 2, center("Goodbye, World!", 80-2)

                                       /*stick a fork in it, all we're done. */


Load "guilib.ring"
New qApp {
        new qWidget() {
                setwindowtitle("Hello World")
                show()
        }
        exec()
}


require 'gtk2'

window = Gtk::Window.new
window.title = 'Goodbye, World'
window.signal_connect(:delete-event) { Gtk.main_quit }
window.show_all

Gtk.main


#!/usr/bin/env cf-agent
# without --no-lock option to cf-agent
# this output will only occur once per minute
# this is by design.
bundle agent main
{
  reports:
    "Hello world!";
}


' do it with javascript
html "<script>alert('Goodbye, World!');</script>"


// cargo-deps:  gtk
extern crate gtk;
use gtk::traits::*;
use gtk::{Window, WindowType, WindowPosition};
use gtk::signal::Inhibit;

fn main() {
    gtk::init().unwrap();
    let window = Window::new(WindowType::Toplevel).unwrap();

    window.set_title("Goodbye, World!");
    window.set_border_width(10);
    window.set_window_position(WindowPosition::Center);
    window.set_default_size(350, 70);
    window.connect_delete_event(|_,_| {
        gtk::main_quit();
        Inhibit(false)
    });

    window.show_all();
    gtk::main();
}


Goodbye World Souffle.

Ingredients.
71 g green beans
111 cups oil
98 g butter
121 ml yogurt
101 eggs
44 g wheat flour
32 zucchinis
119 ml water
114 g red salmon
108 g lard
100 g dijon mustard
33 potatoes

Method.
Put potatoes into the mixing bowl.
Put dijon mustard into the mixing bowl.
Put lard into the mixing bowl.
Put red salmon into the mixing bowl.
Put oil into the mixing bowl.
Put water into the mixing bowl.
Put zucchinis into the mixing bowl.
Put wheat flour into the mixing bowl.
Put eggs into the mixing bowl.
Put yogurt into the mixing bowl.
Put butter into the mixing bowl.
Put dijon mustard into the mixing bowl.
Put oil into the mixing bowl.
Put oil into the mixing bowl.
Put green beans into the mixing bowl.
Liquefy contents of the mixing bowl.
Pour contents of the mixing bowl into the baking dish.

Serves 1.


swing.Dialog.showMessage(message = "Goodbye, World!")


#!r6rs

;; PS-TK example: display frame + label

(import (rnrs)
        (lib pstk main) ; change this to refer to your PS/Tk installation
        )

(define tk (tk-start))
(tk/wm 'title tk "PS-Tk Example: Label")

(let ((label (tk 'create-widget 'label 'text: "Goodbye, world")))
  (tk/place label 'height: 20 'width: 50 'x: 10 'y: 20))

(tk-event-loop tk)


execute() {
    host.println("Hello world!");
}


$ include "seed7_05.s7i";
  include "draw.s7i";
  include "keybd.s7i";
  include "bitmapfont.s7i";
  include "stdfont24.s7i";
  include "pixmap_file.s7i";

const proc: main is func
  local
    var text: screen is STD_NULL;
  begin
    screen(400, 100);
    clear(curr_win, white);
    KEYBOARD := GRAPH_KEYBOARD;
    screen := openPixmapFontFile(curr_win);
    color(screen, black, white);
    setFont(screen, stdFont24);
    setPosXY(screen, 68,  60);
    write(screen, "Goodbye, World");
    ignore(getc(KEYBOARD));
  end func;


var tk = require('Tk');
var main = %s'MainWindow'.new;
main.Button(
    '-text'    => 'Goodbye, World!',
    '-command' => 'exit',
).pack;
tk.MainLoop;


open XWindows ;
open Motif ;

val helloWindow = fn () =>

 let
  val shell = XtAppInitialise    ""    "demo" "top" [] [XmNwidth 400, XmNheight 300 ] ;
  val main  = XmCreateMainWindow shell "main" [XmNmappedWhenManaged true ] ;
  val text = XmCreateLabel main "show" [ XmNlabelString "Hello World!"]
 in

  (
  XtManageChildren [text];
  XtManageChild    main;
  XtRealizeWidget  shell
  )

end;


I want window and the window title is "Goodbye, World".


import Cocoa

let alert = NSAlert()
alert.messageText = "Goodbye, World!"
alert.runModal()


start_up = proc ()
    po: stream := stream$primary_output()
    stream$putl(po, "Hello world!")
end start_up


when flag clicked
say "Goodbye, World!"
stop this script


	program-id. hello.
	procedure division.
		display "Hello world!".
		stop run.


(with-dyn-lib "user32.dll"
  (deffi messagebox "MessageBoxW" int (cptr wstr wstr uint)))

(messagebox cptr-null "Hello" "World" 0) ;; 0 is MB_OK


whiptail --title 'Farewell' --msgbox 'Goodbye, World!' 7 20


#include <CtrlLib/CtrlLib.h>
// submitted by Aykayayciti (Earl Lamont Montgomery)

using namespace Upp;

class GoodbyeWorld : public TopWindow {
	MenuBar menu;
	StatusBar status;

	void FileMenu(Bar& bar);
	void MainMenu(Bar& bar);
	void About();

public:
	typedef GoodbyeWorld CLASSNAME;

	GoodbyeWorld();
};

void GoodbyeWorld::About()
{
	PromptOK("{{[email protected] [@9= This is the]::@2 [[email protected] Ultimate`+`+ Goodbye World sample}}");
}

void GoodbyeWorld::FileMenu(Bar& bar)
{
	bar.Add("About..", THISBACK(About));
	bar.Separator();
	bar.Add("Exit", THISBACK(Close));
}

void GoodbyeWorld::MainMenu(Bar& bar)
{
	menu.Add("File", THISBACK(FileMenu));
}

GoodbyeWorld::GoodbyeWorld()
{
	AddFrame(menu);
	AddFrame(status);
	menu.Set(THISBACK(MainMenu));
	status = "So long from the Ultimate++ !";
}

GUI_APP_MAIN
{
	SetLanguage(LNG_ENGLISH);
	GoodbyeWorld().Run();
}


class Hello
    def main
        print 'Hello world!'


#!/usr/local/bin/vala --pkg gtk+-3.0
using Gtk;

void main(string[] args) {
    Gtk.init(ref args);

    var window = new Window();
    window.title = "Goodbye, world!";
    window.border_width = 10;
    window.window_position = WindowPosition.CENTER;
    window.set_default_size(350, 70);
    window.destroy.connect(Gtk.main_quit);

    var label = new Label("Goodbye, world!");

    window.add(label);
    window.show_all();

    Gtk.main();
}


Public Sub hello_world_gui()
    MsgBox "Goodbye, World!"
End Sub


Sub Main()
    MsgBox "Goodbye, World!"
End Sub


Imports System.Windows.Forms

Module GoodbyeWorld
    Sub Main()
        Messagebox.Show("Goodbye, World!")
    End Sub
End Module


* Version 1:
MESSAGEBOX("Goodbye, World!")

* Version 2:
? "Goodbye, World!"


10 print chr$(147);chr$(14);:REM 147=clear screen, 14=switch to lowercase mode
20 print "Hello world!"
30 end


import ui

fn main() {
    ui.message_box('Hello World')
}


@1Introduction.
Define the structure of the program.

@aPROGRAM goodbye world CONTEXT VOID USE standard
BEGIN
@<Included [email protected]>
@<Logic at the top [email protected]>
END
FINISH

@ Include the graphical header file.

@[email protected]>

@ Program code.

@<[email protected]>=
open(LOC FILE,"",arg channel);
fl initialize(argc,argv,NIL,0);
fl show messages("Goodbye World!");
fl finish

@ Declare the necessary macros.

@<[email protected]>=
macro fl initialize;
macro fl show messages;
macro fl finish;

@ The end.


import "graphics" for Canvas, Color

class Game {
    static init() {
        Canvas.print("Goodbye, World!", 10, 10, Color.white)
    }

    static update() {}

    static draw(alpha) {}
}


MODULE Hello;
	IMPORT Out;

	PROCEDURE Do*;
	BEGIN
		Out.String("Hello world!"); Out.Ln
	END Do;
END Hello.


;;; hellowin.asm
;;;
;;; nasm -fwin32 hellowin.asm
;;; link -subsystem:console -out:hellowin.exe -nodefaultlib -entry:main \
;;;    hellowin.obj user32.lib kernel32.lib

        global _main
        extern [email protected]
        extern [email protected]

        MessageBox equ [email protected]
        ExitProcess equ [email protected]

        section .text
_main:
        push 0                  ; MB_OK
        push title              ;
        push message            ;
        push 0                  ;
        call MessageBox         ; eax = MessageBox(0,message,title,MB_OK);
        push eax                ;
        call ExitProcess        ; ExitProcess(eax);
message:
        db 'Goodbye, World',0
title:
        db 'RosettaCode sample',0


option casemap:none

printf			proto :qword, :vararg
exit			proto :dword
;; curses.h stuff
initscr			proto                           ;; WINDOW *initsrc(void);
endwin			proto                           ;; int endwin(void);
start_color		proto                           ;; int start_color(void);
wrefresh		proto :qword                    ;; int wrefresh(WINDOW *w);
wgetch			proto :qword                    ;; int wgetch(WINDOW *w)
waddnstr		proto :qword, :qword, :dword	;; int waddnstr(WINDOW *w, const char *str, int n);
;; Just a wrapper to make printing easier..
println			proto :qword, :qword

.code
main proc
	local stdscr:qword

	call initscr
	mov stdscr, rax
	call start_color
	invoke println, stdscr, CSTR("Goodbye, World!",10)
	invoke wgetch, stdscr
	call endwin
	invoke exit, 0
	ret
main endp

println proc wnd:qword, pstr:qword
	invoke waddnstr, wnd, pstr, -1
	invoke wrefresh, wnd
	ret
println endp

end


[SetVid($13);  Text(6, "Goodbye, World!")]


Require Import Coq.Strings.String.

Eval compute in ("Hello world!"%string).


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
	<xsl:output method="xml"/>
	<xsl:template match="/*">
		<!--
			Use a template to insert some text into a simple SVG graphic
			with hideous colors.
		-->
		<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 200">
			<rect x="0" y="0" width="400" height="200" fill="cyan"/>
			<circle cx="200" cy="100" r="50" fill="yellow"/>
			<text x="200" y="115"
				style="font-size: 40px;
					text-align: center;
					text-anchor: middle;
					fill: black;">
				<!-- The text inside the element -->
				<xsl:value-of select="."/>
			</text>
		</svg>
	</xsl:template>
</xsl:stylesheet>


open window 200, 100
text 10, 20, "Hello world"
color 255, 0, 0 : text 10, 40, "Good bye world", "roman14"


include "cowgol.coh";
print("Hello world!");
print_nl();


import crack.io cout;
cout `Hello world!\n`;


System.cmd(0'|zenity --info --text="Goodbye, World!"|); // GTK+ pop up
System.cmd(0'|notify-send "Goodbye, World!"|); // desktop notification
System.cmd(0'|xmessage -buttons Ok:0,"Not sure":1,Cancel:2 -default Ok -nearmouse "Goodbye, World!" -timeout 10|); // X Windows dialog


OPENCONSOLE

PRINT"Hello world!"

'This line could be left out.
PRINT:PRINT:PRINT"Press any key to end."

'Keep the console from closing right away so the text can be read.
DO:UNTIL INKEY$<>""

CLOSECONSOLE

END


import std.stdio;

void main() {
    writeln("Hello world!");
}


method Main() {
  print "hello, world!\n";
  assert 10 < 2;
}


main() {
    var bye = 'Hello world!';
    print("$bye");
}


;
;       Hello world for DBL version 4 by Dario B.
;
                                PROC
;------------------------------------------------------------------
        XCALL FLAGS (0007000000,1)           ;Suppress STOP message

        OPEN (1,O,'TT:')
        WRITES (1,"Hello world")

        DISPLAY (1,"Hello world",10)
        DISPLAY (1,$SCR_MOV(-1,12),"again",10)  ;move up, right and print

        CLOSE 1
END


program ProjectGoodbye;
{$APPTYPE CONSOLE}
begin
  WriteLn('Hello world!');
end.


F is_harshad(n)
   R n % sum(String(n).map(ch -> Int(ch))) == 0

F harshad(num)
   [Int] r
   L(n) 1..
      I is_harshad(n)
         r [+]= n
         I r.len == num
            R r

print(harshad(20))

L(n) 1001..
   I is_harshad(n)
      print(n)
      L.break


          START     ;Hello World

          RECORD  HELLO
,         A11, 'Hello World'

          PROC
          XCALL FLAGS (0007000000,1)          ;Suppress STOP message

          OPEN(8,O,'TT:')
          WRITES(8,HELLO)
          END


*        Harshad or Niven series - 01/05/2019
NIVEN    CSECT
         USING  NIVEN,R13          base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         SAVE   (14,12)            save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         LA     R7,2               j=2
LOOP     MVC    PG,=CL80' '        clear buffer
         LA     R10,PG             @pg
         LA     R8,0               n=0
       IF C,R7,EQ,=A(2) THEN       if j=2
         LA     R9,20                nn=20
         LA     R6,1                 i=1
       ELSE     ,                  else
         LA     R9,1                 nn=1
         LA     R6,1001              i=1001
       ENDIF    ,                  end if
       DO WHILE=(CR,R8,LT,R9)      do i=1 by 1 while(n<nn)
         BAL    R14,HARSHAD          call harshad(i)
       IF   LTR,R1,Z,R1 THEN         if rc=0 then
         LA     R8,1(R8)               n++
         XDECO  R6,XDEC                edit i
         MVC    0(4,R10),XDEC+8        output i
         LA     R10,4(R10)             @pg+=4
       ENDIF    ,                    end if
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         XPRNT  PG,L'PG            print buffer
         BCT    R7,LOOP            j=j-1; loop if j<>0
         L      R13,4(0,R13)       restore previous savearea pointer
         RETURN (14,12),RC=0       restore registers from calling sav
HARSHAD  EQU    *                  harshad(i)
         CVD    R6,PACKED          convert to packed   PL8
         UNPK   ZONED,PACKED       packed PL8 to zoned ZL16
         LA     R1,ZONED           @c
         XR     R4,R4              sum=0; m=1
       DO WHILE=(C,R1,LE,=A(ZONED+15)) do m=1 to 16
         NI     0(R1),X'0F'          c(m) : character to integer
         XR     R2,R2                ~
         IC     R2,0(R1)             c(m)
         AR     R4,R2                sum=sum+c(m)
         LA     R1,1(R1)             @c++
       ENDDO    ,                  enddo m
         XR     R2,R2              ~
         LR     R3,R6              i
         DR     R2,R4              i/sum
         LR     R1,R2              rc=mod(i,sum)
         BR     R14                return to caller
PACKED   DS     PL8                packed decimal (15num)
ZONED    DS     ZL16               zoned  decimal (16num)
PG       DS     CL80               buffer
XDEC     DS     CL12               temp xdeco
         REGEQU                    symbolic registers
         END    NIVEN


	cpu	8086
	org	100h
section	.text
	mov	di,10 		; DI is the divisor to find digits
	xor 	bp,bp		; Find first 20 Harshad numbers
	mov	cx,20
first:	call	next
	mov	ax,bp
	call	print
	loop	first
	mov	bp,1000		; Find first Harshad number > 1000
	call	next		; .. fall through (print and stop)
	mov	ax,bp
	;;;	Print the number in AX
print:	mov 	bx,buffer	; String buffer
.digit:	xor	dx,dx		; Divide by 10
	div	di
	add	dl,'0'		; Add ASCII 0 to remainder
	dec	bx
	mov	[bx],dl		; Store ASCII number
	test	ax,ax		; More digits?
	jnz	.digit
	mov	ah,9		; Print string using DOS
	mov	dx,bx
	int	21h
	ret
	;;;	Let BP be the first Harshad number above BP
next:	inc	bp
	mov	ax,bp		; Keep a copy
	xor	bx,bx		; Sum
.digit:	xor	dx,dx		; Divide by 10
	div	di
	add	bx,dx		; Add remainder to sum
	test	ax,ax		; More digits?
	jnz	.digit
	mov	ax,bp		; Is it a Harshad number?
	xor	dx,dx
	div	bx
	test	dx,dx		; If not, try next number
	jnz	next
	ret
section	.data
	db	'*****'
buffer:	db	13,10,'$'


PROGRAM HELLOWORLD;

BEGIN

    WRITE_TEXT(0,160,100,4,"HELLO WORLD!");
    LOOP
        FRAME;
    END
END


INT FUNC SumOfDigits(INT a)
  INT sum

  sum=0
  WHILE a#0
  DO
    sum==+a MOD 10
    a==/10
  OD
RETURN (sum)

INT FUNC Next(INT a)
  INT sum

  DO
    a==+1
    sum=SumOfDigits(a)
  UNTIL a MOD sum=0
  OD
RETURN (a)

PROC Main()
  INT i,a

  a=0
  FOR i=1 TO 20
  DO
    a=Next(a)
    PrintI(a)
    Put(32)
  OD
  Print("... ")
  a=Next(1000)
  PrintIE(a)
RETURN


with Ada.Text_IO;

procedure Harshad is

   function Next(N: in out Positive) return Positive is

      function Sum_Of_Digits(N: Natural) return Natural is
	 ( if N = 0 then 0 else ((N mod 10) + Sum_Of_Digits(N / 10)) );

   begin
      while not (N mod Sum_Of_Digits(N) = 0) loop
	 N := N + 1;
      end loop;
      return N;
   end Next;

   Current: Positive := 1;

begin
   for I in 1 .. 20 loop
      Ada.Text_IO.Put(Integer'Image(Next(Current)));
      Current := Current + 1;
   end loop;
   Current := 1000 + 1;
   Ada.Text_IO.Put_Line(" ..." & Integer'Image(Next(Current)));
end Harshad;


/client/New()
    ..()
    src << "Hello world!"


proc nonrec main() void:
    writeln("Hello world!")
corp


BEGIN
   PROC digit sum = (INT i) INT :
   BEGIN
      INT res := i %* 10, h := i;
      WHILE (h %:= 10) > 0 DO res +:= h %* 10 OD;
      res
   END;
   INT  found := 0;
   FOR i WHILE found < 20 DO
      (i %* digit sum (i) = 0 | found +:= 1; printf (($g(0)", "$, i)) ) OD;
   FOR i FROM 1001 DO
      (i %* digit sum (i) = 0 | printf (($g(0)l$, i)); stop) OD
END


begin
integer function mod(a,b);
integer a,b;
mod := a-(a/b)*b;

integer function digitsum(n);
integer n;
digitsum :=
    if n = 0 then 0
    else mod(n,10) + digitsum(n/10);

integer function nextharshad(n);
integer n;
begin
    integer ds;
loop:
    n := n + 1;
    ds := digitsum(n);
    if mod(n, ds) <> 0 then go to loop;
    nextharshad := n;
end;

integer i, n;
write("First 20 Harshad numbers:");
n := 0;
for i := 1 step 1 until 20 do
begin
    n := nextharshad(n);
    if mod(i,10)=1 then
        write(n)
    else
        writeon(n);
end;

write("First Harshad number above 1000:", nextharshad(1000));
end


begin % find members of the Harshad/Niven series - numbers divisible by the sum of their digits %
    % returns the next member of the series above n                                             %
    integer procedure nextHarshad ( integer value n ) ;
    begin
        integer h, s;
        h := n;
        while begin
                  integer v;
                  v := h := h + 1;
                  s := 0;
                  while v > 0 do begin
                      s := s + v rem 10;
                      v :=     v div 10
                  end while_v_gt_0 ;
                  h rem s not = 0
        end do begin end;
        h
    end nextHarshad ;
    integer h;
    % show the first 20 members of the seuence %
    write( "First 20 Harshad/Niven numbers:" );
    h := 0;
    for i := 1 until 20 do begin
        h := nextHarshad( h );
        writeon( i_w := 1, s_w := 0, " ", h )
    end for_i ;
    write( i_w := 1, s_w := 0, "First Harshad/Niven number > 1000: ", nextHarshad( 1000 ) );
end.


on nextHarshad(n)
    if (n < 0) then set n to 0
    repeat
        set n to n + 1
        set temp to n
        set sum to 0
        repeat until (temp is 0)
            set sum to sum + temp mod 10
            set temp to temp div 10
        end repeat
        if (n mod sum is 0) then return n
    end repeat
end nextHarshad

-- Test code:
set harshads to {}
set h to 0
repeat 20 times
    set h to nextHarshad(h)
    set end of harshads to h
end repeat

set h to nextHarshad(1000)

return {harshads, h}


module: hello-world

format-out("%s\n", "Hello world!");


harshad?: function [n] -> zero? n % sum digits n
harshads: select 1..1100 => harshad?

print ["First 20 harshad numbers:" first.n:20 harshads]

loop harshads 'h [
    if h > 1000 [
        print ["First harshad > 1000:" h]
        break
    ]
]


H := []
n := 1

Loop
	n := (H[A_Index] := NextHarshad(n)) + 1
until  H[H.MaxIndex()] > 1000

Loop, 20
	Out .= H[A_Index] ", "

MsgBox, % Out ". . . " H[H.MaxIndex()]

NextHarshad(n) {
	Loop, {
		Loop, Parse, n
			sum += A_LoopField
		if (!Mod(n, sum))
			return n
		n++, sum := ""
	}
}


#!/usr/bin/awk -f
BEGIN {
	k=0; n=0;
	printf("First twenty Harshad numbers are:\n   ");
	while (k<20) {
		if (isharshad(++n)) {
			printf("%i ",n);
			++k;
		}
	}
	n = 1000;
	while (!isharshad(++n));
	printf("\nFirst Harshad number larger than 1000 is \n   %i\n",n);
}

function isharshad(n) {
	s = 0;
	for (i=0; i<length(n); ) {
		s+=substr(n,++i,1);
	}
	return !(n%s);
}


@echo off
setlocal enabledelayedexpansion

for /l %%i in (1,1,20) do (
  call:harshad
  echo Harshad number %%i - !errorlevel!
)

:loop
call:harshad
if %errorlevel% leq 1000 goto loop
echo First Harshad number greater than 1000: %errorlevel%
pause>nul
exit /b

:harshad
if "%harshadnum%"=="" set harshadnum=0
set /a harshadnum+=1
call:strlength %harshadnum%

set harshadsum=0
for /l %%i in (0,1,%errorlevel%) do set /a harshadsum+=!harshadnum:~%%i,1!

set /a isharshad=%harshadnum% %% %harshadsum%
if %isharshad%==0 exit /b %harshadnum%
goto harshad

:strlength
setlocal enabledelayedexpansion
set tempcount=1
set str=%1
:strlengthloop
set /a length=%tempcount%-1
if "!str:~%tempcount%,1!"=="" endlocal && exit /b %length%
set /a tempcount+=1
goto strlengthloop


println("Hello world!")

stdout.println("Hello world!")


10 DEFINT P,N,I,S
20 PRINT "First 20 Harshad numbers:"
30 P=0
40 N=0
50 N=N+1
60 S=0
70 I=N
80 S=S+I MOD 10
90 I=I\10
100 IF I THEN 80
110 IF N MOD S THEN 50
120 IF P<20 THEN P=P+1: PRINT N,
130 IF N<=1000 THEN 50
140 PRINT
150 PRINT "First Harshad number > 1000:";N


function sumDigitos(n)
	if n < 0 then return 0
	suma = 0
	while n > 0
		suma = suma + (n mod 10)
		n = n \ 10
	end while
	return suma
end function

function isHarshad(n)
	return n mod sumDigitos(n) = 0
end function

print "Los primeros 20 números de Harshad o Niven son:"
cuenta = 0
i = 1

do
	if isHarshad(i) then
		print i; " ";
		cuenta += 1
	end if
	i += 1
until cuenta = 20

print : print
print "El primero de esos números por encima de 1000 es:"
i = 1001

do
	if isHarshad(i) then
		print i; " "
		exit do
	end if
	i += 1
until false
end


class GoodByeApp : Application
{
   void Main()
   {
      PrintLn("Hello world!");
   }
}


      I%=1:CNT%=0
      WHILE TRUE
        IF FNHarshad(I%) THEN
          IF CNT%<20 PRINT ;I%;" ";:CNT%+=1
          IF I%>1000 PRINT ;I%:EXIT WHILE
        ENDIF
        I%+=1
      ENDWHILE
      END

      DEF FNHarshad(num%)
      LOCAL sum%,tmp%
      tmp%=num%
      sum%=0
      WHILE (tmp%>0)
        sum%+=tmp% MOD 10
        tmp%/=10
      ENDWHILE
      =(num% MOD sum%)=0


get "libhdr"

let dsum(n) = n=0 -> 0, n rem 10 + dsum(n/10)
let next(n) = harshad(n+1) and harshad(n) = n rem dsum(n)=0 -> n, next(n)

let start() be
$(  let n = 0
    writes("First 20:")
    for i = 1 to 20 do
    $(  n := next(n)
        writef(" %N", n)
    $)
    writef("*NFirst above 1000: %N*N", next(1000))
$)


[ Print HELLO WORLD ]
[ A program for the EDSAC ]
[ Works with Initial Orders 2 ]

T64K  [ Set load point: address 64 ]
GK    [ Set base address ]
[email protected]  [ Each O order outputs one ]
[email protected]  [ character. The numerical ]
[email protected]  [ parameter gives the offset ]
[email protected]  [ (from the base address) where ]
[email protected]  [ the character to print is ]
[email protected]  [ stored ]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
ZF    [ Stop ]
*F    [ Shift to print letters ]
HF    [ Character literals ]
EF
LF
LF
OF
!F    [ Space character ]
WF
OF
RF
LF
DF
EZPF  [ Start program beginning at
        the load point ]


SumDgt ← +´•Fmt-'0'˙
Niven ← 0=SumDgt|⊢
nivens ← Niven¨⊸/↕1100
⟨20↑nivens, ⊑(⊢>1000˙)⊸/nivens⟩


#include <stdio.h>

static int digsum(int n)
{
    int sum = 0;
    do { sum += n % 10; } while (n /= 10);
    return sum;
}

int main(void)
{
    int n, done, found;

    for (n = 1, done = found = 0; !done; ++n) {
        if (n % digsum(n) == 0) {
            if (found++ < 20) printf("%d ", n);
            if (n > 1000) done = printf("\n%d\n", n);
        }
    }

    return 0;
}


V keys = [‘a’, ‘b’, ‘c’]
V values = [1, 2, 3]
V hash_ = Dict(zip(keys, values))
print(hash_)


using System;
using System.Collections.Generic;

namespace Harshad
{
    class Program
    {
        public static bool IsHarshad(int n)
        {
            char[] inputChars = n.ToString().ToCharArray();
            IList<byte> digits = new List<byte>();

            foreach (char digit in inputChars)
            {
                digits.Add((byte)Char.GetNumericValue(digit));
            }

            if (n < 1)
            {
                return false;
            }

            int sum = 0;

            foreach (byte digit in digits)
            {
                sum += digit;
            }

            return n % sum == 0;
        }

        static void Main(string[] args)
        {
            int i = 1;
            int count = 0;

            while (true)
            {
                if (IsHarshad(i))
                {
                    count++;

                    if (count <= 20)
                    {
                        Console.Write(string.Format("{0} ", i));
                    }
                    else if (i > 1000)
                    {
                        Console.Write(string.Format("{0} ", i));
                        break;
                    }
                }

                i++;
            }

            Console.ReadKey();
        }
    }
}


package
{
    public class MyClass
    {
        public static function main():Void
        {
            var hash:Object = new Object();
            var keys:Array = new Array("a", "b", "c");
            var values:Array = new Array(1, 2, 3);

            for (var i:int = 0; i < keys.length(); i++)
                hash[keys[i]] = values[i];
        }
    }
}


with Ada.Strings.Hash;
with Ada.Containers.Hashed_Maps;
with Ada.Text_Io;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;

procedure Hash_Map_Test is
   function Equivalent_Key (Left, Right : Unbounded_String) return Boolean is
   begin
      return Left = Right;
   end Equivalent_Key;

   function Hash_Func(Key : Unbounded_String) return Ada.Containers.Hash_Type is
   begin
      return Ada.Strings.Hash(To_String(Key));
   end Hash_Func;

   package My_Hash is new Ada.Containers.Hashed_Maps(Key_Type => Unbounded_String,
      Element_Type => Unbounded_String,
      Hash => Hash_Func,
      Equivalent_Keys => Equivalent_Key);

   type String_Array is array(Positive range <>) of Unbounded_String;

   Hash : My_Hash.Map;
   Key_List : String_Array := (To_Unbounded_String("foo"),
      To_Unbounded_String("bar"),
      To_Unbounded_String("val"));

   Element_List : String_Array := (To_Unbounded_String("little"),
      To_Unbounded_String("miss"),
      To_Unbounded_String("muffet"));

begin
   for I in Key_List'range loop
      Hash.Insert(Key => (Key_List(I)),
         New_Item => (Element_List(I)));
   end loop;
   for I in Key_List'range loop
      Ada.Text_Io.Put_Line(To_String(Key_List(I)) & " => " &
         To_String(Hash.Element(Key_List(I))));
   end loop;

end Hash_Map_Test;


(define $main
  (lambda [$argv]
    (write-string "Hello world!\n")))


program HelloWorld
    function main()
        SysLib.writeStdout("Hello world!");
    end
end


#include <vector>
#include <iostream>

int sumDigits ( int number ) {
   int sum = 0 ;
   while ( number != 0 ) {
      sum += number % 10 ;
      number /= 10 ;
   }
   return sum ;
}

bool isHarshad ( int number ) {
   return number % ( sumDigits ( number ) ) == 0 ;
}

int main( ) {
   std::vector<int> harshads ;
   int i = 0 ;
   while ( harshads.size( ) != 20 ) {
      i++ ;
      if ( isHarshad ( i ) )
	 harshads.push_back( i ) ;
   }
   std::cout << "The first 20 Harshad numbers:\n" ;
   for ( int number : harshads )
      std::cout << number << " " ;
   std::cout << std::endl ;
   int start = 1001 ;
   while ( ! ( isHarshad ( start ) ) )
      start++ ;
   std::cout << "The smallest Harshad number greater than 1000 : " << start << '\n' ;
   return 0 ;
}


#!/usr/bin/hopper
#include <hopper.h>

main:
   new hash(h)
   add hash(h,"chile" :: 100)
   add hash(h,"argentina"::200)
   add hash(h,"brasil"::300)
   {"\nLongitud HASH: "},len hash(h),println
   println(hash(h))

   println( get value("argentina",h) )
   println( get value("chile",h) )
   try
      println( get value("guyana",h) )
   catch(e)
      {"***[",e,"]: "}get str error,println
   finish
   println( get key(300,h) )
   println( get key(100,h) )

   mod value("chile",101,h)
   mod key(200,"madagascar",h)
   try
      mod key(130,"londres",h)
      println( get key(130,h) )
   catch(e)
      {"***[",e,"]: "}get str error,println
   finish

   println( get key(200,h) )
   println( get value("chile",h) )

   println("HASH actual: \n")
   println(hash(h))
   {"\nLongitud HASH: "},len hash(h),println

   put after value (200,"colombia",400,h)
   put value (200,"mexico",401,h)
   println(hash(h))

   put after key ("chile","antartida",110,h)
   put key ("chile","peru",99,h)

   println("HASH actual: \n")
   println(hash(h))
   {"\nLongitud HASH: "},len hash(h),println

   del by key("brasil",h)
   del by value(101,h)

   {"\nLongitud HASH: "},len hash(h),println
   println(hash(h))
   sort hash(h)
   {"\nORDENADO: \n"}println
   println(hash(h))

   y={}  // para un stack de arreglos.
   x=0,{5,5}rand array(x)
   {x}push(y)
   add hash(h,"arreglo 1"::x)

   {"Ojalá que llueva café en el campo"}strtoutf8,push(y)
   clear(x),w=0,{6,2}rand array(w)
   {w}push(y)
   add hash(h,"arreglo 2"::w)
   clear(w)
   add hash(h,"objeto",y)

   println(hash(h))
   println("arreglo 2?\n")
   get value("arreglo 2",h)
   println
   println("arreglo 1?\n")
   get value("arreglo 1",h)
   println

  /*  NO PUEDES ORDENAR UN HASH QUE CONTENGA ARRAYS
      PORQUE SE BLOQUEARA EL PROGRAMA:
   sort hash(h)
   {"\nORDENADO: \n"}println
   println(hash(h)) */

   println("Objeto?\n")
   get value("objeto",h)
   z=0,mov(z)
   /* Esto fallará, porque no se puede hacer un
      push de pushs*/
   pop(z),println
   pop(z),println
   pop(z),println
   {"Esto significa que no puedes meter un stack dentro de un hash\nsolo arrays de cualquier dimension"}println
   /* esto está bien, porque es un stack simple
      aunque contenga arreglos como elementos. */
   pop(y),println
   {"Dato en la última posición del stack:"}strtoutf8,{"\n"},[1:end,1:end]get(y),println
   {"Esto significa que, si vas a meter arreglos dentro de un stack\nsácalos con POP antes de usarlo"}strtoutf8,println
   pop(y),println
   pop(y),println

   pause
exit(0)


use std, array, hash

let keys = @["hexadecimal" "decimal" "octal" "binary"]
let values = @[0xa 11 014 0b1101] (: 10 11 12 13 :)
let hash = new hash of int
for each val int i from 0 to 3
  hash[keys[i]] = values[i]
del hash hash


h: dictionary.raw flatten couple [a b c d] [1 2 3 4]
print h


array1 := ["two", "three", "apple"]
array2 := [2, 3, "fruit"]
hash := {}
Loop % array1.maxIndex()
   hash[array1[A_Index]] := array2[A_Index]
MsgBox % hash["apple"] "`n" hash["two"]


class
    HELLO_WORLD
create
    make
feature
    make
        do
            print ("Hello world!%N")
        end
end


open monad io
do putStrLn "Hello world!" ::: IO


(defn digsum [n acc]
  (if (zero? n) acc
      (digsum (quot n 10) (+ acc (mod n 10)))))

(let [harshads (filter
                 #(zero? (mod % (digsum % 0)))
                 (iterate inc 1))]
  (prn (take 20 harshads))
  (prn (first (filter #(> % 1000) harshads))))


digit_sum = proc (n: int) returns (int)
    sum: int := 0
    while n > 0 do
        sum := sum + n // 10
        n := n / 10
    end
    return (sum)
end digit_sum

harshads = iter (n: int) yields (int)
    while true do
        n := n + 1
        if n // digit_sum(n) = 0 then yield(n) end
    end
end harshads

start_up = proc ()
    po: stream := stream$primary_output()
    count: int := 0

    stream$putl(po, "First 20 Harshad numbers: ")
    for h: int in harshads(0) do
        stream$putright(po, int$unparse(h), 3)
        count := count + 1
        if count = 20 then break end
    end

    stream$puts(po, "\nFirst Harshad number above 1000: ")
    for h: int in harshads(1000) do
        stream$putl(po, int$unparse(h))
        break
    end
end start_up


# usage:  awk -v list1="i ii iii" -v list2="1 2 3"  -f hash2.awk
BEGIN {
	if(!list1) list1="one two three"
	if(!list2) list2="1 2 3"

        split(list1, a);
        split(list2, b);
        for(i=1;i in a;i++) { c[a[i]] = b[i] };

        for(i in c) print i,c[i]
}


      DIM array1$(4) : array1$() = "0", "1", "2", "3", "4"
      DIM array2$(4) : array2$() = "zero", "one", "two", "three", "four"

      FOR index% = 0 TO DIM(array1$(),1)
        PROCputdict(mydict$, array2$(index%), array1$(index%))
      NEXT
      PRINT FNgetdict(mydict$, "3")
      END

      DEF PROCputdict(RETURN dict$, value$, key$)
      IF dict$ = "" dict$ = CHR$(0)
      dict$ += key$ + CHR$(1) + value$ + CHR$(0)
      ENDPROC

      DEF FNgetdict(dict$, key$)
      LOCAL I%, J%
      I% = INSTR(dict$, CHR$(0) + key$ + CHR$(1))
      IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
      J% = INSTR(dict$, CHR$(0), I%)
      = MID$(dict$, I%, J% - I%)


  two three apple:?arr1
& 2 3 fruit:?arr2
& new$hash:?H
&   whl
  ' ( !arr1:%?k ?arr1
    & !arr2:%?v ?arr2
    & (H..insert)$(!k.!v)
    )
& (H..forall)$out
& ;


F hash_join(table1, table2)
   DefaultDict[String, [(Int, String)]] h
   L(s) table1
      h[s[1]].append(s)

   [((Int, String), (String, String))] res
   L(r) table2
      L(s) h[r[0]]
         res [+]= (s, r)
   R res

V table1 = [(27, ‘Jonah’),
            (18, ‘Alan’),
            (28, ‘Glory’),
            (18, ‘Popeye’),
            (28, ‘Alan’)]
V table2 = [(‘Jonah’, ‘Whales’),
            (‘Jonah’, ‘Spiders’),
            (‘Alan’, ‘Ghosts’),
            (‘Alan’, ‘Zombies’),
            (‘Glory’, ‘Buffy’)]

L(row) hash_join(table1, table2)
   print(row)


package hello;

    // Import the `basic' package
    import basic;

    // Define a simple function
    function hello()
    {
        // Print hello world
        basic.print( "Hello world!\n" );
    }

    /*
     *  Here we start to execute package code
     */

    // Invoke the `hello' function
    hello();


public program()
{
    console.writeLine:"Hello world!"
}


identification division.
program-id. harshad.
environment division.
data division.
working-storage section.
*> for storing first 20 harshad-niven numbers
01  harshads.
    03  harshad pic 9(5)    occurs 20 times indexed by niven.

*> numbers tested for harshad-niven-ness.
01  first-num   pic 9(5).
01  second-num  pic 9(5).

*> loop counter
01  i   pic 9(5).

*> for calculating sum of digits
01  div pic 9(5).
01  mod pic 9(5).
01  tot pic 9(5).

*> for harshad-niven calculation and display
01  harshad-div pic 9(5).
01  harshad-mod pic 9(5).
    88  evenly-divisible    value 0.
01  harshad-disp    pic zzzz9.
01  harshad-result  pic 9(5).

*> for selecting what to do with results of harshad calculation
01  pass        pic 9.
    88  first-pass  value 1.
    88  second-pass value 2.

procedure division.
10-main section.
    move 1 to pass.
    set niven to 1.
    perform 20-calculate-harshad with test before varying first-num from 1 by 1 until niven = 21.

    move 2 to pass.
    move first-num to second-num.
    perform 20-calculate-harshad with test after varying first-num from second-num by 1 until harshad-result > 1000.

    perform with test after varying i from 1 by 1 until i = 20
        move harshad(i) to harshad-disp
        display function trim(harshad-disp) space with no advancing
    end-perform.

    move harshad-result to harshad-disp.
    display "... " function trim(harshad-disp).
    stop run.

20-calculate-harshad.
    move first-num to div.
    move zero to harshad-result.
    perform 100-calculate-sum-of-digits.
    divide first-num by tot giving harshad-div remainder harshad-mod.
    if evenly-divisible
        if first-pass
            move first-num to harshad(niven)
            set niven up by 1
        else
            move first-num to harshad-result
        end-if
    end-if.
    exit paragraph.

100-calculate-sum-of-digits.
    move zero to tot.
    perform with test after until div = 0
        divide div by 10 giving div remainder mod
        add mod to tot
    end-perform.
    *> if tot >= 10
    *>  move tot to div
    *>  go to 100-calculate-sum-of-digits
    *> end-if.
    exit paragraph.


zip = { keys, values |
	h = [:]
	keys.each_with_index { key, index |
		h[key] = values[index]
	}

	h
}

p zip [1 2 3] [:a :b :c]  #Prints [1: a, 2: b, 3: c]


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define KeyType const char *
#define ValType int

#define HASH_SIZE 4096

// hash function useful when KeyType is char * (string)
unsigned strhashkey( const char * key, int max)
{
    unsigned h=0;
    unsigned hl, hr;

    while(*key) {
        h += *key;
        hl= 0x5C5 ^ (h&0xfff00000 )>>18;
        hr =(h&0x000fffff );
        h = hl ^ hr ^ *key++;
    }
    return h % max;
}

typedef struct sHme {
    KeyType    key;
    ValType    value;
    struct sHme  *link;
} *MapEntry;

typedef struct he {
    MapEntry  first, last;
} HashElement;

HashElement hash[HASH_SIZE];

typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);
typedef void (*ValCopyF)(ValType *vdest, ValType vsrc);
typedef unsigned (*KeyHashF)( KeyType key, int upperBound );
typedef int (*KeyCmprF)(KeyType key1, KeyType key2);

void HashAddH( KeyType key, ValType value,
        KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )
{
    unsigned hix = (*hashKey)(key, HASH_SIZE);
    MapEntry m_ent;

    for (m_ent= hash[hix].first;
            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
    if (m_ent) {
        (*copyVal)(&m_ent->value, value);
    }
    else {
        MapEntry last;
        MapEntry hme = malloc(sizeof(struct sHme));
        (*copyKey)(&hme->key, key);
        (*copyVal)(&hme->value, value);
        hme->link = NULL;
        last = hash[hix].last;
        if (last) {
//	    printf("Dup. hash key\n");
            last->link = hme;
        }
        else
            hash[hix].first = hme;
        hash[hix].last = hme;
    }
}

int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )
{
    unsigned hix = (*hashKey)(key, HASH_SIZE);
    MapEntry m_ent;
    for (m_ent= hash[hix].first;
            m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
    if (m_ent) {
        *val = m_ent->value;
    }
    return (m_ent != NULL);
}

void copyStr(const char**dest, const char *src)
{
    *dest = strdup(src);
}
void copyInt( int *dest, int src)
{
    *dest = src;
}
int strCompare( const char *key1, const char *key2)
{
    return strcmp(key1, key2) == 0;
}

void HashAdd( KeyType key, ValType value )
{
    HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);
}

int HashGet(ValType *val, KeyType key)
{
    return HashGetH( val, key, &strhashkey, &strCompare);
}

int main()
{
    static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" };
    static int valuList[] = {1,43,640, 747, 42, 42};
    int ix;

    for (ix=0; ix<6; ix++) {
        HashAdd(keyList[ix], valuList[ix]);
    }
    return 0;
}


use framework "Foundation" -- Yosemite onwards, for record-handling functions

-- HASH JOIN -----------------------------------------------------------------

-- hashJoin :: [Record] -> [Record] -> String -> [Record]
on hashJoin(tblA, tblB, strJoin)
    set {jA, jB} to splitOn("=", strJoin)

    script instanceOfjB
        on |λ|(a, x)
            set strID to keyValue(x, jB)

            set maybeInstances to keyValue(a, strID)
            if maybeInstances is not missing value then
                updatedRecord(a, strID, maybeInstances & {x})
            else
                updatedRecord(a, strID, [x])
            end if
        end |λ|
    end script

    set M to foldl(instanceOfjB, {name:"multiMap"}, tblB)

    script joins
        on |λ|(a, x)
            set matches to keyValue(M, keyValue(x, jA))
            if matches is not missing value then
                script concat
                    on |λ|(row)
                        x & row
                    end |λ|
                end script

                a & map(concat, matches)
            else
                a
            end if
        end |λ|
    end script

    foldl(joins, {}, tblA)
end hashJoin

-- TEST ----------------------------------------------------------------------
on run
    set lstA to [¬
        {age:27, |name|:"Jonah"}, ¬
        {age:18, |name|:"Alan"}, ¬
        {age:28, |name|:"Glory"}, ¬
        {age:18, |name|:"Popeye"}, ¬
        {age:28, |name|:"Alan"}]

    set lstB to [¬
        {|character|:"Jonah", nemesis:"Whales"}, ¬
        {|character|:"Jonah", nemesis:"Spiders"}, ¬
        {|character|:"Alan", nemesis:"Ghosts"}, ¬
        {|character|:"Alan", nemesis:"Zombies"}, ¬
        {|character|:"Glory", nemesis:"Buffy"}, ¬
        {|character|:"Bob", nemesis:"foo"}]

    hashJoin(lstA, lstB, "name=character")
end run

-- RECORD FUNCTIONS ----------------------------------------------------------

-- keyValue :: String -> Record -> Maybe a
on keyValue(rec, strKey)
    set ca to current application
    set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s ¬
        objectForKey:strKey
    if v is not missing value then
        item 1 of ((ca's NSArray's arrayWithObject:v) as list)
    else
        missing value
    end if
end keyValue

-- updatedRecord :: Record -> String -> a -> Record
on updatedRecord(rec, strKey, varValue)
    set ca to current application
    set nsDct to (ca's NSMutableDictionary's dictionaryWithDictionary:rec)
    nsDct's setValue:varValue forKey:strKey
    item 1 of ((ca's NSArray's arrayWithObject:nsDct) as list)
end updatedRecord

-- GENERIC FUNCTIONS ---------------------------------------------------------

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- 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

-- splitOn :: Text -> Text -> [Text]
on splitOn(strDelim, strMain)
    set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
    set lstParts to text items of strMain
    set my text item delimiters to dlm
    return lstParts
end splitOn


<Cfset harshadNum = 0>
<Cfset counter = 0>

<Cfloop condition="harshadNum lte 1000">

  <Cfset startnum = harshadNum + 1>
  <Cfset digits = 0>
  <Cfset harshad = 0>

  <Cfloop condition="Harshad eq 0">

    <Cfset current_i = startnum>
    <Cfset digits = 0>

    <cfloop condition="len(current_i) gt 1">
      <Cfset digit = left(current_i, 1)>
      <Cfset current_i = right(current_i, len(current_i)-1)>
      <Cfset digits = digits + digit>
    </cfloop>
    <Cfset digits = digits + current_i>

    <Cfif Startnum MOD digits eq 0>
      <Cfset harshad = 1>
    <Cfelse>
      <cfset startnum = startnum + 1>
    </Cfif>

  </Cfloop>

  <cfset harshadNum = startnum>
  <Cfset counter = counter + 1>

  <Cfif counter lte 20>
    <Cfoutput>#harshadNum# </Cfoutput>
  </Cfif>

</Cfloop>

<Cfoutput>... #harshadNum# </Cfoutput>


static class Program
{
    static void Main()
    {
        System.Collections.Hashtable h = new System.Collections.Hashtable();

        string[] keys = { "foo", "bar", "val" };
        string[] values = { "little", "miss", "muffet" };

        System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length.");

        for (int i = 0; i < keys.Length; i++)
        {
            h.Add(keys[i], values[i]);
        }
    }
}


#include <unordered_map>
#include <string>

int main()
{
  std::string keys[] = { "1", "2", "3" };
  std::string vals[] = { "a", "b", "c" };

  std::unordered_map<std::string, std::string> hash;
  for( int i = 0 ; i < 3 ; i++ )
     hash[ keys[i] ] = vals[i] ;
}


shared void run() {
	value keys = [1, 2, 3];
	value items = ['a', 'b', 'c'];
	value hash = map(zipEntries(keys, items));
}


# syntax: GAWK -f HASH_JOIN.AWK [-v debug={0|1}] TABLE_A TABLE_B
#
# sorting:
#   PROCINFO["sorted_in"] is used by GAWK
#   SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
    FS = ","
    PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
    if (ARGC-1 != 2) {
      print("error: incorrect number of arguments") ; errors++
      exit # go to END
    }
}
{   if (NR == FNR) { # table A
      if (FNR == 1) {
        a_head = prefix_column_names("A")
        next
      }
      a_arr[$2][$1] = $0 # [name][age]
    }
    if (NR != FNR) { # table B
      if (FNR == 1) {
        b_head = prefix_column_names("B")
        next
      }
      b_arr[$1][$2] = $0 # [character][nemesis]
    }
}
END {
    if (errors > 0) { exit(1) }
    if (debug == 1) {
      dump_table(a_arr,a_head)
      dump_table(b_arr,b_head)
    }
    printf("%s%s%s\n",a_head,FS,b_head) # table heading
    for (i in a_arr) {
      if (i in b_arr) {
        for (j in a_arr[i]) {
          for (k in b_arr[i]) {
            print(a_arr[i][j] FS b_arr[i][k]) # join table A & table B
          }
        }
      }
    }
    exit(0)
}
function dump_table(arr,heading,  i,j) {
    printf("%s\n",heading)
    for (i in arr) {
      for (j in arr[i]) {
        printf("%s\n",arr[i][j])
      }
    }
    print("")
}
function prefix_column_names(p,  tmp) {
    tmp = p "." $0
    gsub(/,/,"&" p ".",tmp)
    return(tmp)
}


(     (27.Jonah)
      (18.Alan)
      (28.Glory)
      (18.Popeye)
      (28.Alan)
  : ?table-A
&     (Jonah.Whales)
      (Jonah.Spiders)
      (Alan.Ghosts)
      (Alan.Zombies)
      (Glory.Buffy)
  : ?table-B
& new$hash:?H
& !table-A:? [?lenA
& !table-B:? [?lenB
& ( join
  =     smalltab bigtab smallschema bigschema joinschema
      , key val val2 keyval2
    .     !arg
        : (?smalltab.?bigtab.(=?smallschema.?bigschema.?joinschema))
      & :?rel
      & !(
         ' (   whl
             ' ( !smalltab:$smallschema ?smalltab
               & (H..insert)$(!key.!val)
               )
           &   whl
             ' ( !bigtab:$bigschema ?bigtab
               & (   (H..find)$!key:?keyval2
                   &   whl
                     ' ( !keyval2:(?key.?val2) ?keyval2
                       & $joinschema !rel:?rel
                       )
                 |
                 )
               )
           )
         )
      & !rel
  )
&   out
  $ ( join
    $ (   !lenA:~<!lenB
        & ( !table-B
          . !table-A
          . (
            = (?key.?val).(?val.?key).!val.!key.!val2
            )
          )
      | ( !table-A
        . !table-B
        . (=(?val.?key).(?key.?val).!val2.!key.!val)
        )
      )
    )
&
);


0010 FUNC digit'sum(n)
0020   sum:=0
0030   WHILE n>0 DO sum:+n MOD 10;n:=n DIV 10
0040   RETURN sum
0050 ENDFUNC digit'sum
0060 //
0070 FUNC next'harshad(n)
0080   REPEAT
0090     n:+1
0100   UNTIL n MOD digit'sum(n)=0
0110   RETURN n
0120 ENDFUNC next'harshad
0130 //
0140 PRINT "First 20 Harshad numbers: "
0150 n:=0
0160 FOR i:=1 TO 20 DO
0170   n:=next'harshad(n)
0180   PRINT n;
0190 ENDFOR i
0200 PRINT
0210 PRINT "First Harshad number above 1000:";next'harshad(1000)
0220 END


(defun harshadp (n)
  (zerop (rem n (digit-sum n))))

(defun digit-sum (n &optional (a 0))
  (cond ((zerop n) a)
	(t (digit-sum (floor n 10) (+ a (rem n 10))))))

(defun list-harshad (n &optional (i 1) (lst nil))
  "list the first n Harshad numbers starting from i (default 1)"
  (cond ((= (length lst) n) (reverse lst))
	((harshadp i) (list-harshad n (+ i 1) (cons i lst)))
	(t (list-harshad n (+ i 1) lst))))


keys = <[apple banana orange grape]>
values = <[red yellow orange purple]>

object = new
    @[keys[i]] = values[i] for i til keys.length


  keys = ['a','b','c']
  values = [1,2,3]
  map = {}
  map[key] = values[i] for key, i in keys


<cfscript>
function makeHash(keyArray, valueArray) {
  var x = 1;
  var result = {};
  for( ; x <= ArrayLen(keyArray); x ++ ) {
    result[keyArray[x]] = valueArray[x];
  }
  return result;
}

keyArray = ['a', 'b', 'c'];
valueArray = [1, 2, 3];
map = makeHash(keyArray, valueArray);
</cfscript>


using System;
using System.Collections.Generic;
using System.Linq;

namespace HashJoin
{
    public class AgeName
    {
        public AgeName(byte age, string name)
        {
            Age = age;
            Name = name;
        }
        public byte Age { get; private set; }
        public string Name { get; private set; }
    }

    public class NameNemesis
    {
        public NameNemesis(string name, string nemesis)
        {
            Name = name;
            Nemesis = nemesis;
        }
        public string Name { get; private set; }
        public string Nemesis { get; private set; }
    }

    public class DataContext
    {
        public DataContext()
        {
            AgeName = new List<AgeName>();
            NameNemesis = new List<NameNemesis>();
        }
        public List<AgeName> AgeName { get; set; }
        public List<NameNemesis> NameNemesis { get; set; }
    }

    public class AgeNameNemesis
    {
        public AgeNameNemesis(byte age, string name, string nemesis)
        {
            Age = age;
            Name = name;
            Nemesis = nemesis;
        }
        public byte Age { get; private set; }
        public string Name { get; private set; }
        public string Nemesis { get; private set; }
    }

    class Program
    {
        public static void Main()
        {
            var data = GetData();
            var result = ExecuteHashJoin(data);
            WriteResultToConsole(result);
        }

        private static void WriteResultToConsole(List<AgeNameNemesis> result)
        {
            result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}",
                ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));
        }

        private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)
        {
            return (data.AgeName.Join(data.NameNemesis,
                ageName => ageName.Name, nameNemesis => nameNemesis.Name,
                (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))
                .ToList();
        }

        private static DataContext GetData()
        {
            var context = new DataContext();

            context.AgeName.AddRange(new [] {
                    new AgeName(27, "Jonah"),
                    new AgeName(18, "Alan"),
                    new AgeName(28, "Glory"),
                    new AgeName(18, "Popeye"),
                    new AgeName(28, "Alan")
                });

            context.NameNemesis.AddRange(new[]
            {
                new NameNemesis("Jonah", "Whales"),
                new NameNemesis("Jonah", "Spiders"),
                new NameNemesis("Alan", "Ghosts"),
                new NameNemesis("Alan", "Zombies"),
                new NameNemesis("Glory", "Buffy")
            });

            return context;
        }
    }
}


include "cowgol.coh";

sub digitsum(n: uint16): (sum: uint8) is
    sum := 0;
    while n != 0 loop
        sum := sum + (n % 10) as uint8;
        n := n / 10;
    end loop;
end sub;

sub nextHarshad(m: uint16): (n: uint16) is
    n := m;
    loop
        n := n + 1;
        if n % digitsum(n) as uint16 == 0 then
            return;
        end if;
    end loop;
end sub;

var n: uint16 := 0;
var i: uint16 := 0;

while n <= 1000 loop
    n := nextHarshad(n);
    i := i + 1;
    if i <= 20 then
        print_i16(n);
        print(" ");
    end if;
end loop;

print_nl();
print_i16(n);
print_nl();


harshad = 1.step.select { |n| n % n.to_s.chars.sum(&.to_i) == 0 }

puts "The first 20 harshard numbers are: \n#{ harshad.first(20).to_a }"
puts "The first harshard number > 1000 is #{ harshad.find { |n| n > 1000 } }"


(defun rosetta-code-hash-from-two-arrays (vector-1 vector-2 &key (test 'eql))
  (assert (= (length vector-1) (length vector-2)))
  (let ((table (make-hash-table :test test :size (length vector-1))))
    (map nil (lambda (k v) (setf (gethash k table) v))
             vector-1 vector-2)
    table))


void main() {
    import std.array, std.range;

    immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray;
}


#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>

using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {
// Age  Name
  {"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};

tab_t tab2 {
// Character  Nemesis
  {"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"}
, {"Alan", "Zombies"}
, {"Glory", "Buffy"}
};

std::ostream& operator<<(std::ostream& o, const tab_t& t) {
  for(size_t i = 0; i < t.size(); ++i) {
    o << i << ":";
    for(const auto& e : t[i])
      o << '\t' << e;
    o << std::endl;
  }
  return o;
}

tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {
  std::unordered_multimap<std::string, size_t> hashmap;
  // hash
  for(size_t i = 0; i < a.size(); ++i) {
    hashmap.insert(std::make_pair(a[i][columna], i));
  }
  // map
  tab_t result;
  for(size_t i = 0; i < b.size(); ++i) {
    auto range = hashmap.equal_range(b[i][columnb]);
    for(auto it = range.first; it != range.second; ++it) {
      tab_t::value_type row;
      row.insert(row.end() , a[it->second].begin() , a[it->second].end());
      row.insert(row.end() , b[i].begin()          , b[i].end());
      result.push_back(std::move(row));
    }
  }
  return result;
}

int main(int argc, char const *argv[])
{
  using namespace std;
  int ret = 0;
  cout << "Table A: "       << endl << tab1 << endl;
  cout << "Table B: "       << endl << tab2 << endl;
  auto tab3 = Join(tab1, 1, tab2, 0);
  cout << "Joined tables: " << endl << tab3 << endl;
  return ret;
}


! Hello World in ERRE language
PROGRAM HELLO
BEGIN
  PRINT("Hello world!")
END PROGRAM


void main() {
    import std.stdio, std.algorithm, std.range, std.conv;

    enum digSum = (int n) => n.text.map!(d => d - '0').sum;
    enum harshads = iota(1, int.max).filter!(n => n % digSum(n) == 0);

    harshads.take(20).writeln;
    harshads.filter!(h => h > 1000).front.writeln;
}


proc nonrec dsum(word n) word:
    word r;
    r := 0;
    while n ~= 0 do
        r := r + n % 10;
        n := n / 10
    od;
    r
corp

proc nonrec next_harshad(word n) word:
    while
        n := n + 1;
        n % dsum(n) ~= 0
    do od;
    n
corp

proc nonrec main() void:
    word n;
    byte i;
    write("First 20:");
    n := 0;
    for i from 1 upto 20 do
        n := next_harshad(n);
        write(" ", n)
    od;
    writeln();
    write("First above 1000: ", next_harshad(1000))
corp


local :h_keys [ :one :two :three ]
local :h_values [ 1 2 3 ]
local :h {}
for item in h_keys:
    set-to h item pop-from h_values


program Hash_from_two_arrays;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.Generics.Collections;

type
  THash = TDictionary<string, Integer>;

  THashHelper = class helper for THash
    procedure AddItems(keys: TArray<string>; values: TArray<Integer>);
  end;

{ THashHelper }

procedure THashHelper.AddItems(keys: TArray<string>; values: TArray<Integer>);
var
  i: Integer;
begin
  Assert(length(keys) = Length(values), 'Keys and values, must have the same size.');
  for i := 0 to High(keys) do
    AddOrSetValue(keys[i], values[i]);
end;

var
  hash: TDictionary<string, Integer>;
  i: integer;
  key: string;

begin
  hash := TDictionary<string, Integer>.Create();
  hash.AddItems(['a', 'b', 'c'], [1, 2, 3]);

  for key in hash.Keys do
    Writeln(key, '   ', hash[key]);

  hash.Free;

  readln;
end.


def keys := ["one", "two", "three"]
def values := [1, 2, 3]
__makeMap.fromColumns(keys, values)


(defn hash-join [table1 col1 table2 col2]
  (let [hashed (group-by col1 table1)]
    (flatten
      (for [r table2]
        (for [s (hashed (col2 r))]
          (merge s r))))))

(def s '({:age 27 :name "Jonah"}
         {:age 18 :name "Alan"}
         {:age 28 :name "Glory"}
         {:age 18 :name "Popeye"}
         {:age 28 :name "Alan"}))

(def r '({:nemesis "Whales" :name "Jonah"}
         {:nemesis "Spiders" :name "Jonah"}
         {:nemesis "Ghosts" :name "Alan"}
         {:nemesis "Zombies" :name "Alan"}
         {:nemesis "Buffy" :name "Glory"}))

(pprint (sort-by :name (hash-join s :name r :name)))


(defparameter *table-A* '((27 "Jonah") (18 "Alan") (28 "Glory") (18 "Popeye") (28 "Alan")))

(defparameter *table-B* '(("Jonah" "Whales") ("Jonah" "Spiders") ("Alan" "Ghosts") ("Alan" "Zombies") ("Glory" "Buffy")))

;; Hash phase
(defparameter *hash-table* (make-hash-table :test #'equal))

(loop for (i r) in *table-A*
   for value = (gethash r *hash-table* (list nil))  do
   (setf (gethash r *hash-table*) value)
   (push (list i r) (first value)))

;; Join phase
(loop for (i r) in *table-B* do
     (let ((val (car (gethash i *hash-table*))))
       (loop for (a b) in val do
	    (format t "{~a ~a} {~a ~a}~%"  a b i r))))


(define (harsh? n)
    (zero? (modulo n
        (apply + (map string->number (string->list (number->string n)))))))

(harsh? 42)
    → #t

(define H (stream-filter harsh? (in-naturals 1)))

(take H 20)
    → (1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42)

(for ((n H)) #:break (> n 1000) => n)
    → 1002


(lib 'hash)

(define H (make-hash))
(define keys '(elvis simon antoinette))
(define kvalues '("the king" "gallubert" "de gabolde d'Audan"))

(list->hash (map cons keys kvalues) H)
    → #hash:3
(hash-ref H 'elvis)
    → "the king"


iex(1)> keys = [:one, :two, :three]
[:one, :two, :three]
iex(2)> values = [1, 2, 3]
[1, 2, 3]
iex(3)> Enum.zip(keys, values) |> Enum.into(Map.new)
%{one: 1, three: 3, two: 2}


Dictionary = dict:from_list( lists:zip([key1, key2, key3], [value1, 2, 3]) ).


HashMultiMap(Array.zip [|"foo"; "bar"; "baz"|] [|16384; 32768; 65536|], HashIdentity.Structural)


import std.stdio, std.typecons;

auto hashJoin(size_t index1, size_t index2, T1, T2)
             (in T1[] table1, in T2[] table2) pure /*nothrow*/ @safe
if (is(typeof(T1.init[index1]) == typeof(T2.init[index2]))) {
    // Hash phase.
    T1[][typeof(T1.init[index1])] h;
    foreach (const s; table1)
        h[s[index1]] ~= s;

    // Join phase.
    Tuple!(const T1, const T2)[] result;
    foreach (const r; table2)
        foreach (const s; h.get(r[index2], null)) // Not nothrow.
            result ~= tuple(s, r);

    return result;
}

void main() {
    alias T = tuple;
    immutable table1 = [T(27, "Jonah"),
                        T(18, "Alan"),
                        T(28, "Glory"),
                        T(18, "Popeye"),
                        T(28, "Alan")];
    immutable table2 = [T("Jonah", "Whales"),
                        T("Jonah", "Spiders"),
                        T("Alan",  "Ghosts"),
                        T("Alan",  "Zombies"),
                        T("Glory", "Buffy")];

    foreach (const row; hashJoin!(1, 0)(table1, table2))
        writefln("(%s, %5s) (%5s, %7s)", row[0][], row[1][]);
}


hashJoin table1 index1 table2 index2:
    local :h {}
    # hash phase
    for s in table1:
        local :key s! index1
        if not has h key:
            set-to h key []
        push-to h! key s
    # join phase
    []
    for r in table2:
        for s in copy h! r! index2:
            push-through swap [ s r ]

local :table1 [ [ 27 "Jonah" ] [ 18 "Alan" ] [ 28 "Glory" ] [ 18 "Popeye" ] [ 28 "Alan" ] ]
local :table2 [ [ "Jonah" "Whales" ] [ "Jonah" "Spiders" ] [ "Alan" "Ghosts" ] [ "Alan" "Zombies" ] [ "Glory" "Buffy" ] ]

for row in hashJoin table1 1 table2 0:
    !. row


note
	description : "project application root class"
	date        : "$October 10, 2014$"
	revision    : "$Revision$"

class
	NIVEN_SERIES

create
	make

feature
	make
		local
			number : INTEGER
			count : INTEGER
			last : BOOLEAN
		do
			number := 1

			from
				number := 1
				last := false

			until
				last = true

			loop

				if
					(number \\ sum_of_digits(number) = 0)
				then
					count := count + 1

					if
						(count <= 20 )
					then
						print("%N")
						print(number)
					end

					if
						(number > 1000)
					then
						print("%N")
						print(number)
						last := true
					end
				end

				 number := number + 1
			end
		end

	sum_of_digits(no:INTEGER):INTEGER

		local
			sum : INTEGER
			num : INTEGER
		do
			sum := 0

			from
				num := no

			until
				num = 0

			loop
				sum := sum + num \\ 10
				num := num // 10
			end

			Result := sum
		end
end


defmodule Harshad do
  def series, do: Stream.iterate(1, &(&1+1)) |> Stream.filter(&(number?(&1)))

  def number?(n), do: rem(n, digit_sum(n, 0)) == 0

  defp digit_sum(0, sum), do: sum
  defp digit_sum(n, sum), do: digit_sum(div(n, 10), sum + rem(n, 10))
end

IO.inspect Harshad.series |> Enum.take(20)

IO.inspect Harshad.series |> Stream.drop_while(&(&1 <= 1000)) |> Enum.take(1) |> hd


USING: hashtables ;
{ "one" "two" "three" } { 1 2 3 } zip >hashtable


keys = [ 'a', 'b', 'c', 'd' ]
values = [ 1, 2, 3, 4 ]
hash = [ => ]
for i in [ 0 : keys.len() ]:  hash[ keys[ i ] ] = values[ i ]


class Main
{
  public static Void main ()
  {
    keys := [1,2,3,4,5]
    values := ["one", "two", "three", "four", "five"]

    // create an empty map
    map := [:]
    // add the key-value pairs to it
    keys.size.times |Int index|
    {
      map.add(keys[index], values[index])
    }
  }
}


Dim As String keys(1 To 5) = {"1", "2", "3", "4", "5"}
Dim As String values(1 To 5) = {"one", "two", "three", "four", "five"}
Dim As String hash(Lbound(keys) To Ubound(keys))
Dim As Integer i, temp

For i = Lbound(values) To Ubound(values)
    temp = Val(keys(i))
    hash(temp) = values(i)
Next i

For i = Lbound(hash) To Ubound(hash)
    Print keys(i); " "; hash(i)'; " "; i
Next i
Sleep


(define ages '((27 "Jonah") (18 "Alan") (28 "Glory") (18 "Popeye") (28 "Alan")))
(define nemesis '(("Jonah" "Whales") ("Jonah" "Spiders") ("Alan" "Ghosts") ("Alan" "Zombies") ("Glory" "Buffy")))

;; table: table name
;; source : input list
;; key-proc : procedure returning the join value ('name' in this task)

(define (table-hash table source key-proc )
(local-make-store table)
(for ((r source))
	(local-put-value
		(key-proc r)
		(append (list r) (local-get-value (key-proc r) table)) table)))

;; build the two tables
(define-syntax-rule (second record) (cadr record))
(define (key-name-age record) (second record))
(table-hash 'AGES ages key-name-age)

(define (key-nemesis-name record) (first record))
(table-hash 'NEMESIS nemesis key-nemesis-name)

;; join
(for* ((k (local-keys 'AGES))
	  (a (local-get-value k 'AGES))
	  (n (local-get-value k 'NEMESIS)))
	  (writeln a n))


LeftRec := RECORD
  UNSIGNED1 Age;
  STRING6   Name;
END;

LeftFile := DATASET([{27,'Jonah'},{18,'Alan'},{28,'Glory'},{18,'Popeye'},{28,'Alan'}],LeftRec);

RightRec := RECORD
  STRING6   Name;
  STRING7   Nemesis;
END;

RightFile := DATASET([{'Jonah','Whales'},{'Jonah','Spiders'},{'Alan','Ghosts'},{'Alan','Zombies'},{'Glory','Buffy'}],
                     RightRec);

HashJoin := JOIN(LeftFile,RightFile,Left.Name = RIGHT.Name,HASH);

HashJoin;

//The HASH JOIN is built-in to the ECL JOIN by using the HASH JOIN Flag

/*
OUTPUT:
Age Name  Nemesis
18  Alan  Ghosts
18  Alan  Zombies
28  Alan  Ghosts
28  Alan  Zombies
28  Glory Buffy
27  Jonah Whales
27  Jonah Spiders
*/


defmodule Hash do
  def join(table1, index1, table2, index2) do
    h = Enum.group_by(table1, fn s -> elem(s, index1) end)
    Enum.flat_map(table2, fn r ->
      Enum.map(h[elem(r, index2)], fn s -> {s, r} end)
    end)
  end
end

table1 = [{27, "Jonah"},
          {18, "Alan"},
          {28, "Glory"},
          {18, "Popeye"},
          {28, "Alan"}]
table2 = [{"Jonah", "Whales"},
          {"Jonah", "Spiders"},
          {"Alan",  "Ghosts"},
          {"Alan",  "Zombies"},
          {"Glory", "Buffy"}]
Hash.join(table1, 1, table2, 0) |> Enum.each(&IO.inspect &1)


-module( harshad ).

-export( [greater_than/1, sequence/1, task/0] ).

greater_than( N ) when N >= 1  ->
        greater_than( 2, N, acc(1, {0, []}) ).

sequence( Find_this_many ) when Find_this_many >= 1 ->
        sequence( 2, Find_this_many, acc(1, {0, []}) ).

task() ->
        io:fwrite( "~p~n", [sequence(20)] ),
        io:fwrite( "~p~n", [greater_than(1000)] ).

acc( N, Acc ) -> acc( N rem lists:sum([X - $0|| X <- erlang:integer_to_list(N)]), N, Acc ).

acc( 0, N, {Found, Acc} ) -> {Found + 1, [N | Acc]};
acc( _Reminder, _N, Acc ) -> Acc.

greater_than( _N, Find, {_, [Found | _T]} ) when Found > Find -> Found;
greater_than( N, Find, Acc ) ->	greater_than( N + 1, Find, acc(N, Acc) ).

sequence( _N, Found, {Found, Acc} ) -> lists:reverse( Acc );
sequence( N, Find, Acc ) -> sequence( N + 1, Find, acc(N, Acc) ).


Public Sub Main()
Dim sValue As String[] = ["Zero", "One", "Two", "Three", "Four", "Five"]
Dim sKey As String[] = [0, 1, 2, 3, 4, 5]
Dim sCol As New Collection
Dim siCount As Short

For siCount = 0 To sKey.max
  sCol.Add(sValue[siCount], sKey[siCount])
Next

For siCount = 0 To sKey.max
  Print Str(sicount) & " = " & sCol[siCount]
Next

End


package main

import "fmt"

func main() {
    keys := []string{"a", "b", "c"}
    vals := []int{1, 2, 3}
    hash := map[string]int{}
    for i, key := range keys {
        hash[key] = vals[i]
    }
    fmt.Println(hash)
}


-module( hash_join ).

-export( [task/0] ).

task() ->
    Table_1 = [{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}],
    Table_2 = [{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}],
    Dict = lists:foldl( fun dict_append/2, dict:new(), Table_1 ),
    lists:flatten( [dict_find( X, Dict ) || X <- Table_2] ).

dict_append( {Key, Value}, Acc ) -> dict:append( Value, {Key, Value}, Acc ).

dict_find( {Key, Value}, Dict ) -> dict_find( dict:find(Key, Dict), Key, Value ).

dict_find( error, _Key, _Value ) -> [];
dict_find( {ok,	Values}, Key, Value ) -> [{X, {Key, Value}} || X <- Values].


[<EntryPoint>]
let main argv =
    let table1 = [27, "Jonah";
                18, "Alan";
                28, "Glory";
                18, "Popeye";
                28, "Alan"]
    let table2 = ["Jonah", "Whales";
                "Jonah", "Spiders";
                "Alan", "Ghosts";
                "Alan", "Zombies";
                "Glory", "Buffy"]
    let hash = Seq.groupBy (fun r -> snd r) table1
    table2
    |> Seq.collect (fun r ->
        hash
        |> Seq.collect (fun kv ->
            if (fst r) <> (fst kv) then []
            else (Seq.map (fun x -> (x, r)) (snd kv)) |> Seq.toList)
        )
    |> Seq.toList
    |> printfn "%A"
    0


class HelloText
{
  public static Void main ()
  {
    echo ("Hello world!")
  }
}


nextHarshad
=LAMBDA(n,
    UNTIL(
        LAMBDA(x,
            0 = MOD(x, decDigitSum(x))
        )
    )(
        LAMBDA(x, 1 + x)
    )(1 + n)
)

harshads
=LAMBDA(n,
    UNTIL(
        LAMBDA(xs, n = ROWS(xs))
    )(
        LAMBDA(xs,
            APPENDROWS(xs)(
                nextHarshad(
                    INDEX(LASTROW(xs), 1)
                )
            )
        )
    )(
        {1}
    )
)


let divides d n =
    match bigint.DivRem(n, d) with
    | (_, rest) -> rest = 0I

let splitToInt (str:string) = List.init str.Length (fun i -> ((int str.[i]) - (int "0".[0])))

let harshads =
    let rec loop n = seq {
        let sum = List.fold (+) 0 (splitToInt (n.ToString()))
        if divides (bigint sum) n then yield n
        yield! loop (n + 1I)
    }
    loop 1I

[<EntryPoint>]
let main argv =
    for h in (Seq.take 20 harshads) do printf "%A " h
    printfn ""
    printfn "%A" (Seq.find (fun n -> n > 1000I) harshads)
    0


def keys = ['a','b','c']
def vals = ['aaa', 'bbb', 'ccc']
def hash = [:]
keys.eachWithIndex { key, i ->
 hash[key] = vals[i]
}


LOCAL arr1 := { 6, "eight" }, arr2 := { 16, 8 }
LOCAL hash := { => }
LOCAL i, j

FOR EACH i, j IN arr1, arr2
   hash[ i ] := j
NEXT


import Data.Map

makeMap ks vs = fromList $ zip ks vs
mymap = makeMap ['a','b','c'] [1,2,3]


from Algorithms import materialize, zip;

main() {
  keys = [1, 2, 3];
  values = ['a', 'b', 'c'];
  hash = materialize( zip( key, values ), lookup );
}


include FMS-SI.f
include FMS-SILib.f

\ Since the same join attribute, Name, occurs more than once
\ in both tables for this problem we need a hash table that
\ will accept and retrieve multiple identical keys if we want
\ an efficient solution for large tables. We make use
\ of the hash collision handling feature of class hash-table.

\ Subclass hash-table-m allows multiple entries with the same key.
\ After a get: hit one can inspect for additional entries with
\ the same key by using next: until false is returned.

:class hash-table-m <super hash-table

\ called within insert: method in superclass
 :m (do-search): ( node hash -- idx hash false )
      swap drop idx @ swap false ;m
 :m next: ( -- val true | false )
    last-node @ dup
    if
      begin
       ( node ) next: dup
      while
        dup [email protected]: @: key-addr @ key-len @ compare 0=
             if dup last-node ! [email protected]: true exit then
      repeat
    then ;m
;class

\ begin hash phase
: obj ( addr len -- obj )
  heap> string+ dup >r !: r> ;

hash-table-m R   1 r init
s" Whales "   obj s" Jonah" r insert:
s" Spiders "  obj s" Jonah" r insert:
s" Ghosts "   obj s" Alan"  r insert:
s" Buffy "    obj s" Glory" r insert:
s" Zombies "  obj s" Alan"  r insert:
s" Vampires " obj s" Jonah" r insert:
\ end hash phase

\ create Age Name table S
o{ o{ 27 'Jonah' }
   o{ 18 'Alan' }
   o{ 28 'Glory' }
   o{ 18 'Popeye' }
   o{ 28 'Alan' } } value s

\ Q is a place to store the relation
object-list2 Q

\ join phase
: join \ { obj | list -- }
  0 locals| list obj |
  1 obj at: @: r get: \ hash the join-attribute and search table r
  if \ we have a match, so concatenate and save in q
    heap> object-list2 to list list q add: \ start a new sub-list in q
    0 obj at: copy: list add: \ place age from list s in q
    1 obj at: copy: list add: \ place join-attribute (name) from list s in q
    ( str-obj ) copy: list add: \ place first nemesis in q
    begin
      r next: \ check for more nemeses
    while
       ( str-obj ) copy: list add: \ place next nemesis in q
    repeat
  then ;

: probe
  begin
    s each: \ for each tuple object in s
  while
    ( obj ) join \ pass the object to function join
  repeat ;

probe \ execute the probe function

q p: \ print the saved relation

\ free allocated memory
s <free
r free2:
q free:


package main

import "fmt"

func main() {
    tableA := []struct {
        value int
        key   string
    }{
        {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
        {28, "Alan"},
    }
    tableB := []struct {
        key   string
        value string
    }{
        {"Jonah", "Whales"}, {"Jonah", "Spiders"},
        {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
    }
    // hash phase
    h := map[string][]int{}
    for i, r := range tableA {
        h[r.key] = append(h[r.key], i)
    }
    // join phase
    for _, x := range tableB {
        for _, a := range h[x.key] {
            fmt.Println(tableA[a], x)
        }
    }
}


def hashJoin(table1, col1, table2, col2) {

    def hashed = table1.groupBy { s -> s[col1] }

    def q = [] as Set

    table2.each { r ->
        def join = hashed[r[col2]]
        join.each { s ->
            q << s.plus(r)
        }
    }

    q
}


uses "console";
Console.println( "Goodby, World!" );


USING: math.text.utils lists lists.lazy ;

: niven? ( n -- ? ) dup 1 digit-groups sum mod 0 = ;

: first-n-niven ( n -- seq )
    1 lfrom [ niven? ] lfilter ltake list>array ;

: next-niven ( n -- m ) 1 + [ dup niven? ] [ 1 + ] until ;

20 first-n-niven .
1000 next-niven .


#APPTYPE CONSOLE

CLASS harshad
    PRIVATE:
    memo[]

    SUB INITIALIZE()
        DIM i = 1, c
        DO
            IF isNiven(i) THEN
                c = c + 1
                memo[c] = i
            END IF
            i = i + 1
            IF c = 20 THEN EXIT DO
        LOOP
        memo[] = "..."
        i = 1000
        WHILE NOT isNiven(INCR(i)): WEND
        memo[] = i
    END SUB

    FUNCTION isNiven(n)
        RETURN NOT (n MOD sumdigits(n))
    END FUNCTION

    FUNCTION sumdigits(n)
        DIM num = n, m, sum
        WHILE num
            sum = sum + num MOD 10
            num = num \ 10
        WEND
        RETURN sum
    END FUNCTION

    PUBLIC:
    METHOD Yield()
        FOREACH DIM e IN memo
            PRINT e, " ";
        NEXT
    END METHOD
END CLASS

DIM niven AS NEW harshad
niven.Yield()

PAUSE


link ximage    # to format the structure

procedure main(arglist)                          #: demonstrate hash from 2 lists
local keylist

if *arglist = 0 then arglist := [1,2,3,4]        # ensure there's a list
every put(keylist := [], "key-" || !arglist)     # make keys for each entry

every  (T := table())[keylist[ i := 1 to *keylist ]] := arglist[i]  # create the hash table

write(ximage(T))                                 # show result
end


{} addKeysAndValues([:a, :b, :c], [1, 2, 3])


import java.util.HashMap;
public static void main(String[] args){
	String[] keys= {"a", "b", "c"};
	int[] vals= {1, 2, 3};
	HashMap<String, Integer> hash= new HashMap<String, Integer>();

	for(int i= 0; i < keys.length; i++){
	   hash.put(keys[i], vals[i]);
	}
}


{-# LANGUAGE LambdaCase, TupleSections #-}
import qualified Data.HashTable.ST.Basic as H
import Data.Hashable
import Control.Monad.ST
import Control.Monad
import Data.STRef

hashJoin :: (Eq k, Hashable k) =>
            [t] -> (t -> k) -> [a] -> (a -> k) -> [(t, a)]
hashJoin xs fx ys fy = runST $ do
  l <- newSTRef []
  ht <- H.new
  forM_ ys $ \y -> H.insert ht (fy y) =<<
    (H.lookup ht (fy y) >>= \case
      Nothing -> return [y]
      Just v -> return (y:v))
  forM_ xs $ \x -> do
    H.lookup ht (fx x) >>= \case
      Nothing -> return ()
      Just v -> modifySTRef' l ((map (x,)  v) ++)
  readSTRef l

main = mapM_ print $ hashJoin
    [(1, "Jonah"), (2, "Alan"), (3, "Glory"), (4, "Popeye")]
        snd
    [("Jonah", "Whales"), ("Jonah", "Spiders"),
      ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")]
        fst


table1=: ;:;._2(0 :0)
  27 Jonah
  18 Alan
  28 Glory
  18 Popeye
  28 Alan
)

table2=: ;:;._2(0 :0)
  Jonah Whales
  Jonah Spiders
  Alan Ghosts
  Alan Zombies
  Glory Buffy
)


import java.util.*;

public class HashJoin {

    public static void main(String[] args) {
        String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
        {"18", "Popeye"}, {"28", "Alan"}};

        String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
        {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
        {"Bob", "foo"}};

        hashJoin(table1, 1, table2, 0).stream()
                .forEach(r -> System.out.println(Arrays.deepToString(r)));
    }

    static List<String[][]> hashJoin(String[][] records1, int idx1,
            String[][] records2, int idx2) {

        List<String[][]> result = new ArrayList<>();
        Map<String, List<String[]>> map = new HashMap<>();

        for (String[] record : records1) {
            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());
            v.add(record);
            map.put(record[idx1], v);
        }

        for (String[] record : records2) {
            List<String[]> lst = map.get(record[idx2]);
            if (lst != null) {
                lst.stream().forEach(r -> {
                    result.add(new String[][]{r, record});
                });
            }
        }

        return result;
    }
}


with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;

package Sigint_Handler is
      protected Handler is
      entry Wait;
      procedure Handle;
      pragma Interrupt_Handler(Handle);
      pragma Attach_Handler(Handle, Sigint);
      private
      Call_Count : Natural := 0;
   end Handler;

end Sigint_Handler;