Kernighans large earthquake problem: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 21: Line 21:
{{trans|Python}}
{{trans|Python}}


<lang 11l>L(ln) File(‘data.txt’).read_lines()
<syntaxhighlight lang="11l">L(ln) File(‘data.txt’).read_lines()
I Float(ln.split(‘ ’, group_delimiters' 1B)[2]) > 6
I Float(ln.split(‘ ’, group_delimiters' 1B)[2]) > 6
print(ln)</lang>
print(ln)</syntaxhighlight>


{{out}}
{{out}}
Line 34: Line 34:
I'm going to make the assumption that all magnitudes are given as floating points rounded to one decimal place, e.g. "6.0" when the magnitude is exactly 6. That way I don't need to actually use floating point logic. The hardware print routines were omitted to keep things short, since the Sega Genesis doesn't have a built-in kernel and so I'd have to manually write to the video chip. Chances are you're not interested in seeing all that fluff when you'd rather look at the actual algorithm for the task.
I'm going to make the assumption that all magnitudes are given as floating points rounded to one decimal place, e.g. "6.0" when the magnitude is exactly 6. That way I don't need to actually use floating point logic. The hardware print routines were omitted to keep things short, since the Sega Genesis doesn't have a built-in kernel and so I'd have to manually write to the video chip. Chances are you're not interested in seeing all that fluff when you'd rather look at the actual algorithm for the task.


<lang 68000devpac>;Macros
<syntaxhighlight lang="68000devpac">;Macros
macro pushRegs 1
macro pushRegs 1
MOVEM.L \1,-(SP)
MOVEM.L \1,-(SP)
Line 149: Line 149:
bra lineseek
bra lineseek
.done:
.done:
RTS</lang>
RTS</syntaxhighlight>
{{out}}
{{out}}
<pre>8/27/1883 Krakatoa 8.8
<pre>8/27/1883 Krakatoa 8.8
Line 164: Line 164:
automatically.
automatically.


<lang 8080asm>FCB1: equ 5Ch ; FCB for first command line argument
<syntaxhighlight lang="8080asm">FCB1: equ 5Ch ; FCB for first command line argument
puts: equ 9 ; CP/M syscall to print a string
puts: equ 9 ; CP/M syscall to print a string
fopen: equ 15 ; CP/M syscall to open a file
fopen: equ 15 ; CP/M syscall to open a file
Line 230: Line 230:
jmp 5
jmp 5
emsg: db 'Error!$'
emsg: db 'Error!$'
line: equ $ ; Line buffer after program </lang>
line: equ $ ; Line buffer after program </syntaxhighlight>


{{out}}
{{out}}
Line 252: Line 252:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
{{libheader|Action! Real Math}}
<lang Action!>INCLUDE "H6:REALMATH.ACT"
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"


BYTE FUNC FindFirstNonspace(CHAR ARRAY s BYTE start)
BYTE FUNC FindFirstNonspace(CHAR ARRAY s BYTE start)
Line 314: Line 314:
PrintRE(value) PutE()
PrintRE(value) PutE()
Process(fname,value,1)
Process(fname,value,1)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Kernighans_large_earthquake_problem.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Kernighans_large_earthquake_problem.png Screenshot from Atari 8-bit computer]
Line 339: Line 339:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>-- Kernighans large earthquake problem
<syntaxhighlight lang="ada">-- Kernighans large earthquake problem
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
Line 371: Line 371:
end loop;
end loop;
Close (Inpt_File);
Close (Inpt_File);
end Main;</lang>
end Main;</syntaxhighlight>
The file data.txt contains a 0 length line as well as a line composed of only blanks.
The file data.txt contains a 0 length line as well as a line composed of only blanks.
<pre>
<pre>
Line 391: Line 391:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>IF FILE input file;
<syntaxhighlight lang="algol68">IF FILE input file;
STRING file name = "data.txt";
STRING file name = "data.txt";
open( input file, file name, stand in channel ) /= 0
open( input file, file name, stand in channel ) /= 0
Line 461: Line 461:
# close the file #
# close the file #
close( input file )
close( input file )
FI</lang>
FI</syntaxhighlight>


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
/* Kernighans large earthquake problem. */
/* Kernighans large earthquake problem. */


Line 491: Line 491:
CEND
CEND
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 534: Line 534:
<p>On the other hand, HOPPER processes dates in DD/MM/YYYY format, and the file records dates in MM/DD/YYYY format: therefore, it is necessary to exchange "DD" for "MM", because HOPPER does not allow other types of format for "dates".</p>
<p>On the other hand, HOPPER processes dates in DD/MM/YYYY format, and the file records dates in MM/DD/YYYY format: therefore, it is necessary to exchange "DD" for "MM", because HOPPER does not allow other types of format for "dates".</p>
<p>The final program would be as follows:</p>
<p>The final program would be as follows:</p>
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
/* Kernighans large earthquake problem. */
/* Kernighans large earthquake problem. */


Line 568: Line 568:
CEND
CEND
END
END
</syntaxhighlight>
</lang>
<p>And this is fast!</p>
<p>And this is fast!</p>
<p>If you want to print the original dates, just add the line "Swap Day By Month(1,2)" before printing the result. In this case, the results are printed with the dates changed.</p>
<p>If you want to print the original dates, just add the line "Swap Day By Month(1,2)" before printing the result. In this case, the results are printed with the dates changed.</p>
Line 581: Line 581:
=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang applescript>on kernighansEarthquakes(magnitudeToBeat)
<syntaxhighlight lang="applescript">on kernighansEarthquakes(magnitudeToBeat)
-- A local "owner" for the long AppleScript lists. Speeds up references to their items and properties.
-- A local "owner" for the long AppleScript lists. Speeds up references to their items and properties.
script o
script o
Line 616: Line 616:
end kernighansEarthquakes
end kernighansEarthquakes


kernighansEarthquakes(6)</lang>
kernighansEarthquakes(6)</syntaxhighlight>


===Functional===
===Functional===
Line 623: Line 623:
while emphasising code reuse, and speed of writing and refactoring:
while emphasising code reuse, and speed of writing and refactoring:


<lang applescript>use AppleScript version "2.4"
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use framework "Foundation"
use scripting additions
use scripting additions
Line 762: Line 762:
set my text item delimiters to dlm
set my text item delimiters to dlm
str
str
end unlines</lang>
end unlines</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Magnitudes above 6.0 in ~/Desktop/data.txt:
<pre>Magnitudes above 6.0 in ~/Desktop/data.txt:
Line 775: Line 775:
and the magnitude as an optional left argument (defaulting to 6).
and the magnitude as an optional left argument (defaulting to 6).


<lang APL>quakes←{
<syntaxhighlight lang="apl">quakes←{
⍺←6
⍺←6
nl←⎕UCS 13 10
nl←⎕UCS 13 10
Line 782: Line 782:
keep←⍺{0::0 ⋄ ⍺ < ⍎3⊃(~⍵∊4↑⎕TC)⊆⍵}¨lines
keep←⍺{0::0 ⋄ ⍺ < ⍎3⊃(~⍵∊4↑⎕TC)⊆⍵}¨lines
↑keep/lines
↑keep/lines
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 799: Line 799:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>data: {
<syntaxhighlight lang="rebol">data: {
3/13/2009 CostaRica 5.1
3/13/2009 CostaRica 5.1
8/27/1883 Krakatoa 8.8
8/27/1883 Krakatoa 8.8
Line 808: Line 808:


print first sort.descending.by:'magnitude map split.lines data =>
print first sort.descending.by:'magnitude map split.lines data =>
[to :earthquake split.words &]</lang>
[to :earthquake split.words &]</syntaxhighlight>


{{out}}
{{out}}
Line 815: Line 815:


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk> awk '$3 > 6' data.txt</lang>
<syntaxhighlight lang="awk"> awk '$3 > 6' data.txt</syntaxhighlight>


=={{header|Bash}}==
=={{header|Bash}}==
<lang bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash
while read line
while read line
do
do
[[ ${line##* } =~ ^([7-9]|6\.0*[1-9]).*$ ]] && echo "$line"
[[ ${line##* } =~ ^([7-9]|6\.0*[1-9]).*$ ]] && echo "$line"
done < data.txt</lang>
done < data.txt</syntaxhighlight>


{{out}}
{{out}}
Line 840: Line 840:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
<lang BASIC256>
f = freefile
f = freefile
filename$ = "data.txt"
filename$ = "data.txt"
Line 852: Line 852:
close f
close f
end
end
</syntaxhighlight>
</lang>




=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <string.h>
#include <stdlib.h>
#include <stdlib.h>
Line 883: Line 883:
if (line) free(line);
if (line) free(line);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 895: Line 895:


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.IO;
using System.IO;
using System.Linq;
using System.Linq;
Line 913: Line 913:
select parts;
select parts;


}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>// Randizo was here!
<syntaxhighlight lang="cpp">// Randizo was here!
#include <iostream>
#include <iostream>
#include <fstream>
#include <fstream>
Line 959: Line 959:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


New version:
New version:
<lang cpp>// Jolkdarr was also here!
<syntaxhighlight lang="cpp">// Jolkdarr was also here!
#include <iostream>
#include <iostream>
#include <iomanip>
#include <iomanip>
Line 984: Line 984:
cout << endl << "Number of quakes greater than 6 is " << count_quake << endl;
cout << endl << "Number of quakes greater than 6 is " << count_quake << endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Cixl}}==
=={{header|Cixl}}==
<lang cixl>
<syntaxhighlight lang="cixl">
use: cx;
use: cx;


Line 995: Line 995:
$m1 6 >= $m2 0 > and {[$time @@s $place @@s $mag] say} if
$m1 6 >= $m2 0 > and {[$time @@s $place @@s $mag] say} if
} for
} for
</syntaxhighlight>
</lang>


{{output}}
{{output}}
Line 1,007: Line 1,007:
First, with a data file. This adds a fair amount of verbosity to COBOL. For something this one-off, a simpler cut using ACCEPT from standard in is shown.
First, with a data file. This adds a fair amount of verbosity to COBOL. For something this one-off, a simpler cut using ACCEPT from standard in is shown.


<lang cobol>
<syntaxhighlight lang="cobol">
*>
*>
*> Kernighan large earthquake problem
*> Kernighan large earthquake problem
Line 1,093: Line 1,093:
.
.


end program quakes.</lang>
end program quakes.</syntaxhighlight>


{{output}}
{{output}}
Line 1,108: Line 1,108:
A slighter shorter-version.
A slighter shorter-version.


<lang cobol> *>
<syntaxhighlight lang="cobol"> *>
*> Tectonics: ./kerighan-earth-quakes <quakes.txt
*> Tectonics: ./kerighan-earth-quakes <quakes.txt
identification division.
identification division.
Line 1,140: Line 1,140:


goback.
goback.
end program quakes.</lang>
end program quakes.</syntaxhighlight>


That cut would be used as <pre>prompt$ ./kernighans-large-earthquakes <quakes.txt</pre>
That cut would be used as <pre>prompt$ ./kernighans-large-earthquakes <quakes.txt</pre>


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "file.coh";
include "file.coh";


Line 1,226: Line 1,226:
end if;
end if;


ForEachLine(&quakes, PrintIfGt6); </lang>
ForEachLine(&quakes, PrintIfGt6); </syntaxhighlight>


{{out}}
{{out}}
Line 1,243: Line 1,243:
=={{header|D}}==
=={{header|D}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang d>import std.conv : to;
<syntaxhighlight lang="d">import std.conv : to;
import std.regex : ctRegex, split;
import std.regex : ctRegex, split;
import std.stdio : File, writeln;
import std.stdio : File, writeln;
Line 1,257: Line 1,257:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Those earthquakes with a magnitude > 6.0 are:
<pre>Those earthquakes with a magnitude > 6.0 are:
Line 1,264: Line 1,264:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>(with-temp-buffer
<syntaxhighlight lang="lisp">(with-temp-buffer
(insert-file-contents "data.txt")
(insert-file-contents "data.txt")
(goto-char (point-min))
(goto-char (point-min))
Line 1,273: Line 1,273:
(when (> (string-to-number magn) 6.0)
(when (> (string-to-number magn) 6.0)
(message line)))
(message line)))
(forward-line 1)))</lang>
(forward-line 1)))</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<code>lines</code> is a convenience word that reads lines from standard input. If you don't want to type them all in yourself, it is suggested that you give the program a file to read. For example, on the Windows command line: <code>factor kernighan.factor < earthquakes.txt</code>
<code>lines</code> is a convenience word that reads lines from standard input. If you don't want to type them all in yourself, it is suggested that you give the program a file to read. For example, on the Windows command line: <code>factor kernighan.factor < earthquakes.txt</code>
<lang factor>USING: io math math.parser prettyprint sequences splitting ;
<syntaxhighlight lang="factor">USING: io math math.parser prettyprint sequences splitting ;
IN: rosetta-code.kernighan
IN: rosetta-code.kernighan


lines [ "\s" split last string>number 6 > ] filter .</lang>
lines [ "\s" split last string>number 6 > ] filter .</syntaxhighlight>




=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>
<syntaxhighlight lang="freebasic">
Dim As Long f
Dim As Long f
f = Freefile
f = Freefile
Line 1,301: Line 1,301:
Close #f
Close #f
Sleep
Sleep
</syntaxhighlight>
</lang>




=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,336: Line 1,336:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,348: Line 1,348:
=={{header|Groovy}}==
=={{header|Groovy}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang groovy>import java.util.regex.Pattern
<syntaxhighlight lang="groovy">import java.util.regex.Pattern


class LargeEarthquake {
class LargeEarthquake {
Line 1,361: Line 1,361:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Those earthquakes with a magnitude > 6.0 are:
<pre>Those earthquakes with a magnitude > 6.0 are:
Line 1,369: Line 1,369:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import qualified Data.ByteString.Lazy.Char8 as C
<syntaxhighlight lang="haskell">import qualified Data.ByteString.Lazy.Char8 as C


main :: IO ()
main :: IO ()
Line 1,378: Line 1,378:
(\x ->
(\x ->
[ x
[ x
| 6 < (read (last (C.unpack <$> C.words x)) :: Float) ])</lang>
| 6 < (read (last (C.unpack <$> C.words x)) :: Float) ])</syntaxhighlight>
{{Out}}
{{Out}}
<pre>"8/27/1883 Krakatoa 8.8"
<pre>"8/27/1883 Krakatoa 8.8"
Line 1,384: Line 1,384:


=={{header|J}}==
=={{header|J}}==
<syntaxhighlight lang="j">
<lang J>
NB. this program is designed for systems where the line ending is either LF or CRLF
NB. this program is designed for systems where the line ending is either LF or CRLF


Line 1,399: Line 1,399:
(y <: magnitudes) # lines
(y <: magnitudes) # lines
)
)
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 1,409: Line 1,409:
=={{header|Java}}==
=={{header|Java}}==
Input file contains sample data shown in the task
Input file contains sample data shown in the task
<syntaxhighlight lang="java">
<lang Java>
import java.io.BufferedReader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileReader;
Line 1,430: Line 1,430:


}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,440: Line 1,440:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
Input file contains sample data shown in the task. The code below uses Nodejs to read the file.
Input file contains sample data shown in the task. The code below uses Nodejs to read the file.
<syntaxhighlight lang="javascript">
<lang JavaScript>
const fs = require("fs");
const fs = require("fs");
const readline = require("readline");
const readline = require("readline");
Line 1,463: Line 1,463:
}
}
});
});
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,487: Line 1,487:
where data.txt is as for [[#Snobol|Snobol]].
where data.txt is as for [[#Snobol|Snobol]].


<lang jq>input as $one
<syntaxhighlight lang="jq">input as $one
| "The earthquakes from \(input_filename) with a magnitude greater than 6 are:\n",
| "The earthquakes from \(input_filename) with a magnitude greater than 6 are:\n",
( $one, inputs
( $one, inputs
Line 1,498: Line 1,498:
| $line) catch "WARNING: column 3 is not a recognized number in the line:\n\($line)"
| $line) catch "WARNING: column 3 is not a recognized number in the line:\n\($line)"
end )
end )
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,510: Line 1,510:
=={{header|Julia}}==
=={{header|Julia}}==
Using the example data as a small text file.
Using the example data as a small text file.
<lang julia>using DataFrames, CSV
<syntaxhighlight lang="julia">using DataFrames, CSV


df = CSV.File("kernighansproblem.txt", delim=" ", ignorerepeated=true,
df = CSV.File("kernighansproblem.txt", delim=" ", ignorerepeated=true,
Line 1,517: Line 1,517:


println(filter(row -> row[:Magnitude] > 6, df))
println(filter(row -> row[:Magnitude] > 6, df))
</lang> {{output}} <pre>
</syntaxhighlight> {{output}} <pre>
2×3 DataFrame
2×3 DataFrame
│ Row │ Date │ Location │ Magnitude │
│ Row │ Date │ Location │ Magnitude │
Line 1,527: Line 1,527:


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>arg pop nip len dup
<syntaxhighlight lang="klingphix">arg pop nip len dup


( [get nip]
( [get nip]
Line 1,544: Line 1,544:
$f fclose
$f fclose


"End " input</lang>
"End " input</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// Version 1.2.40
<syntaxhighlight lang="scala">// Version 1.2.40


import java.io.File
import java.io.File
Line 1,557: Line 1,557:
if (it.split(r)[2].toDouble() > 6.0) println(it)
if (it.split(r)[2].toDouble() > 6.0) println(it)
}
}
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 1,570: Line 1,570:
=={{header|Lua}}==
=={{header|Lua}}==
For each line, the Lua pattern "%S+$" is used to capture between the final space character and the end of the line.
For each line, the Lua pattern "%S+$" is used to capture between the final space character and the end of the line.
<lang lua>-- arg[1] is the first argument provided at the command line
<syntaxhighlight lang="lua">-- arg[1] is the first argument provided at the command line
for line in io.lines(arg[1] or "data.txt") do -- use data.txt if arg[1] is nil
for line in io.lines(arg[1] or "data.txt") do -- use data.txt if arg[1] is nil
magnitude = line:match("%S+$")
magnitude = line:match("%S+$")
if tonumber(magnitude) > 6 then print(line) end
if tonumber(magnitude) > 6 then print(line) end
end</lang>
end</syntaxhighlight>
=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Find_Magnitude {
Module Find_Magnitude {
data$={8/27/1883 Krakatoa 8.8
data$={8/27/1883 Krakatoa 8.8
Line 1,599: Line 1,599:




</syntaxhighlight>
</lang>




Line 1,610: Line 1,610:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>Import["data.txt", "Table"] // Select[Last /* GreaterThan[6]]</lang>
<syntaxhighlight lang="mathematica">Import["data.txt", "Table"] // Select[Last /* GreaterThan[6]]</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
Here is one way to do that:
Here is one way to do that:


<lang Nim>import strscans
<syntaxhighlight lang="nim">import strscans


for line in "data.txt".lines:
for line in "data.txt".lines:
Line 1,623: Line 1,623:
if magnitude > 6:
if magnitude > 6:
echo line
echo line
# else wrong line: ignore.</lang>
# else wrong line: ignore.</syntaxhighlight>


Here is another way with less checks:
Here is another way with less checks:


<lang Nim>import strutils
<syntaxhighlight lang="nim">import strutils


for line in "data.txt".lines:
for line in "data.txt".lines:
let magnitude = line.rsplit(' ', 1)[1]
let magnitude = line.rsplit(' ', 1)[1]
if magnitude.parseFloat() > 6:
if magnitude.parseFloat() > 6:
echo line</lang>
echo line</syntaxhighlight>


{{out}}
{{out}}
Line 1,639: Line 1,639:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>perl -n -e '/(\S+)\s*$/ and $1 > 6 and print' data.txt</lang>
<syntaxhighlight lang="perl">perl -n -e '/(\S+)\s*$/ and $1 > 6 and print' data.txt</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">filename</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"data.txt"</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">filename</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"data.txt"</span>
Line 1,656: Line 1,656:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,664: Line 1,664:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>argument tail nip len dup
<syntaxhighlight lang="phixmonti">argument tail nip len dup
if
if
get nip
get nip
Line 1,685: Line 1,685:
endif
endif
endwhile
endwhile
fclose</lang>
fclose</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
Parse using PHP's fscanf().
Parse using PHP's fscanf().
<lang php><?php
<syntaxhighlight lang="php"><?php


// make sure filename was specified on command line
// make sure filename was specified on command line
Line 1,706: Line 1,706:


fclose( $fh );
fclose( $fh );
</syntaxhighlight>
</lang>


Usage: Specify file name on command line. Ex:
Usage: Specify file name on command line. Ex:
Line 1,718: Line 1,718:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(load "@lib/misc.l")
(load "@lib/misc.l")


Line 1,727: Line 1,727:
(prinl (align -10 Date) " " (align -15 Quake) " " Mag)))))
(prinl (align -10 Date) " " (align -15 Quake) " " Mag)))))
(bye)
(bye)
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,737: Line 1,737:
{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
Example command line: <code>swipl kernighans_earthquake.pl earthquake.txt</code>.
Example command line: <code>swipl kernighans_earthquake.pl earthquake.txt</code>.
<lang prolog>:- initialization(main, main).
<syntaxhighlight lang="prolog">:- initialization(main, main).


process_line(Line):-
process_line(Line):-
Line 1,765: Line 1,765:
main(_):-
main(_):-
swritef(Message, 'File argument is missing\n', []),
swritef(Message, 'File argument is missing\n', []),
write(user_error, Message).</lang>
write(user_error, Message).</syntaxhighlight>


{{out}}
{{out}}
Line 1,774: Line 1,774:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>If OpenConsole() And ReadFile(0,"data.txt")
<syntaxhighlight lang="purebasic">If OpenConsole() And ReadFile(0,"data.txt")
PrintN("Those earthquakes with a magnitude > 6.0 are:")
PrintN("Those earthquakes with a magnitude > 6.0 are:")
While Not Eof(0)
While Not Eof(0)
Line 1,784: Line 1,784:
CloseFile(0)
CloseFile(0)
Input()
Input()
EndIf</lang>
EndIf</syntaxhighlight>
{{out}}
{{out}}
<pre>Those earthquakes with a magnitude > 6.0 are:
<pre>Those earthquakes with a magnitude > 6.0 are:
Line 1,792: Line 1,792:
=={{header|Python}}==
=={{header|Python}}==
Typed into a bash shell or similar:
Typed into a bash shell or similar:
<lang python>python -c '
<syntaxhighlight lang="python">python -c '
with open("data.txt") as f:
with open("data.txt") as f:
for ln in f:
for ln in f:
if float(ln.strip().split()[2]) > 6:
if float(ln.strip().split()[2]) > 6:
print(ln.strip())'</lang>
print(ln.strip())'</syntaxhighlight>




Or, if scale permits a file slurp and a parse retained for further processing, we can combine the parse and filter with a concatMap abstraction:
Or, if scale permits a file slurp and a parse retained for further processing, we can combine the parse and filter with a concatMap abstraction:


<lang python>from os.path import expanduser
<syntaxhighlight lang="python">from os.path import expanduser
from functools import (reduce)
from functools import (reduce)
from itertools import (chain)
from itertools import (chain)
Line 1,838: Line 1,838:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[('8/27/1883', 'Krakatoa', '8.8'), ('5/18/1980', 'MountStHelens', '7.6')]</pre>
<pre>[('8/27/1883', 'Krakatoa', '8.8'), ('5/18/1980', 'MountStHelens', '7.6')]</pre>
Line 1,848: Line 1,848:
This is just a file filter, matching lines are printed out.
This is just a file filter, matching lines are printed out.


<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(with-input-from-file "data/large-earthquake.txt"
(with-input-from-file "data/large-earthquake.txt"
Line 1,854: Line 1,854:
(for ((s (in-port read-line))
(for ((s (in-port read-line))
#:when (> (string->number (third (string-split s))) 6))
#:when (> (string->number (third (string-split s))) 6))
(displayln s))))</lang>
(displayln s))))</syntaxhighlight>




Or, defining a list -> list function in terms of '''filter''':
Or, defining a list -> list function in terms of '''filter''':
<lang scheme>#lang racket
<syntaxhighlight lang="scheme">#lang racket


; largeQuakes :: Int -> [String] -> [String]
; largeQuakes :: Int -> [String] -> [String]
Line 1,889: Line 1,889:
; unlines :: [String] -> String
; unlines :: [String] -> String
(define (unlines xs)
(define (unlines xs)
(string-join xs "\n"))</lang>
(string-join xs "\n"))</syntaxhighlight>


{{out}}
{{out}}
Line 1,896: Line 1,896:


To combine filtering with more pre-processing, we can use '''concatMap''' in place of '''filter''':
To combine filtering with more pre-processing, we can use '''concatMap''' in place of '''filter''':
<lang scheme>#lang racket
<syntaxhighlight lang="scheme">#lang racket


(require gregor) ; Date parsing
(require gregor) ; Date parsing
Line 1,935: Line 1,935:
(define (readFile fp)
(define (readFile fp)
(file->string
(file->string
(expand-user-path fp)))</lang>
(expand-user-path fp)))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>(#<date 1883-08-27> "Krakatoa" 8.8)
<pre>(#<date 1883-08-27> "Krakatoa" 8.8)
Line 1,944: Line 1,944:
{{works with|Rakudo|2018.03}}
{{works with|Rakudo|2018.03}}
Pass in a file name, or use default for demonstration purposes.
Pass in a file name, or use default for demonstration purposes.
<lang perl6>$_ = @*ARGS[0] ?? @*ARGS[0].IO !! q:to/END/;
<syntaxhighlight lang="raku" line>$_ = @*ARGS[0] ?? @*ARGS[0].IO !! q:to/END/;
8/27/1883 Krakatoa 8.8
8/27/1883 Krakatoa 8.8
5/18/1980 MountStHelens 7.6
5/18/1980 MountStHelens 7.6
Line 1,950: Line 1,950:
END
END


map { .say if .words[2] > 6 }, .lines;</lang>
map { .say if .words[2] > 6 }, .lines;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,959: Line 1,959:
:::* &nbsp; the number of records that met the qualifying magnitude
:::* &nbsp; the number of records that met the qualifying magnitude
:::* &nbsp; the qualifying magnitude
:::* &nbsp; the qualifying magnitude
<lang rexx>/*REXX program to read a file containing a list of earthquakes: date, site, magnitude.*/
<syntaxhighlight lang="rexx">/*REXX program to read a file containing a list of earthquakes: date, site, magnitude.*/
parse arg iFID mMag . /*obtain optional arguments from the CL*/
parse arg iFID mMag . /*obtain optional arguments from the CL*/
if iFID=='' | iFID=="," then iFID= 'earthquakes.dat' /*Not specified? Then use default*/
if iFID=='' | iFID=="," then iFID= 'earthquakes.dat' /*Not specified? Then use default*/
Line 1,977: Line 1,977:
say
say
if j==0 then say er 'file ' iFID " is empty or not found."
if j==0 then say er 'file ' iFID " is empty or not found."
else say # ' earthquakes listed whose magnitude is ≥ ' mMag</lang>
else say # ' earthquakes listed whose magnitude is ≥ ' mMag</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 1,993: Line 1,993:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Kernighans large earthquake problem
# Project : Kernighans large earthquake problem


Line 2,019: Line 2,019:
ok
ok
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,054: Line 2,054:


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>fn main() -> Result<(), Box<dyn std::error::Error>> {
<syntaxhighlight lang="rust">fn main() -> Result<(), Box<dyn std::error::Error>> {
use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader};


Line 2,072: Line 2,072:


Ok(())
Ok(())
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>scala.io.Source.fromFile("data.txt").getLines
<syntaxhighlight lang="scala">scala.io.Source.fromFile("data.txt").getLines
.map("\\s+".r.split(_))
.map("\\s+".r.split(_))
.filter(_(2).toDouble > 6.0)
.filter(_(2).toDouble > 6.0)
.map(_.mkString("\t"))
.map(_.mkString("\t"))
.foreach(println)</lang>
.foreach(println)</syntaxhighlight>


=={{header|Snobol}}==
=={{header|Snobol}}==
Line 2,085: Line 2,085:
This is hard-coded to read the input from "data.txt".
This is hard-coded to read the input from "data.txt".


<lang snobol> input(.quake, 1,, 'data.txt') :f(err)
<syntaxhighlight lang="snobol"> input(.quake, 1,, 'data.txt') :f(err)
num = '.0123456789'
num = '.0123456789'


Line 2,093: Line 2,093:


err output = 'Error!'
err output = 'Error!'
end</lang>
end</syntaxhighlight>


{{output}}
{{output}}
Line 2,113: Line 2,113:
Expects the program to be started with the path to the data file.
Expects the program to be started with the path to the data file.


<lang Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


guard let path = Array(CommandLine.arguments.dropFirst()).first else {
guard let path = Array(CommandLine.arguments.dropFirst()).first else {
Line 2,131: Line 2,131:


print(line)
print(line)
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Inspired by awk.
Inspired by awk.
<lang tcl>catch {console show} ;## show console when running from tclwish
<syntaxhighlight lang="tcl">catch {console show} ;## show console when running from tclwish
catch {wm withdraw .}
catch {wm withdraw .}


Line 2,151: Line 2,151:
if {$f3 > 6} { puts "$line" }
if {$f3 > 6} { puts "$line" }
}
}
close $fh </lang>
close $fh </syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Imports System.IO
<syntaxhighlight lang="vbnet">Imports System.IO


Module Module1
Module Module1
Line 2,172: Line 2,172:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>import os
<syntaxhighlight lang="vlang">import os
fn main() {
fn main() {
lines := os.read_lines('data.txt')?
lines := os.read_lines('data.txt')?
Line 2,186: Line 2,186:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,198: Line 2,198:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-pattern}}
{{libheader|Wren-pattern}}
<lang ecmascript>import "io" for File
<syntaxhighlight lang="ecmascript">import "io" for File
import "os" for Process
import "os" for Process
import "/pattern" for Pattern
import "/pattern" for Pattern
Line 2,213: Line 2,213:
var mag = Num.fromString(data[2])
var mag = Num.fromString(data[2])
if (mag > 6) System.print(line)
if (mag > 6) System.print(line)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,225: Line 2,225:
=={{header|XPL0}}==
=={{header|XPL0}}==
Usage: quake <data.txt
Usage: quake <data.txt
<lang XPL0>int C;
<syntaxhighlight lang="xpl0">int C;
[loop [OpenO(8); \get line from input file
[loop [OpenO(8); \get line from input file
repeat C:= ChIn(1);
repeat C:= ChIn(1);
Line 2,242: Line 2,242:
];
];
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,260: Line 2,260:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>if peek("argument") then
<syntaxhighlight lang="yabasic">if peek("argument") then
filename$ = peek$("argument")
filename$ = peek$("argument")
else
else
Line 2,274: Line 2,274:
if val(tok$(3)) > 6 print a$
if val(tok$(3)) > 6 print a$
wend
wend
close a</lang>
close a</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Line 2,280: Line 2,280:
is bad practice so I don't do it (written so text is automatically
is bad practice so I don't do it (written so text is automatically
converted to float).
converted to float).
<lang zkl>fcn equake(data,out=Console){
<syntaxhighlight lang="zkl">fcn equake(data,out=Console){
data.pump(out,fcn(line){ 6.0line.split()[-1] },Void.Filter)
data.pump(out,fcn(line){ 6.0line.split()[-1] },Void.Filter)
}</lang>
}</syntaxhighlight>
<lang zkl>equake(Data(Void,
<syntaxhighlight lang="zkl">equake(Data(Void,
#<<<
#<<<
"8/27/1883 Krakatoa 8.8\n"
"8/27/1883 Krakatoa 8.8\n"
Line 2,289: Line 2,289:
"3/13/2009 CostaRica 5.1\n"
"3/13/2009 CostaRica 5.1\n"
#<<<
#<<<
));</lang>
));</syntaxhighlight>
or
or
<lang zkl>equake(File("equake.txt"));</lang>
<syntaxhighlight lang="zkl">equake(File("equake.txt"));</syntaxhighlight>
or
or
<lang zkl>$ zkl --eval 'File.stdin.pump(Console,fcn(line){ 6.0<line.split()[-1] },Void.Filter)' < equake.txt</lang>
<syntaxhighlight lang="zkl">$ zkl --eval 'File.stdin.pump(Console,fcn(line){ 6.0<line.split()[-1] },Void.Filter)' < equake.txt</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>