Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Ensure the translated C code behaves exactly like the original Java snippet.
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.lang.reflect.InvocationTargetException; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class WindowController extends JFrame { public static void main( final String[] args ) { EventQueue.invokeLater( () -> new WindowController() ); } private JComboBox<ControlledWindow> list; private class ControlButton extends JButton { private ControlButton( final String name ) { super( new AbstractAction( name ) { public void actionPerformed( final ActionEvent e ) { try { WindowController.class.getMethod( "do" + name ) .invoke ( WindowController.this ); } catch ( final Exception x ) { x.printStackTrace(); } } } ); } } public WindowController() { super( "Controller" ); final JPanel main = new JPanel(); final JPanel controls = new JPanel(); setLocationByPlatform( true ); setResizable( false ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new BorderLayout( 3, 3 ) ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); add( new JLabel( "Add windows and control them." ), BorderLayout.NORTH ); main.add( list = new JComboBox<>() ); add( main, BorderLayout.CENTER ); controls.setLayout( new GridLayout( 0, 1, 3, 3 ) ); controls.add( new ControlButton( "Add" ) ); controls.add( new ControlButton( "Hide" ) ); controls.add( new ControlButton( "Show" ) ); controls.add( new ControlButton( "Close" ) ); controls.add( new ControlButton( "Maximise" ) ); controls.add( new ControlButton( "Minimise" ) ); controls.add( new ControlButton( "Move" ) ); controls.add( new ControlButton( "Resize" ) ); add( controls, BorderLayout.EAST ); pack(); setVisible( true ); } private static class ControlledWindow extends JFrame { private int num; public ControlledWindow( final int num ) { super( Integer.toString( num ) ); this.num = num; setLocationByPlatform( true ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); add( new JLabel( "I am window " + num + ". Use the controller to control me." ) ); pack(); setVisible( true ); } public String toString() { return "Window " + num; } } public void doAdd() { list.addItem( new ControlledWindow( list.getItemCount () + 1 ) ); pack(); } public void doHide() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( false ); } public void doShow() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( true ); } public void doClose() { final JFrame window = getWindow(); if ( null == window ) { return; } window.dispose(); } public void doMinimise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setState( Frame.ICONIFIED ); } public void doMaximise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setExtendedState( Frame.MAXIMIZED_BOTH ); } public void doMove() { final JFrame window = getWindow(); if ( null == window ) { return; } final int hPos = getInt( "Horizontal position?" ); if ( -1 == hPos ) { return; } final int vPos = getInt( "Vertical position?" ); if ( -1 == vPos ) { return; } window.setLocation ( hPos, vPos ); } public void doResize() { final JFrame window = getWindow(); if ( null == window ) { return; } final int width = getInt( "Width?" ); if ( -1 == width ) { return; } final int height = getInt( "Height?" ); if ( -1 == height ) { return; } window.setBounds ( window.getX(), window.getY(), width, height ); } private JFrame getWindow() { final JFrame window = ( JFrame ) list.getSelectedItem(); if ( null == window ) { JOptionPane.showMessageDialog( this, "Add a window first" ); } return window; } private int getInt(final String prompt) { final String s = JOptionPane.showInputDialog( prompt ); if ( null == s ) { return -1; } try { return Integer.parseInt( s ); } catch ( final NumberFormatException x ) { JOptionPane.showMessageDialog( this, "Not a number" ); return -1; } } }
#include<windows.h> #include<unistd.h> #include<stdio.h> const char g_szClassName[] = "weirdWindow"; LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd[3]; MSG Msg; int i,x=0,y=0; char str[3][100]; int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); char messages[15][180] = {"Welcome to the Rosettacode Window C implementation.", "If you can see two blank windows just behind this message box, you are in luck.", "Let's get started....", "Yes, you will be seeing a lot of me :)", "Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)", "Let's compare the windows for equality.", "Now let's hide Window 1.", "Now let's see Window 1 again.", "Let's close Window 2, bye, bye, Number 2 !", "Let's minimize Window 1.", "Now let's maximize Window 1.", "And finally we come to the fun part, watch Window 1 move !", "Let's double Window 1 in size for all the good work.", "That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )"}; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } for(i=0;i<2;i++){ sprintf(str[i],"Window Number %d",i+1); hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL); if(hwnd[i] == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd[i], nCmdShow); UpdateWindow(hwnd[i]); } for(i=0;i<6;i++){ MessageBox(NULL, messages[i], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); } if(hwnd[0]==hwnd[1]) MessageBox(NULL, "Window 1 and 2 are equal.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); else MessageBox(NULL, "Nope, they are not.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MessageBox(NULL, messages[6], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_HIDE); MessageBox(NULL, messages[7], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_SHOW); MessageBox(NULL, messages[8], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[1], SW_HIDE); MessageBox(NULL, messages[9], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MINIMIZE); MessageBox(NULL, messages[10], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MAXIMIZE); MessageBox(NULL, messages[11], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_RESTORE); while(x!=maxX/2||y!=maxY/2){ if(x<maxX/2) x++; if(y<maxY/2) y++; MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0); sleep(10); } MessageBox(NULL, messages[12], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MoveWindow(hwnd[0],0,0,maxX, maxY,0); MessageBox(NULL, messages[13], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }
Translate this program into C but keep the logic exactly as in Java.
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.lang.reflect.InvocationTargetException; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class WindowController extends JFrame { public static void main( final String[] args ) { EventQueue.invokeLater( () -> new WindowController() ); } private JComboBox<ControlledWindow> list; private class ControlButton extends JButton { private ControlButton( final String name ) { super( new AbstractAction( name ) { public void actionPerformed( final ActionEvent e ) { try { WindowController.class.getMethod( "do" + name ) .invoke ( WindowController.this ); } catch ( final Exception x ) { x.printStackTrace(); } } } ); } } public WindowController() { super( "Controller" ); final JPanel main = new JPanel(); final JPanel controls = new JPanel(); setLocationByPlatform( true ); setResizable( false ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new BorderLayout( 3, 3 ) ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); add( new JLabel( "Add windows and control them." ), BorderLayout.NORTH ); main.add( list = new JComboBox<>() ); add( main, BorderLayout.CENTER ); controls.setLayout( new GridLayout( 0, 1, 3, 3 ) ); controls.add( new ControlButton( "Add" ) ); controls.add( new ControlButton( "Hide" ) ); controls.add( new ControlButton( "Show" ) ); controls.add( new ControlButton( "Close" ) ); controls.add( new ControlButton( "Maximise" ) ); controls.add( new ControlButton( "Minimise" ) ); controls.add( new ControlButton( "Move" ) ); controls.add( new ControlButton( "Resize" ) ); add( controls, BorderLayout.EAST ); pack(); setVisible( true ); } private static class ControlledWindow extends JFrame { private int num; public ControlledWindow( final int num ) { super( Integer.toString( num ) ); this.num = num; setLocationByPlatform( true ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); add( new JLabel( "I am window " + num + ". Use the controller to control me." ) ); pack(); setVisible( true ); } public String toString() { return "Window " + num; } } public void doAdd() { list.addItem( new ControlledWindow( list.getItemCount () + 1 ) ); pack(); } public void doHide() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( false ); } public void doShow() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( true ); } public void doClose() { final JFrame window = getWindow(); if ( null == window ) { return; } window.dispose(); } public void doMinimise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setState( Frame.ICONIFIED ); } public void doMaximise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setExtendedState( Frame.MAXIMIZED_BOTH ); } public void doMove() { final JFrame window = getWindow(); if ( null == window ) { return; } final int hPos = getInt( "Horizontal position?" ); if ( -1 == hPos ) { return; } final int vPos = getInt( "Vertical position?" ); if ( -1 == vPos ) { return; } window.setLocation ( hPos, vPos ); } public void doResize() { final JFrame window = getWindow(); if ( null == window ) { return; } final int width = getInt( "Width?" ); if ( -1 == width ) { return; } final int height = getInt( "Height?" ); if ( -1 == height ) { return; } window.setBounds ( window.getX(), window.getY(), width, height ); } private JFrame getWindow() { final JFrame window = ( JFrame ) list.getSelectedItem(); if ( null == window ) { JOptionPane.showMessageDialog( this, "Add a window first" ); } return window; } private int getInt(final String prompt) { final String s = JOptionPane.showInputDialog( prompt ); if ( null == s ) { return -1; } try { return Integer.parseInt( s ); } catch ( final NumberFormatException x ) { JOptionPane.showMessageDialog( this, "Not a number" ); return -1; } } }
#include<windows.h> #include<unistd.h> #include<stdio.h> const char g_szClassName[] = "weirdWindow"; LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd[3]; MSG Msg; int i,x=0,y=0; char str[3][100]; int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); char messages[15][180] = {"Welcome to the Rosettacode Window C implementation.", "If you can see two blank windows just behind this message box, you are in luck.", "Let's get started....", "Yes, you will be seeing a lot of me :)", "Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)", "Let's compare the windows for equality.", "Now let's hide Window 1.", "Now let's see Window 1 again.", "Let's close Window 2, bye, bye, Number 2 !", "Let's minimize Window 1.", "Now let's maximize Window 1.", "And finally we come to the fun part, watch Window 1 move !", "Let's double Window 1 in size for all the good work.", "That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )"}; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } for(i=0;i<2;i++){ sprintf(str[i],"Window Number %d",i+1); hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL); if(hwnd[i] == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd[i], nCmdShow); UpdateWindow(hwnd[i]); } for(i=0;i<6;i++){ MessageBox(NULL, messages[i], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); } if(hwnd[0]==hwnd[1]) MessageBox(NULL, "Window 1 and 2 are equal.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); else MessageBox(NULL, "Nope, they are not.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MessageBox(NULL, messages[6], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_HIDE); MessageBox(NULL, messages[7], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_SHOW); MessageBox(NULL, messages[8], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[1], SW_HIDE); MessageBox(NULL, messages[9], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MINIMIZE); MessageBox(NULL, messages[10], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MAXIMIZE); MessageBox(NULL, messages[11], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_RESTORE); while(x!=maxX/2||y!=maxY/2){ if(x<maxX/2) x++; if(y<maxY/2) y++; MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0); sleep(10); } MessageBox(NULL, messages[12], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MoveWindow(hwnd[0],0,0,maxX, maxY,0); MessageBox(NULL, messages[13], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }
Maintain the same structure and functionality when rewriting this code in C.
class SpecialPrimes { private static boolean isPrime(int n) { if (n < 2) return false; if (n%2 == 0) return n == 2; if (n%3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return false; d += 4; } return true; } public static void main(String[] args) { System.out.println("Special primes under 1,050:"); System.out.println("Prime1 Prime2 Gap"); int lastSpecial = 3; int lastGap = 1; System.out.printf("%6d %6d %3d\n", 2, 3, lastGap); for (int i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } } }
#include <stdio.h> #include <stdbool.h> bool isPrime(int n) { int d; if (n < 2) return false; if (!(n%2)) return n == 2; if (!(n%3)) return n == 3; d = 5; while (d*d <= n) { if (!(n%d)) return false; d += 2; if (!(n%d)) return false; d += 4; } return true; } int main() { int i, lastSpecial = 3, lastGap = 1; printf("Special primes under 1,050:\n"); printf("Prime1 Prime2 Gap\n"); printf("%6d %6d %3d\n", 2, 3, lastGap); for (i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } }
Port the provided Java code into C while preserving the original functionality.
class SpecialPrimes { private static boolean isPrime(int n) { if (n < 2) return false; if (n%2 == 0) return n == 2; if (n%3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return false; d += 4; } return true; } public static void main(String[] args) { System.out.println("Special primes under 1,050:"); System.out.println("Prime1 Prime2 Gap"); int lastSpecial = 3; int lastGap = 1; System.out.printf("%6d %6d %3d\n", 2, 3, lastGap); for (int i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } } }
#include <stdio.h> #include <stdbool.h> bool isPrime(int n) { int d; if (n < 2) return false; if (!(n%2)) return n == 2; if (!(n%3)) return n == 3; d = 5; while (d*d <= n) { if (!(n%d)) return false; d += 2; if (!(n%d)) return false; d += 4; } return true; } int main() { int i, lastSpecial = 3, lastGap = 1; printf("Special primes under 1,050:\n"); printf("Prime1 Prime2 Gap\n"); printf("%6d %6d %3d\n", 2, 3, lastGap); for (i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } }
Convert this Java block to C, preserving its control flow and logic.
import java.math.BigInteger; public class MayanNumerals { public static void main(String[] args) { for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) { displayMyan(BigInteger.valueOf(base10)); System.out.printf("%n"); } } private static char[] digits = "0123456789ABCDEFGHJK".toCharArray(); private static BigInteger TWENTY = BigInteger.valueOf(20); private static void displayMyan(BigInteger numBase10) { System.out.printf("As base 10: %s%n", numBase10); String numBase20 = ""; while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) { numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20; numBase10 = numBase10.divide(TWENTY); } System.out.printf("As base 20: %s%nAs Mayan:%n", numBase20); displayMyanLine1(numBase20); displayMyanLine2(numBase20); displayMyanLine3(numBase20); displayMyanLine4(numBase20); displayMyanLine5(numBase20); displayMyanLine6(numBase20); } private static char boxUL = Character.toChars(9556)[0]; private static char boxTeeUp = Character.toChars(9574)[0]; private static char boxUR = Character.toChars(9559)[0]; private static char boxHorz = Character.toChars(9552)[0]; private static char boxVert = Character.toChars(9553)[0]; private static char theta = Character.toChars(952)[0]; private static char boxLL = Character.toChars(9562)[0]; private static char boxLR = Character.toChars(9565)[0]; private static char boxTeeLow = Character.toChars(9577)[0]; private static char bullet = Character.toChars(8729)[0]; private static char dash = Character.toChars(9472)[0]; private static void displayMyanLine1(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxUL); } for ( int j = 0 ; j < 4 ; j++ ) { sb.append(boxHorz); } sb.append(i < chars.length-1 ? boxTeeUp : boxUR); } System.out.println(sb.toString()); } private static String getBullet(int count) { StringBuilder sb = new StringBuilder(); switch ( count ) { case 1: sb.append(" " + bullet + " "); break; case 2: sb.append(" " + bullet + bullet + " "); break; case 3: sb.append("" + bullet + bullet + bullet + " "); break; case 4: sb.append("" + bullet + bullet + bullet + bullet); break; default: throw new IllegalArgumentException("Must be 1-4: " + count); } return sb.toString(); } private static void displayMyanLine2(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case 'G': sb.append(getBullet(1)); break; case 'H': sb.append(getBullet(2)); break; case 'J': sb.append(getBullet(3)); break; case 'K': sb.append(getBullet(4)); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static String DASH = getDash(); private static String getDash() { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < 4 ; i++ ) { sb.append(dash); } return sb.toString(); } private static void displayMyanLine3(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case 'B': sb.append(getBullet(1)); break; case 'C': sb.append(getBullet(2)); break; case 'D': sb.append(getBullet(3)); break; case 'E': sb.append(getBullet(4)); break; case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static void displayMyanLine4(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case '6': sb.append(getBullet(1)); break; case '7': sb.append(getBullet(2)); break; case '8': sb.append(getBullet(3)); break; case '9': sb.append(getBullet(4)); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static void displayMyanLine5(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case '0': sb.append(" " + theta + " "); break; case '1': sb.append(getBullet(1)); break; case '2': sb.append(getBullet(2)); break; case '3': sb.append(getBullet(3)); break; case '4': sb.append(getBullet(4)); break; case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static void displayMyanLine6(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxLL); } for ( int j = 0 ; j < 4 ; j++ ) { sb.append(boxHorz); } sb.append(i < chars.length-1 ? boxTeeLow : boxLR); } System.out.println(sb.toString()); } }
#include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #define MAX(x,y) ((x) > (y) ? (x) : (y)) #define MIN(x,y) ((x) < (y) ? (x) : (y)) size_t base20(unsigned int n, uint8_t *out) { uint8_t *start = out; do {*out++ = n % 20;} while (n /= 20); size_t length = out - start; while (out > start) { uint8_t x = *--out; *out = *start; *start++ = x; } return length; } void make_digit(int n, char *place, size_t line_length) { static const char *parts[] = {" "," . "," .. ","... ","....","----"}; int i; for (i=4; i>0; i--, n -= 5) memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4); if (n == -20) place[4 * line_length + 1] = '@'; } char *mayan(unsigned int n) { if (n == 0) return NULL; uint8_t digits[15]; size_t n_digits = base20(n, digits); size_t line_length = n_digits*5 + 2; char *str = malloc(line_length * 6 + 1); if (str == NULL) return NULL; str[line_length * 6] = 0; char *ptr; unsigned int i; for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, "+----", 5); memcpy(ptr-5, "+\n", 2); memcpy(str+5*line_length, str, line_length); for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, "| ", 5); memcpy(ptr-5, "|\n", 2); memcpy(str+2*line_length, str+line_length, line_length); memcpy(str+3*line_length, str+line_length, 2*line_length); for (i=0; i<n_digits; i++) make_digit(digits[i], str+1+5*i, line_length); return str; } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: mayan <number>\n"); return 1; } int i = atoi(argv[1]); if (i <= 0) { fprintf(stderr, "number must be positive\n"); return 1; } char *m = mayan(i); printf("%s",m); free(m); return 0; }
Translate the given Java code snippet into C without altering its behavior.
import java.util.Arrays; import java.util.stream.IntStream; public class RamseysTheorem { static char[][] createMatrix() { String r = "-" + Integer.toBinaryString(53643); int len = r.length(); return IntStream.range(0, len) .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i)) .map(String::toCharArray) .toArray(char[][]::new); } static String ramseyCheck(char[][] mat) { int len = mat.length; char[] connectivity = "------".toCharArray(); for (int a = 0; a < len; a++) { for (int b = 0; b < len; b++) { if (a == b) continue; connectivity[0] = mat[a][b]; for (int c = 0; c < len; c++) { if (a == c || b == c) continue; connectivity[1] = mat[a][c]; connectivity[2] = mat[b][c]; for (int d = 0; d < len; d++) { if (a == d || b == d || c == d) continue; connectivity[3] = mat[a][d]; connectivity[4] = mat[b][d]; connectivity[5] = mat[c][d]; String conn = new String(connectivity); if (conn.indexOf('0') == -1) return String.format("Fail, found wholly connected: " + "%d %d %d %d", a, b, c, d); else if (conn.indexOf('1') == -1) return String.format("Fail, found wholly unconnected: " + "%d %d %d %d", a, b, c, d); } } } } return "Satisfies Ramsey condition."; } public static void main(String[] a) { char[][] mat = createMatrix(); for (char[] s : mat) System.out.println(Arrays.toString(s)); System.out.println(ramseyCheck(mat)); } }
#include <stdio.h> int a[17][17], idx[4]; int find_group(int type, int min_n, int max_n, int depth) { int i, n; if (depth == 4) { printf("totally %sconnected group:", type ? "" : "un"); for (i = 0; i < 4; i++) printf(" %d", idx[i]); putchar('\n'); return 1; } for (i = min_n; i < max_n; i++) { for (n = 0; n < depth; n++) if (a[idx[n]][i] != type) break; if (n == depth) { idx[n] = i; if (find_group(type, 1, max_n, depth + 1)) return 1; } } return 0; } int main() { int i, j, k; const char *mark = "01-"; for (i = 0; i < 17; i++) a[i][i] = 2; for (k = 1; k <= 8; k <<= 1) { for (i = 0; i < 17; i++) { j = (i + k) % 17; a[i][j] = a[j][i] = 1; } } for (i = 0; i < 17; i++) { for (j = 0; j < 17; j++) printf("%c ", mark[a[i][j]]); putchar('\n'); } for (i = 0; i < 17; i++) { idx[0] = i; if (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) { puts("no good"); return 0; } } puts("all good"); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
import java.awt.*; import javax.swing.JFrame; public class Test extends JFrame { public static void main(String[] args) { new Test(); } Test() { Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); System.out.println("Physical screen size: " + screenSize); Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration()); System.out.println("Insets: " + insets); screenSize.width -= (insets.left + insets.right); screenSize.height -= (insets.top + insets.bottom); System.out.println("Max available: " + screenSize); } }
#include<windows.h> #include<stdio.h> int main() { printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN)); return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
public class FourIsMagic { public static void main(String[] args) { for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) { String magic = fourIsMagic(n); System.out.printf("%d = %s%n", n, toSentence(magic)); } } private static final String toSentence(String s) { return s.substring(0,1).toUpperCase() + s.substring(1) + "."; } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String fourIsMagic(long n) { if ( n == 4 ) { return numToString(n) + " is magic"; } String result = numToString(n); return result + " is " + numToString(result.length()) + ", " + fourIsMagic(result.length()); } private static final String numToString(long n) { if ( n < 0 ) { return "negative " + numToString(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? " " + numToString(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToString(n / factor) + " " + label + (n % factor > 0 ? " " + numToString(n % factor ) : ""); } }
#include <stdint.h> #include <stdio.h> #include <glib.h> typedef struct named_number_tag { const char* name; uint64_t number; } named_number; const named_number named_numbers[] = { { "hundred", 100 }, { "thousand", 1000 }, { "million", 1000000 }, { "billion", 1000000000 }, { "trillion", 1000000000000 }, { "quadrillion", 1000000000000000ULL }, { "quintillion", 1000000000000000000ULL } }; const named_number* get_named_number(uint64_t n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_number); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } size_t append_number_name(GString* str, uint64_t n) { static const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; static const char* tens[] = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; size_t len = str->len; if (n < 20) { g_string_append(str, small[n]); } else if (n < 100) { g_string_append(str, tens[n/10 - 2]); if (n % 10 != 0) { g_string_append_c(str, '-'); g_string_append(str, small[n % 10]); } } else { const named_number* num = get_named_number(n); uint64_t p = num->number; append_number_name(str, n/p); g_string_append_c(str, ' '); g_string_append(str, num->name); if (n % p != 0) { g_string_append_c(str, ' '); append_number_name(str, n % p); } } return str->len - len; } GString* magic(uint64_t n) { GString* str = g_string_new(NULL); for (unsigned int i = 0; ; ++i) { size_t count = append_number_name(str, n); if (i == 0) str->str[0] = g_ascii_toupper(str->str[0]); if (n == 4) { g_string_append(str, " is magic."); break; } g_string_append(str, " is "); append_number_name(str, count); g_string_append(str, ", "); n = count; } return str; } void test_magic(uint64_t n) { GString* str = magic(n); printf("%s\n", str->str); g_string_free(str, TRUE); } int main() { test_magic(5); test_magic(13); test_magic(78); test_magic(797); test_magic(2739); test_magic(4000); test_magic(7893); test_magic(93497412); test_magic(2673497412U); test_magic(10344658531277200972ULL); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
public static int findNumOfDec(double x){ String str = String.valueOf(x); if(str.endsWith(".0")) return 0; else return (str.substring(str.indexOf('.')).length() - 1); }
#include <stdio.h> int findNumOfDec(double x) { char buffer[128]; int pos, num; sprintf(buffer, "%.14f", x); pos = 0; num = 0; while (buffer[pos] != 0 && buffer[pos] != '.') { pos++; } if (buffer[pos] != 0) { pos++; while (buffer[pos] != 0) { pos++; } pos--; while (buffer[pos] == '0') { pos--; } while (buffer[pos] != '.') { num++; pos--; } } return num; } void test(double x) { int num = findNumOfDec(x); printf("%f has %d decimals\n", x, num); } int main() { test(12.0); test(12.345); test(12.345555555555); test(12.3450); test(12.34555555555555555555); test(1.2345e+54); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
enum Fruits{ APPLE, BANANA, CHERRY }
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
Rewrite the snippet below in C so it works the same as the original Java code.
enum Fruits{ APPLE, BANANA, CHERRY }
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; static void tree(int br, int n, int l, int inSum, BigInteger cnt) { int sum = inSum; for (int b = br + 1; b <= nBranches; b++) { sum += n; if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return; BigInteger tmp = rooted[n]; if (b == br + 1) { c[br] = tmp.multiply(cnt); } else { c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1))); c[br] = c[br].divide(BigInteger.valueOf(b - br)); } if (l * 2 < sum) unrooted[sum] = unrooted[sum].add(c[br]); if (b < nBranches) rooted[sum] = rooted[sum].add(c[br]); for (int m = n - 1; m > 0; m--) tree(b, m, l, sum, c[br]); } } static void bicenter(int s) { if ((s & 1) == 0) { BigInteger tmp = rooted[s / 2]; tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]); unrooted[s] = unrooted[s].add(tmp.shiftRight(1)); } } public static void main(String[] args) { Arrays.fill(rooted, BigInteger.ZERO); Arrays.fill(unrooted, BigInteger.ZERO); rooted[0] = rooted[1] = BigInteger.ONE; unrooted[0] = unrooted[1] = BigInteger.ONE; for (int n = 1; n <= nMax; n++) { tree(0, n, n, 1, BigInteger.ONE); bicenter(n); System.out.printf("%d: %s%n", n, unrooted[n]); } } }
#include <stdio.h> #define MAX_N 33 #define BRANCH 4 typedef unsigned long long xint; #define FMT "llu" xint rooted[MAX_N] = {1, 1, 0}; xint unrooted[MAX_N] = {1, 1, 0}; xint choose(xint m, xint k) { xint i, r; if (k == 1) return m; for (r = m, i = 1; i < k; i++) r = r * (m + i) / (i + 1); return r; } void tree(xint br, xint n, xint cnt, xint sum, xint l) { xint b, c, m, s; for (b = br + 1; b <= BRANCH; b++) { s = sum + (b - br) * n; if (s >= MAX_N) return; c = choose(rooted[n], b - br) * cnt; if (l * 2 < s) unrooted[s] += c; if (b == BRANCH) return; rooted[s] += c; for (m = n; --m; ) tree(b, m, c, s, l); } } void bicenter(int s) { if (s & 1) return; unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2; } int main() { xint n; for (n = 1; n < MAX_N; n++) { tree(0, n, 1, 1, n); bicenter(n); printf("%"FMT": %"FMT"\n", n, unrooted[n]); } return 0; }
Please provide an equivalent version of this Java code in C.
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; static void tree(int br, int n, int l, int inSum, BigInteger cnt) { int sum = inSum; for (int b = br + 1; b <= nBranches; b++) { sum += n; if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return; BigInteger tmp = rooted[n]; if (b == br + 1) { c[br] = tmp.multiply(cnt); } else { c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1))); c[br] = c[br].divide(BigInteger.valueOf(b - br)); } if (l * 2 < sum) unrooted[sum] = unrooted[sum].add(c[br]); if (b < nBranches) rooted[sum] = rooted[sum].add(c[br]); for (int m = n - 1; m > 0; m--) tree(b, m, l, sum, c[br]); } } static void bicenter(int s) { if ((s & 1) == 0) { BigInteger tmp = rooted[s / 2]; tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]); unrooted[s] = unrooted[s].add(tmp.shiftRight(1)); } } public static void main(String[] args) { Arrays.fill(rooted, BigInteger.ZERO); Arrays.fill(unrooted, BigInteger.ZERO); rooted[0] = rooted[1] = BigInteger.ONE; unrooted[0] = unrooted[1] = BigInteger.ONE; for (int n = 1; n <= nMax; n++) { tree(0, n, n, 1, BigInteger.ONE); bicenter(n); System.out.printf("%d: %s%n", n, unrooted[n]); } } }
#include <stdio.h> #define MAX_N 33 #define BRANCH 4 typedef unsigned long long xint; #define FMT "llu" xint rooted[MAX_N] = {1, 1, 0}; xint unrooted[MAX_N] = {1, 1, 0}; xint choose(xint m, xint k) { xint i, r; if (k == 1) return m; for (r = m, i = 1; i < k; i++) r = r * (m + i) / (i + 1); return r; } void tree(xint br, xint n, xint cnt, xint sum, xint l) { xint b, c, m, s; for (b = br + 1; b <= BRANCH; b++) { s = sum + (b - br) * n; if (s >= MAX_N) return; c = choose(rooted[n], b - br) * cnt; if (l * 2 < s) unrooted[s] += c; if (b == BRANCH) return; rooted[s] += c; for (m = n; --m; ) tree(b, m, c, s, l); } } void bicenter(int s) { if (s & 1) return; unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2; } int main() { xint n; for (n = 1; n < MAX_N; n++) { tree(0, n, 1, 1, n); bicenter(n); printf("%"FMT": %"FMT"\n", n, unrooted[n]); } return 0; }
Produce a functionally identical C code for the snippet given in Java.
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class Pentagram extends JPanel { final double degrees144 = Math.toRadians(144); public Pentagram() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawPentagram(Graphics2D g, int len, int x, int y, Color fill, Color stroke) { double angle = 0; Path2D p = new Path2D.Float(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { int x2 = x + (int) (Math.cos(angle) * len); int y2 = y + (int) (Math.sin(-angle) * len); p.lineTo(x2, y2); x = x2; y = y2; angle -= degrees144; } p.closePath(); g.setColor(fill); g.fill(p); g.setColor(stroke); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0)); drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pentagram"); f.setResizable(false); f.add(new Pentagram(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" }; int stroke=0,fill=0,back=0,i; double centerX = 300,centerY = 300,coreSide,armLength,pentaLength; printf("Enter core pentagon side length : "); scanf("%lf",&coreSide); printf("Enter pentagram arm length : "); scanf("%lf",&armLength); printf("Available colours are :\n"); for(i=0;i<16;i++){ printf("%d. %s\t",i+1,colourNames[i]); if((i+1) % 3 == 0){ printf("\n"); } } while(stroke==fill && fill==back){ printf("\nEnter three diffrenet options for stroke, fill and background : "); scanf("%d%d%d",&stroke,&fill,&back); } pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4); initwindow(2*centerX,2*centerY,"Pentagram"); setcolor(stroke-1); setfillstyle(SOLID_FILL,back-1); bar(0,0,2*centerX,2*centerY); floodfill(centerX,centerY,back-1); setfillstyle(SOLID_FILL,fill-1); for(i=0;i<5;i++){ line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5))); line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1); } floodfill(centerX,centerY,stroke-1); getch(); closegraph(); }
Convert this Java snippet to C and keep its semantics consistent.
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class Pentagram extends JPanel { final double degrees144 = Math.toRadians(144); public Pentagram() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawPentagram(Graphics2D g, int len, int x, int y, Color fill, Color stroke) { double angle = 0; Path2D p = new Path2D.Float(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { int x2 = x + (int) (Math.cos(angle) * len); int y2 = y + (int) (Math.sin(-angle) * len); p.lineTo(x2, y2); x = x2; y = y2; angle -= degrees144; } p.closePath(); g.setColor(fill); g.fill(p); g.setColor(stroke); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0)); drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pentagram"); f.setResizable(false); f.add(new Pentagram(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" }; int stroke=0,fill=0,back=0,i; double centerX = 300,centerY = 300,coreSide,armLength,pentaLength; printf("Enter core pentagon side length : "); scanf("%lf",&coreSide); printf("Enter pentagram arm length : "); scanf("%lf",&armLength); printf("Available colours are :\n"); for(i=0;i<16;i++){ printf("%d. %s\t",i+1,colourNames[i]); if((i+1) % 3 == 0){ printf("\n"); } } while(stroke==fill && fill==back){ printf("\nEnter three diffrenet options for stroke, fill and background : "); scanf("%d%d%d",&stroke,&fill,&back); } pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4); initwindow(2*centerX,2*centerY,"Pentagram"); setcolor(stroke-1); setfillstyle(SOLID_FILL,back-1); bar(0,0,2*centerX,2*centerY); floodfill(centerX,centerY,back-1); setfillstyle(SOLID_FILL,fill-1); for(i=0;i<5;i++){ line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5))); line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1); } floodfill(centerX,centerY,stroke-1); getch(); closegraph(); }
Port the following code from Java to C with equivalent syntax and logic.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParseIPAddress { public static void main(String[] args) { String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"}; System.out.printf("%-40s %-32s %s%n", "Test Case", "Hex Address", "Port"); for ( String ip : tests ) { try { String [] parsed = parseIP(ip); System.out.printf("%-40s %-32s %s%n", ip, parsed[0], parsed[1]); } catch (IllegalArgumentException e) { System.out.printf("%-40s Invalid address: %s%n", ip, e.getMessage()); } } } private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$"); private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$"); private static String ipv6Pattern; static { ipv6Pattern = "^\\[{0,1}"; for ( int i = 1 ; i <= 7 ; i ++ ) { ipv6Pattern += "([0-9a-f]+):"; } ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$"; } private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern); private static String[] parseIP(String ip) { String hex = ""; String port = ""; Matcher ipv4Matcher = IPV4_PAT.matcher(ip); if ( ipv4Matcher.matches() ) { for ( int i = 1 ; i <= 4 ; i++ ) { hex += toHex4(ipv4Matcher.group(i)); } if ( ipv4Matcher.group(5) != null ) { port = ipv4Matcher.group(5); } return new String[] {hex, port}; } Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip); if ( ipv6DoubleColonMatcher.matches() ) { String p1 = ipv6DoubleColonMatcher.group(1); if ( p1.isEmpty() ) { p1 = "0"; } String p2 = ipv6DoubleColonMatcher.group(2); if ( p2.isEmpty() ) { p2 = "0"; } ip = p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2; if ( ipv6DoubleColonMatcher.group(3) != null ) { ip = "[" + ip + "]:" + ipv6DoubleColonMatcher.group(3); } } Matcher ipv6Matcher = IPV6_PAT.matcher(ip); if ( ipv6Matcher.matches() ) { for ( int i = 1 ; i <= 8 ; i++ ) { hex += String.format("%4s", toHex6(ipv6Matcher.group(i))).replace(" ", "0"); } if ( ipv6Matcher.group(9) != null ) { port = ipv6Matcher.group(9); } return new String[] {hex, port}; } throw new IllegalArgumentException("ERROR 103: Unknown address: " + ip); } private static int numCount(String s) { return s.split(":").length; } private static String getZero(int count) { StringBuilder sb = new StringBuilder(); sb.append(":"); while ( count > 0 ) { sb.append("0:"); count--; } return sb.toString(); } private static String toHex4(String s) { int val = Integer.parseInt(s); if ( val < 0 || val > 255 ) { throw new IllegalArgumentException("ERROR 101: Invalid value : " + s); } return String.format("%2s", Integer.toHexString(val)).replace(" ", "0"); } private static String toHex6(String s) { int val = Integer.parseInt(s, 16); if ( val < 0 || val > 65536 ) { throw new IllegalArgumentException("ERROR 102: Invalid hex value : " + s); } return s; } }
#include <string.h> #include <memory.h> static unsigned int _parseDecimal ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' ) { nVal *= 10; nVal += chNow - '0'; ++*pchCursor; } return nVal; } static unsigned int _parseHex ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor & 0x5f, (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || (chNow >= 'A' && chNow <= 'F') ) { unsigned char nybbleValue; chNow -= 0x10; nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow ); nVal <<= 4; nVal += nybbleValue; ++*pchCursor; } return nVal; } int ParseIPv4OrIPv6 ( const char** ppszText, unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) { unsigned char* abyAddrLocal; unsigned char abyDummyAddr[16]; const char* pchColon = strchr ( *ppszText, ':' ); const char* pchDot = strchr ( *ppszText, '.' ); const char* pchOpenBracket = strchr ( *ppszText, '[' ); const char* pchCloseBracket = NULL; int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot || ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) ); if ( bIsIPv6local ) { pchCloseBracket = strchr ( *ppszText, ']' ); if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket || pchCloseBracket < pchOpenBracket ) ) return 0; } else { if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) ) return 0; } if ( NULL != pbIsIPv6 ) *pbIsIPv6 = bIsIPv6local; abyAddrLocal = abyAddr; if ( NULL == abyAddrLocal ) abyAddrLocal = abyDummyAddr; if ( ! bIsIPv6local ) { unsigned char* pbyAddrCursor = abyAddrLocal; unsigned int nVal; const char* pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; if ( ':' == **ppszText && NULL != pnPort ) { unsigned short usPortNetwork; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); *pnPort = usPortNetwork; return 1; } else { if ( NULL != pnPort ) *pnPort = 0; return 1; } } else { unsigned char* pbyAddrCursor; unsigned char* pbyZerosLoc; int bIPv4Detected; int nIdx; if ( NULL != pchOpenBracket ) *ppszText = pchOpenBracket + 1; pbyAddrCursor = abyAddrLocal; pbyZerosLoc = NULL; bIPv4Detected = 0; for ( nIdx = 0; nIdx < 8; ++nIdx ) { const char* pszTextBefore = *ppszText; unsigned nVal =_parseHex ( ppszText ); if ( pszTextBefore == *ppszText ) { if ( NULL != pbyZerosLoc ) { if ( pbyZerosLoc == pbyAddrCursor ) { --nIdx; break; } return 0; } if ( ':' != **ppszText ) return 0; if ( 0 == nIdx ) { ++(*ppszText); if ( ':' != **ppszText ) return 0; } pbyZerosLoc = pbyAddrCursor; ++(*ppszText); } else { if ( '.' == **ppszText ) { const char* pszTextlocal = pszTextBefore; unsigned char abyAddrlocal[16]; int bIsIPv6local; int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local ); *ppszText = pszTextlocal; if ( ! bParseResultlocal || bIsIPv6local ) return 0; *(pbyAddrCursor++) = abyAddrlocal[0]; *(pbyAddrCursor++) = abyAddrlocal[1]; *(pbyAddrCursor++) = abyAddrlocal[2]; *(pbyAddrCursor++) = abyAddrlocal[3]; ++nIdx; bIPv4Detected = 1; break; } if ( nVal > 65535 ) return 0; *(pbyAddrCursor++) = nVal >> 8; *(pbyAddrCursor++) = nVal & 0xff; if ( ':' == **ppszText ) { ++(*ppszText); } else { break; } } } if ( NULL != pbyZerosLoc ) { int nHead = (int)( pbyZerosLoc - abyAddrLocal ); int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); int nZeros = 16 - nTail - nHead; memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail ); memset ( pbyZerosLoc, 0, nZeros ); } if ( bIPv4Detected ) { static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff }; if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) ) return 0; } if ( NULL != pchOpenBracket ) { if ( ']' != **ppszText ) return 0; ++(*ppszText); } if ( ':' == **ppszText && NULL != pnPort ) { const char* pszTextBefore; unsigned int nVal; unsigned short usPortNetwork; ++(*ppszText); pszTextBefore = *ppszText; pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); *pnPort = usPortNetwork; return 1; } else { if ( NULL != pnPort ) *pnPort = 0; return 1; } } } int ParseIPv4OrIPv6_2 ( const char* pszText, unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) { const char* pszTextLocal = pszText; return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6); }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
package hu.pj.alg; import hu.pj.obj.Item; import java.text.*; public class UnboundedKnapsack { protected Item [] items = { new Item("panacea", 3000, 0.3, 0.025), new Item("ichor" , 1800, 0.2, 0.015), new Item("gold" , 2500, 2.0, 0.002) }; protected final int n = items.length; protected Item sack = new Item("sack" , 0, 25.0, 0.250); protected Item best = new Item("best" , 0, 0.0, 0.000); protected int [] maxIt = new int [n]; protected int [] iIt = new int [n]; protected int [] bestAm = new int [n]; public UnboundedKnapsack() { for (int i = 0; i < n; i++) { maxIt [i] = Math.min( (int)(sack.getWeight() / items[i].getWeight()), (int)(sack.getVolume() / items[i].getVolume()) ); } calcWithRecursion(0); NumberFormat nf = NumberFormat.getInstance(); System.out.println("Maximum value achievable is: " + best.getValue()); System.out.print("This is achieved by carrying (one solution): "); for (int i = 0; i < n; i++) { System.out.print(bestAm[i] + " " + items[i].getName() + ", "); } System.out.println(); System.out.println("The weight to carry is: " + nf.format(best.getWeight()) + " and the volume used is: " + nf.format(best.getVolume()) ); } public void calcWithRecursion(int item) { for (int i = 0; i <= maxIt[item]; i++) { iIt[item] = i; if (item < n-1) { calcWithRecursion(item+1); } else { int currVal = 0; double currWei = 0.0; double currVol = 0.0; for (int j = 0; j < n; j++) { currVal += iIt[j] * items[j].getValue(); currWei += iIt[j] * items[j].getWeight(); currVol += iIt[j] * items[j].getVolume(); } if (currVal > best.getValue() && currWei <= sack.getWeight() && currVol <= sack.getVolume() ) { best.setValue (currVal); best.setWeight(currWei); best.setVolume(currVol); for (int j = 0; j < n; j++) bestAm[j] = iIt[j]; } } } } public static void main(String[] args) { new UnboundedKnapsack(); } }
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; double value; double weight; double volume; } item_t; item_t items[] = { {"panacea", 3000.0, 0.3, 0.025}, {"ichor", 1800.0, 0.2, 0.015}, {"gold", 2500.0, 2.0, 0.002}, }; int n = sizeof (items) / sizeof (item_t); int *count; int *best; double best_value; void knapsack (int i, double value, double weight, double volume) { int j, m1, m2, m; if (i == n) { if (value > best_value) { best_value = value; for (j = 0; j < n; j++) { best[j] = count[j]; } } return; } m1 = weight / items[i].weight; m2 = volume / items[i].volume; m = m1 < m2 ? m1 : m2; for (count[i] = m; count[i] >= 0; count[i]--) { knapsack( i + 1, value + count[i] * items[i].value, weight - count[i] * items[i].weight, volume - count[i] * items[i].volume ); } } int main () { count = malloc(n * sizeof (int)); best = malloc(n * sizeof (int)); best_value = 0; knapsack(0, 0.0, 25.0, 0.25); int i; for (i = 0; i < n; i++) { printf("%d %s\n", best[i], items[i].name); } printf("best value: %.0f\n", best_value); free(count); free(best); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class RTextonyms { private static final Map<Character, Character> mapping; private int total, elements, textonyms, max_found; private String filename, mappingResult; private Vector<String> max_strings; private Map<String, Vector<String>> values; static { mapping = new HashMap<Character, Character>(); mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2'); mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3'); mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4'); mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5'); mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6'); mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7'); mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8'); mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9'); } public RTextonyms(String filename) { this.filename = filename; this.total = this.elements = this.textonyms = this.max_found = 0; this.values = new HashMap<String, Vector<String>>(); this.max_strings = new Vector<String>(); return; } public void add(String line) { String mapping = ""; total++; if (!get_mapping(line)) { return; } mapping = mappingResult; if (values.get(mapping) == null) { values.put(mapping, new Vector<String>()); } int num_strings; num_strings = values.get(mapping).size(); textonyms += num_strings == 1 ? 1 : 0; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.add(mapping); max_found = num_strings; } else if (num_strings == max_found) { max_strings.add(mapping); } values.get(mapping).add(line); return; } public void results() { System.out.printf("Read %,d words from %s%n%n", total, filename); System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements, filename); System.out.printf("They require %,d digit combinations to represent them.%n", values.size()); System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms); System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1); for (String key : max_strings) { System.out.printf("%16s maps to: %s%n", key, values.get(key).toString()); } System.out.println(); return; } public void match(String key) { Vector<String> match; match = values.get(key); if (match == null) { System.out.printf("Key %s not found%n", key); } else { System.out.printf("Key %s matches: %s%n", key, match.toString()); } return; } private boolean get_mapping(String line) { mappingResult = line; StringBuilder mappingBuilder = new StringBuilder(); for (char cc : line.toCharArray()) { if (Character.isAlphabetic(cc)) { mappingBuilder.append(mapping.get(Character.toUpperCase(cc))); } else if (Character.isDigit(cc)) { mappingBuilder.append(cc); } else { return false; } } mappingResult = mappingBuilder.toString(); return true; } public static void main(String[] args) { String filename; if (args.length > 0) { filename = args[0]; } else { filename = "./unixdict.txt"; } RTextonyms tc; tc = new RTextonyms(filename); Path fp = Paths.get(filename); try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) { while (fs.hasNextLine()) { tc.add(fs.nextLine()); } } catch (IOException ex) { ex.printStackTrace(); } List<String> numbers = Arrays.asList( "001", "228", "27484247", "7244967473642", "." ); tc.results(); for (String number : numbers) { if (number.equals(".")) { System.out.println(); } else { tc.match(number); } } return; } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> char text_char(char c) { switch (c) { case 'a': case 'b': case 'c': return '2'; case 'd': case 'e': case 'f': return '3'; case 'g': case 'h': case 'i': return '4'; case 'j': case 'k': case 'l': return '5'; case 'm': case 'n': case 'o': return '6'; case 'p': case 'q': case 'r': case 's': return '7'; case 't': case 'u': case 'v': return '8'; case 'w': case 'x': case 'y': case 'z': return '9'; default: return 0; } } bool text_string(const GString* word, GString* text) { g_string_set_size(text, word->len); for (size_t i = 0; i < word->len; ++i) { char c = text_char(g_ascii_tolower(word->str[i])); if (c == 0) return false; text->str[i] = c; } return true; } typedef struct textonym_tag { const char* text; size_t length; GPtrArray* words; } textonym_t; int compare_by_text_length(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->length > t2->length) return -1; if (t1->length < t2->length) return 1; return strcmp(t1->text, t2->text); } int compare_by_word_count(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->words->len > t2->words->len) return -1; if (t1->words->len < t2->words->len) return 1; return strcmp(t1->text, t2->text); } void print_words(GPtrArray* words) { for (guint i = 0, n = words->len; i < n; ++i) { if (i > 0) printf(", "); printf("%s", g_ptr_array_index(words, i)); } printf("\n"); } void print_top_words(GArray* textonyms, guint top) { for (guint i = 0; i < top; ++i) { const textonym_t* t = &g_array_index(textonyms, textonym_t, i); printf("%s = ", t->text); print_words(t->words); } } void free_strings(gpointer ptr) { g_ptr_array_free(ptr, TRUE); } bool find_textonyms(const char* filename, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(filename, "r", &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return false; } GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, free_strings); GString* word = g_string_sized_new(64); GString* text = g_string_sized_new(64); guint count = 0; gsize term_pos; while (g_io_channel_read_line_string(channel, word, &term_pos, &error) == G_IO_STATUS_NORMAL) { g_string_truncate(word, term_pos); if (!text_string(word, text)) continue; GPtrArray* words = g_hash_table_lookup(ht, text->str); if (words == NULL) { words = g_ptr_array_new_full(1, g_free); g_hash_table_insert(ht, g_strdup(text->str), words); } g_ptr_array_add(words, g_strdup(word->str)); ++count; } g_io_channel_unref(channel); g_string_free(word, TRUE); g_string_free(text, TRUE); if (error != NULL) { g_propagate_error(error_ptr, error); g_hash_table_destroy(ht); return false; } GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t)); GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, ht); while (g_hash_table_iter_next(&iter, &key, &value)) { GPtrArray* v = value; if (v->len > 1) { textonym_t textonym; textonym.text = key; textonym.length = strlen(key); textonym.words = v; g_array_append_val(words, textonym); } } printf("There are %u words in '%s' which can be represented by the digit key mapping.\n", count, filename); guint size = g_hash_table_size(ht); printf("They require %u digit combinations to represent them.\n", size); guint textonyms = words->len; printf("%u digit combinations represent Textonyms.\n", textonyms); guint top = 5; if (textonyms < top) top = textonyms; printf("\nTop %u by number of words:\n", top); g_array_sort(words, compare_by_word_count); print_top_words(words, top); printf("\nTop %u by length:\n", top); g_array_sort(words, compare_by_text_length); print_top_words(words, top); g_array_free(words, TRUE); g_hash_table_destroy(ht); return true; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s word-list\n", argv[0]); return EXIT_FAILURE; } GError* error = NULL; if (!find_textonyms(argv[1], &error)) { if (error != NULL) { fprintf(stderr, "%s: %s\n", argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } return EXIT_SUCCESS; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.io.*; import java.util.*; public class Teacup { public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java Teacup dictionary"); System.exit(1); } try { findTeacupWords(loadDictionary(args[0])); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static Set<String> loadDictionary(String fileName) throws IOException { Set<String> words = new TreeSet<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String word; while ((word = reader.readLine()) != null) words.add(word); return words; } } private static void findTeacupWords(Set<String> words) { List<String> teacupWords = new ArrayList<>(); Set<String> found = new HashSet<>(); for (String word : words) { int len = word.length(); if (len < 3 || found.contains(word)) continue; teacupWords.clear(); teacupWords.add(word); char[] chars = word.toCharArray(); for (int i = 0; i < len - 1; ++i) { String rotated = new String(rotate(chars)); if (rotated.equals(word) || !words.contains(rotated)) break; teacupWords.add(rotated); } if (teacupWords.size() == len) { found.addAll(teacupWords); System.out.print(word); for (int i = 1; i < len; ++i) System.out.print(" " + teacupWords.get(i)); System.out.println(); } } } private static char[] rotate(char[] ch) { char c = ch[0]; System.arraycopy(ch, 1, ch, 0, ch.length - 1); ch[ch.length - 1] = c; return ch; } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> int string_compare(gconstpointer p1, gconstpointer p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } GPtrArray* load_dictionary(const char* file, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(file, "r", &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return NULL; } GPtrArray* dict = g_ptr_array_new_full(1024, g_free); GString* line = g_string_sized_new(64); gsize term_pos; while (g_io_channel_read_line_string(channel, line, &term_pos, &error) == G_IO_STATUS_NORMAL) { char* word = g_strdup(line->str); word[term_pos] = '\0'; g_ptr_array_add(dict, word); } g_string_free(line, TRUE); g_io_channel_unref(channel); if (error != NULL) { g_propagate_error(error_ptr, error); g_ptr_array_free(dict, TRUE); return NULL; } g_ptr_array_sort(dict, string_compare); return dict; } void rotate(char* str, size_t len) { char c = str[0]; memmove(str, str + 1, len - 1); str[len - 1] = c; } char* dictionary_search(const GPtrArray* dictionary, const char* word) { char** result = bsearch(&word, dictionary->pdata, dictionary->len, sizeof(char*), string_compare); return result != NULL ? *result : NULL; } void find_teacup_words(GPtrArray* dictionary) { GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal); GPtrArray* teacup_words = g_ptr_array_new(); GString* temp = g_string_sized_new(8); for (size_t i = 0, n = dictionary->len; i < n; ++i) { char* word = g_ptr_array_index(dictionary, i); size_t len = strlen(word); if (len < 3 || g_hash_table_contains(found, word)) continue; g_ptr_array_set_size(teacup_words, 0); g_string_assign(temp, word); bool is_teacup_word = true; for (size_t i = 0; i < len - 1; ++i) { rotate(temp->str, len); char* w = dictionary_search(dictionary, temp->str); if (w == NULL) { is_teacup_word = false; break; } if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL)) g_ptr_array_add(teacup_words, w); } if (is_teacup_word && teacup_words->len > 0) { printf("%s", word); g_hash_table_add(found, word); for (size_t i = 0; i < teacup_words->len; ++i) { char* teacup_word = g_ptr_array_index(teacup_words, i); printf(" %s", teacup_word); g_hash_table_add(found, teacup_word); } printf("\n"); } } g_string_free(temp, TRUE); g_ptr_array_free(teacup_words, TRUE); g_hash_table_destroy(found); } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s dictionary\n", argv[0]); return EXIT_FAILURE; } GError* error = NULL; GPtrArray* dictionary = load_dictionary(argv[1], &error); if (dictionary == NULL) { if (error != NULL) { fprintf(stderr, "Cannot load dictionary file '%s': %s\n", argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } find_teacup_words(dictionary); g_ptr_array_free(dictionary, TRUE); return EXIT_SUCCESS; }
Write a version of this Java function in C with identical behavior.
import java.io.*; import java.util.*; public class Teacup { public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java Teacup dictionary"); System.exit(1); } try { findTeacupWords(loadDictionary(args[0])); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static Set<String> loadDictionary(String fileName) throws IOException { Set<String> words = new TreeSet<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String word; while ((word = reader.readLine()) != null) words.add(word); return words; } } private static void findTeacupWords(Set<String> words) { List<String> teacupWords = new ArrayList<>(); Set<String> found = new HashSet<>(); for (String word : words) { int len = word.length(); if (len < 3 || found.contains(word)) continue; teacupWords.clear(); teacupWords.add(word); char[] chars = word.toCharArray(); for (int i = 0; i < len - 1; ++i) { String rotated = new String(rotate(chars)); if (rotated.equals(word) || !words.contains(rotated)) break; teacupWords.add(rotated); } if (teacupWords.size() == len) { found.addAll(teacupWords); System.out.print(word); for (int i = 1; i < len; ++i) System.out.print(" " + teacupWords.get(i)); System.out.println(); } } } private static char[] rotate(char[] ch) { char c = ch[0]; System.arraycopy(ch, 1, ch, 0, ch.length - 1); ch[ch.length - 1] = c; return ch; } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> int string_compare(gconstpointer p1, gconstpointer p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } GPtrArray* load_dictionary(const char* file, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(file, "r", &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return NULL; } GPtrArray* dict = g_ptr_array_new_full(1024, g_free); GString* line = g_string_sized_new(64); gsize term_pos; while (g_io_channel_read_line_string(channel, line, &term_pos, &error) == G_IO_STATUS_NORMAL) { char* word = g_strdup(line->str); word[term_pos] = '\0'; g_ptr_array_add(dict, word); } g_string_free(line, TRUE); g_io_channel_unref(channel); if (error != NULL) { g_propagate_error(error_ptr, error); g_ptr_array_free(dict, TRUE); return NULL; } g_ptr_array_sort(dict, string_compare); return dict; } void rotate(char* str, size_t len) { char c = str[0]; memmove(str, str + 1, len - 1); str[len - 1] = c; } char* dictionary_search(const GPtrArray* dictionary, const char* word) { char** result = bsearch(&word, dictionary->pdata, dictionary->len, sizeof(char*), string_compare); return result != NULL ? *result : NULL; } void find_teacup_words(GPtrArray* dictionary) { GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal); GPtrArray* teacup_words = g_ptr_array_new(); GString* temp = g_string_sized_new(8); for (size_t i = 0, n = dictionary->len; i < n; ++i) { char* word = g_ptr_array_index(dictionary, i); size_t len = strlen(word); if (len < 3 || g_hash_table_contains(found, word)) continue; g_ptr_array_set_size(teacup_words, 0); g_string_assign(temp, word); bool is_teacup_word = true; for (size_t i = 0; i < len - 1; ++i) { rotate(temp->str, len); char* w = dictionary_search(dictionary, temp->str); if (w == NULL) { is_teacup_word = false; break; } if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL)) g_ptr_array_add(teacup_words, w); } if (is_teacup_word && teacup_words->len > 0) { printf("%s", word); g_hash_table_add(found, word); for (size_t i = 0; i < teacup_words->len; ++i) { char* teacup_word = g_ptr_array_index(teacup_words, i); printf(" %s", teacup_word); g_hash_table_add(found, teacup_word); } printf("\n"); } } g_string_free(temp, TRUE); g_ptr_array_free(teacup_words, TRUE); g_hash_table_destroy(found); } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s dictionary\n", argv[0]); return EXIT_FAILURE; } GError* error = NULL; GPtrArray* dictionary = load_dictionary(argv[1], &error); if (dictionary == NULL) { if (error != NULL) { fprintf(stderr, "Cannot load dictionary file '%s': %s\n", argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } find_teacup_words(dictionary); g_ptr_array_free(dictionary, TRUE); return EXIT_SUCCESS; }
Keep all operations the same but rewrite the snippet in C.
public class NivenNumberGaps { public static void main(String[] args) { long prevGap = 0; long prevN = 1; long index = 0; System.out.println("Gap Gap Index Starting Niven"); for ( long n = 2 ; n < 20_000_000_000l ; n++ ) { if ( isNiven(n) ) { index++; long curGap = n - prevN; if ( curGap > prevGap ) { System.out.printf("%3d  %,13d  %,15d%n", curGap, index, prevN); prevGap = curGap; } prevN = n; } } } public static boolean isNiven(long n) { long sum = 0; long nSave = n; while ( n > 0 ) { sum += n % 10; n /= 10; } return nSave % sum == 0; } }
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1) return false; return n % d == 0; } int main() { setlocale(LC_ALL, ""); uint64_t previous = 1, gap = 0, sum = 0; int niven_index = 0, gap_index = 1; printf("Gap index Gap Niven index Niven number\n"); for (uint64_t niven = 1; gap_index <= 32; ++niven) { sum = digit_sum(niven, sum); if (divisible(niven, sum)) { if (niven > previous + gap) { gap = niven - previous; printf("%'9d %'4llu %'14d %'15llu\n", gap_index++, gap, niven_index, previous); } previous = niven; ++niven_index; } } return 0; }
Write the same code in C as shown below in Java.
import java.util.Objects; public class PrintDebugStatement { private static void printDebug(String message) { Objects.requireNonNull(message); RuntimeException exception = new RuntimeException(); StackTraceElement[] stackTrace = exception.getStackTrace(); StackTraceElement stackTraceElement = stackTrace[1]; String fileName = stackTraceElement.getFileName(); String className = stackTraceElement.getClassName(); String methodName = stackTraceElement.getMethodName(); int lineNumber = stackTraceElement.getLineNumber(); System.out.printf("[DEBUG][%s %s.%s#%d] %s\n", fileName, className, methodName, lineNumber, message); } private static void blah() { printDebug("Made It!"); } public static void main(String[] args) { printDebug("Hello world."); blah(); Runnable oops = () -> printDebug("oops"); oops.run(); } }
#include <stdio.h> #define DEBUG_INT(x) printf( #x " at line %d\nresult: %d\n\n", __LINE__, x) int add(int x, int y) { int result = x + y; DEBUG_INT(x); DEBUG_INT(y); DEBUG_INT(result); DEBUG_INT(result+1); return result; } int main() { add(2, 7); return 0; }
Port the provided Java code into C while preserving the original functionality.
import java.awt.*; import java.awt.geom.Path2D; import static java.lang.Math.pow; import java.util.Hashtable; import javax.swing.*; import javax.swing.event.*; public class SuperEllipse extends JPanel implements ChangeListener { private double exp = 2.5; public SuperEllipse() { setPreferredSize(new Dimension(650, 650)); setBackground(Color.white); setFont(new Font("Serif", Font.PLAIN, 18)); } void drawGrid(Graphics2D g) { g.setStroke(new BasicStroke(2)); g.setColor(new Color(0xEEEEEE)); int w = getWidth(); int h = getHeight(); int spacing = 25; for (int i = 0; i < w / spacing; i++) { g.drawLine(0, i * spacing, w, i * spacing); g.drawLine(i * spacing, 0, i * spacing, w); } g.drawLine(0, h - 1, w, h - 1); g.setColor(new Color(0xAAAAAA)); g.drawLine(0, w / 2, w, w / 2); g.drawLine(w / 2, 0, w / 2, w); } void drawLegend(Graphics2D g) { g.setColor(Color.black); g.setFont(getFont()); g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45); g.drawString("a = b = 200", getWidth() - 150, 75); } void drawEllipse(Graphics2D g) { final int a = 200; double[] points = new double[a + 1]; Path2D p = new Path2D.Double(); p.moveTo(a, 0); for (int x = a; x >= 0; x--) { points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); p.lineTo(x, -points[x]); } for (int x = 0; x <= a; x++) p.lineTo(x, points[x]); for (int x = a; x >= 0; x--) p.lineTo(-x, points[x]); for (int x = 0; x <= a; x++) p.lineTo(-x, -points[x]); g.translate(getWidth() / 2, getHeight() / 2); g.setStroke(new BasicStroke(2)); g.setColor(new Color(0x25B0C4DE, true)); g.fill(p); g.setColor(new Color(0xB0C4DE)); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); drawGrid(g); drawLegend(g); drawEllipse(g); } @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); exp = source.getValue() / 2.0; repaint(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Super Ellipse"); f.setResizable(false); SuperEllipse panel = new SuperEllipse(); f.add(panel, BorderLayout.CENTER); JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5); exponent.addChangeListener(panel); exponent.setMajorTickSpacing(1); exponent.setPaintLabels(true); exponent.setBackground(Color.white); exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); Hashtable<Integer, JLabel> labelTable = new Hashtable<>(); for (int i = 1; i < 10; i++) labelTable.put(i, new JLabel(String.valueOf(i * 0.5))); exponent.setLabelTable(labelTable); f.add(exponent, BorderLayout.SOUTH); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ double a,b,n,i,incr = 0.0001; printf("Enter major and minor axes of the SuperEllipse : "); scanf("%lf%lf",&a,&b); printf("Enter n : "); scanf("%lf",&n); initwindow(500,500,"Superellipse"); for(i=0;i<2*pi;i+=incr){ putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15); } printf("Done. %lf",i); getch(); closegraph(); }
Produce a functionally identical C code for the snippet given in Java.
import java.math.BigInteger; import java.util.*; class RankPermutation { public static BigInteger getRank(int[] permutation) { int n = permutation.length; BitSet usedDigits = new BitSet(); BigInteger rank = BigInteger.ZERO; for (int i = 0; i < n; i++) { rank = rank.multiply(BigInteger.valueOf(n - i)); int digit = 0; int v = -1; while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i]) digit++; usedDigits.set(v); rank = rank.add(BigInteger.valueOf(digit)); } return rank; } public static int[] getPermutation(int n, BigInteger rank) { int[] digits = new int[n]; for (int digit = 2; digit <= n; digit++) { BigInteger divisor = BigInteger.valueOf(digit); digits[n - digit] = rank.mod(divisor).intValue(); if (digit < n) rank = rank.divide(divisor); } BitSet usedDigits = new BitSet(); int[] permutation = new int[n]; for (int i = 0; i < n; i++) { int v = usedDigits.nextClearBit(0); for (int j = 0; j < digits[i]; j++) v = usedDigits.nextClearBit(v + 1); permutation[i] = v; usedDigits.set(v); } return permutation; } public static void main(String[] args) { for (int i = 0; i < 6; i++) { int[] permutation = getPermutation(3, BigInteger.valueOf(i)); System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } Random rnd = new Random(); for (int n : new int[] { 12, 144 }) { BigInteger factorial = BigInteger.ONE; for (int i = 2; i <= n; i++) factorial = factorial.multiply(BigInteger.valueOf(i)); System.out.println("n = " + n); for (int i = 0; i < 5; i++) { BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd); rank = rank.mod(factorial); int[] permutation = getPermutation(n, rank); System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } } } }
#include <stdio.h> #include <stdlib.h> #define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0) void _mr_unrank1(int rank, int n, int *vec) { int t, q, r; if (n < 1) return; q = rank / n; r = rank % n; SWAP(vec[r], vec[n-1]); _mr_unrank1(q, n-1, vec); } int _mr_rank1(int n, int *vec, int *inv) { int s, t; if (n < 2) return 0; s = vec[n-1]; SWAP(vec[n-1], vec[inv[n-1]]); SWAP(inv[s], inv[n-1]); return s + n * _mr_rank1(n-1, vec, inv); } void get_permutation(int rank, int n, int *vec) { int i; for (i = 0; i < n; ++i) vec[i] = i; _mr_unrank1(rank, n, vec); } int get_rank(int n, int *vec) { int i, r, *v, *inv; v = malloc(n * sizeof(int)); inv = malloc(n * sizeof(int)); for (i = 0; i < n; ++i) { v[i] = vec[i]; inv[vec[i]] = i; } r = _mr_rank1(n, v, inv); free(inv); free(v); return r; } int main(int argc, char *argv[]) { int i, r, tv[4]; for (r = 0; r < 24; ++r) { printf("%3d: ", r); get_permutation(r, 4, tv); for (i = 0; i < 4; ++i) { if (0 == i) printf("[ "); else printf(", "); printf("%d", tv[i]); } printf(" ] = %d\n", get_rank(4, tv)); } }
Convert this Java snippet to C and keep its semantics consistent.
import java.math.BigInteger; import java.util.*; class RankPermutation { public static BigInteger getRank(int[] permutation) { int n = permutation.length; BitSet usedDigits = new BitSet(); BigInteger rank = BigInteger.ZERO; for (int i = 0; i < n; i++) { rank = rank.multiply(BigInteger.valueOf(n - i)); int digit = 0; int v = -1; while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i]) digit++; usedDigits.set(v); rank = rank.add(BigInteger.valueOf(digit)); } return rank; } public static int[] getPermutation(int n, BigInteger rank) { int[] digits = new int[n]; for (int digit = 2; digit <= n; digit++) { BigInteger divisor = BigInteger.valueOf(digit); digits[n - digit] = rank.mod(divisor).intValue(); if (digit < n) rank = rank.divide(divisor); } BitSet usedDigits = new BitSet(); int[] permutation = new int[n]; for (int i = 0; i < n; i++) { int v = usedDigits.nextClearBit(0); for (int j = 0; j < digits[i]; j++) v = usedDigits.nextClearBit(v + 1); permutation[i] = v; usedDigits.set(v); } return permutation; } public static void main(String[] args) { for (int i = 0; i < 6; i++) { int[] permutation = getPermutation(3, BigInteger.valueOf(i)); System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } Random rnd = new Random(); for (int n : new int[] { 12, 144 }) { BigInteger factorial = BigInteger.ONE; for (int i = 2; i <= n; i++) factorial = factorial.multiply(BigInteger.valueOf(i)); System.out.println("n = " + n); for (int i = 0; i < 5; i++) { BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd); rank = rank.mod(factorial); int[] permutation = getPermutation(n, rank); System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } } } }
#include <stdio.h> #include <stdlib.h> #define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0) void _mr_unrank1(int rank, int n, int *vec) { int t, q, r; if (n < 1) return; q = rank / n; r = rank % n; SWAP(vec[r], vec[n-1]); _mr_unrank1(q, n-1, vec); } int _mr_rank1(int n, int *vec, int *inv) { int s, t; if (n < 2) return 0; s = vec[n-1]; SWAP(vec[n-1], vec[inv[n-1]]); SWAP(inv[s], inv[n-1]); return s + n * _mr_rank1(n-1, vec, inv); } void get_permutation(int rank, int n, int *vec) { int i; for (i = 0; i < n; ++i) vec[i] = i; _mr_unrank1(rank, n, vec); } int get_rank(int n, int *vec) { int i, r, *v, *inv; v = malloc(n * sizeof(int)); inv = malloc(n * sizeof(int)); for (i = 0; i < n; ++i) { v[i] = vec[i]; inv[vec[i]] = i; } r = _mr_rank1(n, v, inv); free(inv); free(v); return r; } int main(int argc, char *argv[]) { int i, r, tv[4]; for (r = 0; r < 24; ++r) { printf("%3d: ", r); get_permutation(r, 4, tv); for (i = 0; i < 4; ++i) { if (0 == i) printf("[ "); else printf(", "); printf("%d", tv[i]); } printf(" ] = %d\n", get_rank(4, tv)); } }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
public class RangeExtraction { public static void main(String[] args) { int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39}; int len = arr.length; int idx = 0, idx2 = 0; while (idx < len) { while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1); if (idx2 - idx > 2) { System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]); idx = idx2; } else { for (; idx < idx2; idx++) System.out.printf("%s,", arr[idx]); } } } }
#include <stdio.h> #include <stdlib.h> size_t rprint(char *s, int *x, int len) { #define sep (a > s ? "," : "") #define ol (s ? 100 : 0) int i, j; char *a = s; for (i = j = 0; i < len; i = ++j) { for (; j < len - 1 && x[j + 1] == x[j] + 1; j++); if (i + 1 < j) a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]); else while (i <= j) a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]); } return a - s; #undef sep #undef ol } int main() { int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1); rprint(s, x, sizeof(x) / sizeof(int)); printf("%s\n", s); return 0; }
Produce a functionally identical C code for the snippet given in Java.
public class TypeDetection { private static void showType(Object a) { if (a instanceof Integer) { System.out.printf("'%s' is an integer\n", a); } else if (a instanceof Double) { System.out.printf("'%s' is a double\n", a); } else if (a instanceof Character) { System.out.printf("'%s' is a character\n", a); } else { System.out.printf("'%s' is some other type\n", a); } } public static void main(String[] args) { showType(5); showType(7.5); showType('d'); showType(true); } }
#include<stdio.h> #include<ctype.h> void typeDetector(char* str){ if(isalnum(str[0])!=0) printf("\n%c is alphanumeric",str[0]); if(isalpha(str[0])!=0) printf("\n%c is alphabetic",str[0]); if(iscntrl(str[0])!=0) printf("\n%c is a control character",str[0]); if(isdigit(str[0])!=0) printf("\n%c is a digit",str[0]); if(isprint(str[0])!=0) printf("\n%c is printable",str[0]); if(ispunct(str[0])!=0) printf("\n%c is a punctuation character",str[0]); if(isxdigit(str[0])!=0) printf("\n%c is a hexadecimal digit",str[0]); } int main(int argC, char* argV[]) { int i; if(argC==1) printf("Usage : %s <followed by ASCII characters>"); else{ for(i=1;i<argC;i++) typeDetector(argV[i]); } return 0; }
Generate an equivalent C version of this Java code.
import java.nio.file.*; import static java.util.Arrays.stream; public class MaxPathSum { public static void main(String[] args) throws Exception { int[][] data = Files.lines(Paths.get("triangle.txt")) .map(s -> stream(s.trim().split("\\s+")) .mapToInt(Integer::parseInt) .toArray()) .toArray(int[][]::new); for (int r = data.length - 1; r > 0; r--) for (int c = 0; c < data[r].length - 1; c++) data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]); System.out.println(data[0][0]); } }
#include <stdio.h> #include <math.h> #define max(x,y) ((x) > (y) ? (x) : (y)) int tri[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; int main(void) { const int len = sizeof(tri) / sizeof(tri[0]); const int base = (sqrt(8*len + 1) - 1) / 2; int step = base - 1; int stepc = 0; int i; for (i = len - base - 1; i >= 0; --i) { tri[i] += max(tri[i + step], tri[i + step + 1]); if (++stepc == step) { step--; stepc = 0; } } printf("%d\n", tri[0]); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "}; final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}}; final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6}, {0, 4, 6}}}; static List<Point> toWhite = new ArrayList<>(); static char[][] grid; public static void main(String[] args) { grid = new char[image.length][]; for (int r = 0; r < image.length; r++) grid[r] = image[r].toCharArray(); thinImage(); } static void thinImage() { boolean firstStep = false; boolean hasChanged; do { hasChanged = false; firstStep = !firstStep; for (int r = 1; r < grid.length - 1; r++) { for (int c = 1; c < grid[0].length - 1; c++) { if (grid[r][c] != '#') continue; int nn = numNeighbors(r, c); if (nn < 2 || nn > 6) continue; if (numTransitions(r, c) != 1) continue; if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) continue; toWhite.add(new Point(c, r)); hasChanged = true; } } for (Point p : toWhite) grid[p.y][p.x] = ' '; toWhite.clear(); } while (firstStep || hasChanged); printResult(); } static int numNeighbors(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') count++; return count; } static int numTransitions(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') { if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') count++; } return count; } static boolean atLeastOneIsWhite(int r, int c, int step) { int count = 0; int[][] group = nbrGroups[step]; for (int i = 0; i < 2; i++) for (int j = 0; j < group[i].length; j++) { int[] nbr = nbrs[group[i][j]]; if (grid[r + nbr[1]][c + nbr[0]] == ' ') { count++; break; } } return count > 1; } static void printResult() { for (char[] row : grid) System.out.println(row); } }
#include<stdlib.h> #include<stdio.h> char** imageMatrix; char blankPixel,imagePixel; typedef struct{ int row,col; }pixel; int getBlackNeighbours(int row,int col){ int i,j,sum = 0; for(i=-1;i<=1;i++){ for(j=-1;j<=1;j++){ if(i!=0 || j!=0) sum+= (imageMatrix[row+i][col+j]==imagePixel); } } return sum; } int getBWTransitions(int row,int col){ return ((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel) +(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel) +(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel) +(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel) +(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel) +(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel) +(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel) +(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel)); } int zhangSuenTest1(int row,int col){ int neighbours = getBlackNeighbours(row,col); return ((neighbours>=2 && neighbours<=6) && (getBWTransitions(row,col)==1) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) && (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel)); } int zhangSuenTest2(int row,int col){ int neighbours = getBlackNeighbours(row,col); return ((neighbours>=2 && neighbours<=6) && (getBWTransitions(row,col)==1) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel)); } void zhangSuen(char* inputFile, char* outputFile){ int startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed; pixel* markers; FILE* inputP = fopen(inputFile,"r"); fscanf(inputP,"%d%d",&rows,&cols); fscanf(inputP,"%d%d",&blankPixel,&imagePixel); blankPixel<=9?blankPixel+='0':blankPixel; imagePixel<=9?imagePixel+='0':imagePixel; printf("\nPrinting original image :\n"); imageMatrix = (char**)malloc(rows*sizeof(char*)); for(i=0;i<rows;i++){ imageMatrix[i] = (char*)malloc((cols+1)*sizeof(char)); fscanf(inputP,"%s\n",imageMatrix[i]); printf("\n%s",imageMatrix[i]); } fclose(inputP); endRow = rows-2; endCol = cols-2; do{ markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel)); count = 0; for(i=startRow;i<=endRow;i++){ for(j=startCol;j<=endCol;j++){ if(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){ markers[count].row = i; markers[count].col = j; count++; } } } processed = (count>0); for(i=0;i<count;i++){ imageMatrix[markers[i].row][markers[i].col] = blankPixel; } free(markers); markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel)); count = 0; for(i=startRow;i<=endRow;i++){ for(j=startCol;j<=endCol;j++){ if(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){ markers[count].row = i; markers[count].col = j; count++; } } } if(processed==0) processed = (count>0); for(i=0;i<count;i++){ imageMatrix[markers[i].row][markers[i].col] = blankPixel; } free(markers); }while(processed==1); FILE* outputP = fopen(outputFile,"w"); printf("\n\n\nPrinting image after applying Zhang Suen Thinning Algorithm : \n\n\n"); for(i=0;i<rows;i++){ for(j=0;j<cols;j++){ printf("%c",imageMatrix[i][j]); fprintf(outputP,"%c",imageMatrix[i][j]); } printf("\n"); fprintf(outputP,"\n"); } fclose(outputP); printf("\nImage also written to : %s",outputFile); } int main() { char inputFile[100],outputFile[100]; printf("Enter full path of input image file : "); scanf("%s",inputFile); printf("Enter full path of output image file : "); scanf("%s",outputFile); zhangSuen(inputFile,outputFile); return 0; }
Generate an equivalent C version of this Java code.
public class VariableDeclarationReset { public static void main(String[] args) { int[] s = {1, 2, 2, 3, 4, 4, 5}; for (int i = 0; i < s.length; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) System.out.println(i); prev = curr; } int gprev = 0; for (int i = 0; i < s.length; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) System.out.println(i); gprev = curr; } } }
#include <stdio.h> int main() { int i, gprev = 0; int s[7] = {1, 2, 2, 3, 4, 4, 5}; for (i = 0; i < 7; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) printf("%d\n", i); prev = curr; } for (i = 0; i < 7; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) printf("%d\n", i); gprev = curr; } return 0; }
Generate an equivalent C version of this Java code.
public class FirstLastBits { public static int mssb(int x) { return Integer.highestOneBit(x); } public static long mssb(long x) { return Long.highestOneBit(x); } public static int mssb_idx(int x) { return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x); } public static int mssb_idx(long x) { return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); } public static int mssb_idx(BigInteger x) { return x.bitLength() - 1; } public static int lssb(int x) { return Integer.lowestOneBit(x); } public static long lssb(long x) { return Long.lowestOneBit(x); } public static int lssb_idx(int x) { return Integer.numberOfTrailingZeros(x); } public static int lssb_idx(long x) { return Long.numberOfTrailingZeros(x); } public static int lssb_idx(BigInteger x) { return x.getLowestSetBit(); } public static void main(String[] args) { System.out.println("int:"); int n1 = 1; for (int i = 0; ; i++, n1 *= 42) { System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n1, n1, mssb(n1), mssb_idx(n1), lssb(n1), lssb_idx(n1)); if (n1 >= Integer.MAX_VALUE / 42) break; } System.out.println(); System.out.println("long:"); long n2 = 1; for (int i = 0; ; i++, n2 *= 42) { System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n", i, n2, n2, mssb(n2), mssb_idx(n2), lssb(n2), lssb_idx(n2)); if (n2 >= Long.MAX_VALUE / 42) break; } System.out.println(); System.out.println("BigInteger:"); BigInteger n3 = BigInteger.ONE; BigInteger k = BigInteger.valueOf(1302); for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) { System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n", i, n3, n3, mssb_idx(n3), lssb_idx(n3)); } } }
#include <stdio.h> #include <stdint.h> uint32_t msb32(uint32_t n) { uint32_t b = 1; if (!n) return 0; #define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } int msb32_idx(uint32_t n) { int b = 0; if (!n) return -1; #define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } #define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) ) inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); } int main() { int32_t n; int i; for (i = 0, n = 1; ; i++, n *= 42) { printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n, n, msb32(n), msb32_idx(n), lsb32(n), lsb32_idx(n)); if (n >= INT32_MAX / 42) break; } return 0; }
Translate this program into C but keep the logic exactly as in Java.
public class FirstLastBits { public static int mssb(int x) { return Integer.highestOneBit(x); } public static long mssb(long x) { return Long.highestOneBit(x); } public static int mssb_idx(int x) { return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x); } public static int mssb_idx(long x) { return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); } public static int mssb_idx(BigInteger x) { return x.bitLength() - 1; } public static int lssb(int x) { return Integer.lowestOneBit(x); } public static long lssb(long x) { return Long.lowestOneBit(x); } public static int lssb_idx(int x) { return Integer.numberOfTrailingZeros(x); } public static int lssb_idx(long x) { return Long.numberOfTrailingZeros(x); } public static int lssb_idx(BigInteger x) { return x.getLowestSetBit(); } public static void main(String[] args) { System.out.println("int:"); int n1 = 1; for (int i = 0; ; i++, n1 *= 42) { System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n1, n1, mssb(n1), mssb_idx(n1), lssb(n1), lssb_idx(n1)); if (n1 >= Integer.MAX_VALUE / 42) break; } System.out.println(); System.out.println("long:"); long n2 = 1; for (int i = 0; ; i++, n2 *= 42) { System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n", i, n2, n2, mssb(n2), mssb_idx(n2), lssb(n2), lssb_idx(n2)); if (n2 >= Long.MAX_VALUE / 42) break; } System.out.println(); System.out.println("BigInteger:"); BigInteger n3 = BigInteger.ONE; BigInteger k = BigInteger.valueOf(1302); for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) { System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n", i, n3, n3, mssb_idx(n3), lssb_idx(n3)); } } }
#include <stdio.h> #include <stdint.h> uint32_t msb32(uint32_t n) { uint32_t b = 1; if (!n) return 0; #define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } int msb32_idx(uint32_t n) { int b = 0; if (!n) return -1; #define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } #define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) ) inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); } int main() { int32_t n; int i; for (i = 0, n = 1; ; i++, n *= 42) { printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n, n, msb32(n), msb32_idx(n), lsb32(n), lsb32_idx(n)); if (n >= INT32_MAX / 42) break; } return 0; }
Generate a C translation of this Java snippet without changing its computational steps.
public class EqualRisesFalls { public static void main(String[] args) { final int limit1 = 200; final int limit2 = 10000000; System.out.printf("The first %d numbers in the sequence are:\n", limit1); int n = 0; for (int count = 0; count < limit2; ) { if (equalRisesAndFalls(++n)) { ++count; if (count <= limit1) System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' '); } } System.out.printf("\nThe %dth number in the sequence is %d.\n", limit2, n); } private static boolean equalRisesAndFalls(int n) { int total = 0; for (int previousDigit = -1; n > 0; n /= 10) { int digit = n % 10; if (previousDigit > digit) ++total; else if (previousDigit >= 0 && previousDigit < digit) --total; previousDigit = digit; } return total == 0; } }
#include <stdio.h> int riseEqFall(int num) { int rdigit = num % 10; int netHeight = 0; while (num /= 10) { netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit); rdigit = num % 10; } return netHeight == 0; } int nextNum() { static int num = 0; do {num++;} while (!riseEqFall(num)); return num; } int main(void) { int total, num; printf("The first 200 numbers are: \n"); for (total = 0; total < 200; total++) printf("%d ", nextNum()); printf("\n\nThe 10,000,000th number is: "); for (; total < 10000000; total++) num = nextNum(); printf("%d\n", num); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
int l = 300; void setup() { size(400, 400); background(0, 0, 255); stroke(255); translate(width/2.0, height/2.0); translate(-l/2.0, l*sqrt(3)/6.0); for (int i = 1; i <= 3; i++) { kcurve(0, l); rotate(radians(120)); translate(-l, 0); } } void kcurve(float x1, float x2) { float s = (x2-x1)/3; if (s < 5) { pushMatrix(); translate(x1, 0); line(0, 0, s, 0); line(2*s, 0, 3*s, 0); translate(s, 0); rotate(radians(60)); line(0, 0, s, 0); translate(s, 0); rotate(radians(-120)); line(0, 0, s, 0); popMatrix(); return; } pushMatrix(); translate(x1, 0); kcurve(0, s); kcurve(2*s, 3*s); translate(s, 0); rotate(radians(60)); kcurve(0, s); translate(s, 0); rotate(radians(-120)); kcurve(0, s); popMatrix(); }
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #define pi M_PI typedef struct{ double x,y; }point; void kochCurve(point p1,point p2,int times){ point p3,p4,p5; double theta = pi/3; if(times>0){ p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3}; p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3}; p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)}; kochCurve(p1,p3,times-1); kochCurve(p3,p4,times-1); kochCurve(p4,p5,times-1); kochCurve(p5,p2,times-1); } else{ line(p1.x,p1.y,p2.x,p2.y); } } int main(int argC, char** argV) { int w,h,r; point p1,p2; if(argC!=4){ printf("Usage : %s <window width> <window height> <recursion level>",argV[0]); } else{ w = atoi(argV[1]); h = atoi(argV[2]); r = atoi(argV[3]); initwindow(w,h,"Koch Curve"); p1 = (point){10,h-10}; p2 = (point){w-10,h-10}; kochCurve(p1,p2,r); getch(); closegraph(); } return 0; }
Write the same code in C as shown below in Java.
size(640,480); stroke(#ffff00); ellipse(random(640),random(480),1,1);
#include<graphics.h> #include<stdlib.h> #include<time.h> int main() { srand(time(NULL)); initwindow(640,480,"Yellow Random Pixel"); putpixel(rand()%640,rand()%480,YELLOW); getch(); return 0; }
Keep all operations the same but rewrite the snippet in C.
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class DrawAPixel extends JFrame{ public DrawAPixel() { super("Red Pixel"); setSize(320, 240); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } @Override public void paint(Graphics g) { g.setColor(new Color(255, 0, 0)); g.drawRect(100, 100, 1, 1); } public static void main(String[] args) { new DrawAPixel(); } }
#include<graphics.h> int main() { initwindow(320,240,"Red Pixel"); putpixel(100,100,RED); getch(); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Java version.
import java.io.*; import java.util.*; public class NeighbourWords { public static void main(String[] args) { try { int minLength = 9; List<String> words = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) { String line; while ((line = reader.readLine()) != null) { if (line.length() >= minLength) words.add(line); } } Collections.sort(words); String previousWord = null; int count = 0; for (int i = 0, n = words.size(); i + minLength <= n; ++i) { StringBuilder sb = new StringBuilder(minLength); for (int j = 0; j < minLength; ++j) sb.append(words.get(i + j).charAt(j)); String word = sb.toString(); if (word.equals(previousWord)) continue; if (Collections.binarySearch(words, word) >= 0) System.out.printf("%2d. %s\n", ++count, word); previousWord = word; } } catch (Exception e) { e.printStackTrace(); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_SIZE 80 #define MIN_LENGTH 9 #define WORD_SIZE (MIN_LENGTH + 1) void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } int word_compare(const void* p1, const void* p2) { return memcmp(p1, p2, WORD_SIZE); } int main(int argc, char** argv) { const char* filename = argc < 2 ? "unixdict.txt" : argv[1]; FILE* in = fopen(filename, "r"); if (!in) { perror(filename); return EXIT_FAILURE; } char line[MAX_WORD_SIZE]; size_t size = 0, capacity = 1024; char* words = xmalloc(WORD_SIZE * capacity); while (fgets(line, sizeof(line), in)) { size_t len = strlen(line) - 1; if (len < MIN_LENGTH) continue; line[len] = '\0'; if (size == capacity) { capacity *= 2; words = xrealloc(words, WORD_SIZE * capacity); } memcpy(&words[size * WORD_SIZE], line, WORD_SIZE); ++size; } fclose(in); qsort(words, size, WORD_SIZE, word_compare); int count = 0; char prev_word[WORD_SIZE] = { 0 }; for (size_t i = 0; i + MIN_LENGTH <= size; ++i) { char word[WORD_SIZE] = { 0 }; for (size_t j = 0; j < MIN_LENGTH; ++j) word[j] = words[(i + j) * WORD_SIZE + j]; if (word_compare(word, prev_word) == 0) continue; if (bsearch(word, words, size, WORD_SIZE, word_compare)) printf("%2d. %s\n", ++count, word); memcpy(prev_word, word, WORD_SIZE); } free(words); return EXIT_SUCCESS; }
Keep all operations the same but rewrite the snippet in C.
public class GateLogic { public interface OneInputGate { boolean eval(boolean input); } public interface TwoInputGate { boolean eval(boolean input1, boolean input2); } public interface MultiGate { boolean[] eval(boolean... inputs); } public static OneInputGate NOT = new OneInputGate() { public boolean eval(boolean input) { return !input; } }; public static TwoInputGate AND = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 && input2; } }; public static TwoInputGate OR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 || input2; } }; public static TwoInputGate XOR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return OR.eval( AND.eval(input1, NOT.eval(input2)), AND.eval(NOT.eval(input1), input2) ); } }; public static MultiGate HALF_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 2) throw new IllegalArgumentException(); return new boolean[] { XOR.eval(inputs[0], inputs[1]), AND.eval(inputs[0], inputs[1]) }; } }; public static MultiGate FULL_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 3) throw new IllegalArgumentException(); boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]); boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]); return new boolean[] { haOutputs2[0], OR.eval(haOutputs1[1], haOutputs2[1]) }; } }; public static MultiGate buildAdder(final int numBits) { return new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != (numBits << 1)) throw new IllegalArgumentException(); boolean[] outputs = new boolean[numBits + 1]; boolean[] faInputs = new boolean[3]; boolean[] faOutputs = null; for (int i = 0; i < numBits; i++) { faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; faInputs[1] = inputs[i]; faInputs[2] = inputs[numBits + i]; faOutputs = FULL_ADDER.eval(faInputs); outputs[i] = faOutputs[0]; } if (faOutputs != null) outputs[numBits] = faOutputs[1]; return outputs; } }; } public static void main(String[] args) { int numBits = Integer.parseInt(args[0]); int firstNum = Integer.parseInt(args[1]); int secondNum = Integer.parseInt(args[2]); int maxNum = 1 << numBits; if ((firstNum < 0) || (firstNum >= maxNum)) { System.out.println("First number is out of range"); return; } if ((secondNum < 0) || (secondNum >= maxNum)) { System.out.println("Second number is out of range"); return; } MultiGate multiBitAdder = buildAdder(numBits); boolean[] inputs = new boolean[numBits << 1]; String firstNumDisplay = ""; String secondNumDisplay = ""; for (int i = 0; i < numBits; i++) { boolean firstBit = ((firstNum >>> i) & 1) == 1; boolean secondBit = ((secondNum >>> i) & 1) == 1; inputs[i] = firstBit; inputs[numBits + i] = secondBit; firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay; secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay; } boolean[] outputs = multiBitAdder.eval(inputs); int outputNum = 0; String outputNumDisplay = ""; String outputCarryDisplay = null; for (int i = numBits; i >= 0; i--) { outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0); if (i == numBits) outputCarryDisplay = outputs[i] ? "1" : "0"; else outputNumDisplay += (outputs[i] ? "1" : "0"); } System.out.println("numBits=" + numBits); System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")"); return; } }
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
public class GateLogic { public interface OneInputGate { boolean eval(boolean input); } public interface TwoInputGate { boolean eval(boolean input1, boolean input2); } public interface MultiGate { boolean[] eval(boolean... inputs); } public static OneInputGate NOT = new OneInputGate() { public boolean eval(boolean input) { return !input; } }; public static TwoInputGate AND = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 && input2; } }; public static TwoInputGate OR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 || input2; } }; public static TwoInputGate XOR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return OR.eval( AND.eval(input1, NOT.eval(input2)), AND.eval(NOT.eval(input1), input2) ); } }; public static MultiGate HALF_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 2) throw new IllegalArgumentException(); return new boolean[] { XOR.eval(inputs[0], inputs[1]), AND.eval(inputs[0], inputs[1]) }; } }; public static MultiGate FULL_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 3) throw new IllegalArgumentException(); boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]); boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]); return new boolean[] { haOutputs2[0], OR.eval(haOutputs1[1], haOutputs2[1]) }; } }; public static MultiGate buildAdder(final int numBits) { return new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != (numBits << 1)) throw new IllegalArgumentException(); boolean[] outputs = new boolean[numBits + 1]; boolean[] faInputs = new boolean[3]; boolean[] faOutputs = null; for (int i = 0; i < numBits; i++) { faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; faInputs[1] = inputs[i]; faInputs[2] = inputs[numBits + i]; faOutputs = FULL_ADDER.eval(faInputs); outputs[i] = faOutputs[0]; } if (faOutputs != null) outputs[numBits] = faOutputs[1]; return outputs; } }; } public static void main(String[] args) { int numBits = Integer.parseInt(args[0]); int firstNum = Integer.parseInt(args[1]); int secondNum = Integer.parseInt(args[2]); int maxNum = 1 << numBits; if ((firstNum < 0) || (firstNum >= maxNum)) { System.out.println("First number is out of range"); return; } if ((secondNum < 0) || (secondNum >= maxNum)) { System.out.println("Second number is out of range"); return; } MultiGate multiBitAdder = buildAdder(numBits); boolean[] inputs = new boolean[numBits << 1]; String firstNumDisplay = ""; String secondNumDisplay = ""; for (int i = 0; i < numBits; i++) { boolean firstBit = ((firstNum >>> i) & 1) == 1; boolean secondBit = ((secondNum >>> i) & 1) == 1; inputs[i] = firstBit; inputs[numBits + i] = secondBit; firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay; secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay; } boolean[] outputs = multiBitAdder.eval(inputs); int outputNum = 0; String outputNumDisplay = ""; String outputCarryDisplay = null; for (int i = numBits; i >= 0; i--) { outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0); if (i == numBits) outputCarryDisplay = outputs[i] ? "1" : "0"; else outputNumDisplay += (outputs[i] ? "1" : "0"); } System.out.println("numBits=" + numBits); System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")"); return; } }
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
public class MagicSquareSinglyEven { public static void main(String[] args) { int n = 6; for (int[] row : magicSquareSinglyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int n) { if (n < 3 || n % 2 == 0) throw new IllegalArgumentException("base must be odd and > 2"); int value = 0; int gridSize = n * n; int c = n / 2, r = 0; int[][] result = new int[n][n]; while (++value <= gridSize) { result[r][c] = value; if (r == 0) { if (c == n - 1) { r++; } else { r = n - 1; c++; } } else if (c == n - 1) { r--; c = 0; } else if (result[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } return result; } static int[][] magicSquareSinglyEven(final int n) { if (n < 6 || (n - 2) % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4 plus 2"); int size = n * n; int halfN = n / 2; int subSquareSize = size / 4; int[][] subSquare = magicSquareOdd(halfN); int[] quadrantFactors = {0, 2, 3, 1}; int[][] result = new int[n][n]; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { int quadrant = (r / halfN) * 2 + (c / halfN); result[r][c] = subSquare[r % halfN][c % halfN]; result[r][c] += quadrantFactors[quadrant] * subSquareSize; } } int nColsLeft = halfN / 2; int nColsRight = nColsLeft - 1; for (int r = 0; r < halfN; r++) for (int c = 0; c < n; c++) { if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { if (c == 0 && r == nColsLeft) continue; int tmp = result[r][c]; result[r][c] = result[r + halfN][c]; result[r + halfN][c] = tmp; } } return result; } }
#include<stdlib.h> #include<ctype.h> #include<stdio.h> int** oddMagicSquare(int n) { if (n < 3 || n % 2 == 0) return NULL; int value = 0; int squareSize = n * n; int c = n / 2, r = 0,i; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); while (++value <= squareSize) { result[r][c] = value; if (r == 0) { if (c == n - 1) { r++; } else { r = n - 1; c++; } } else if (c == n - 1) { r--; c = 0; } else if (result[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } return result; } int** singlyEvenMagicSquare(int n) { if (n < 6 || (n - 2) % 4 != 0) return NULL; int size = n * n; int halfN = n / 2; int subGridSize = size / 4, i; int** subGrid = oddMagicSquare(halfN); int gridFactors[] = {0, 2, 3, 1}; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { int grid = (r / halfN) * 2 + (c / halfN); result[r][c] = subGrid[r % halfN][c % halfN]; result[r][c] += gridFactors[grid] * subGridSize; } } int nColsLeft = halfN / 2; int nColsRight = nColsLeft - 1; for (int r = 0; r < halfN; r++) for (int c = 0; c < n; c++) { if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { if (c == 0 && r == nColsLeft) continue; int tmp = result[r][c]; result[r][c] = result[r + halfN][c]; result[r + halfN][c] = tmp; } } return result; } int numDigits(int n){ int count = 1; while(n>=10){ n /= 10; count++; } return count; } void printMagicSquare(int** square,int rows){ int i,j; for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]); } printf("\n"); } printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2); } int main(int argC,char* argV[]) { int n; if(argC!=2||isdigit(argV[1][0])==0) printf("Usage : %s <integer specifying rows in magic square>",argV[0]); else{ n = atoi(argV[1]); printMagicSquare(singlyEvenMagicSquare(n),n); } return 0; }
Please provide an equivalent version of this Java code in C.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R'); public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", ""))); return pieces; } private static boolean check(String rank){ if(!rank.matches(".*R.*K.*R.*")) return false; if(!rank.matches(".*B(..|....|......|)B.*")) return false; return true; } public static void main(String[] args){ for(int i = 0; i < 10; i++){ System.out.println(generateFirstRank()); } } }
#include<stdlib.h> #include<locale.h> #include<wchar.h> #include<stdio.h> #include<time.h> char rank[9]; int pos[8]; void swap(int i,int j){ int temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; } void generateFirstRank(){ int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i; for(i=0;i<8;i++){ rank[i] = 'e'; pos[i] = i; } do{ kPos = rand()%8; rPos1 = rand()%8; rPos2 = rand()%8; }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2)); rank[pos[rPos1]] = 'R'; rank[pos[kPos]] = 'K'; rank[pos[rPos2]] = 'R'; swap(rPos1,7); swap(rPos2,6); swap(kPos,5); do{ bPos1 = rand()%5; bPos2 = rand()%5; }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2)); rank[pos[bPos1]] = 'B'; rank[pos[bPos2]] = 'B'; swap(bPos1,4); swap(bPos2,3); do{ qPos = rand()%3; nPos1 = rand()%3; }while(qPos==nPos1); rank[pos[qPos]] = 'Q'; rank[pos[nPos1]] = 'N'; for(i=0;i<8;i++) if(rank[i]=='e'){ rank[i] = 'N'; break; } } void printRank(){ int i; #ifdef _WIN32 printf("%s\n",rank); #else { setlocale(LC_ALL,""); printf("\n"); for(i=0;i<8;i++){ if(rank[i]=='K') printf("%lc",(wint_t)9812); else if(rank[i]=='Q') printf("%lc",(wint_t)9813); else if(rank[i]=='R') printf("%lc",(wint_t)9814); else if(rank[i]=='B') printf("%lc",(wint_t)9815); if(rank[i]=='N') printf("%lc",(wint_t)9816); } } #endif } int main() { int i; srand((unsigned)time(NULL)); for(i=0;i<9;i++){ generateFirstRank(); printRank(); } return 0; }
Produce a functionally identical C code for the snippet given in Java.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 2; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; } cell[ptr]+= 1; ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr-= 2; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 4; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 2; if(ptr<0) perror("Program pointer underflow"); } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 7; putchar(cell[ptr]); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 7; putchar(cell[ptr]); ptr-= 3; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { while(cell[ptr]) { cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { cell[ptr]-= 1; } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 15; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); cell[ptr]-= 6; putchar(cell[ptr]); cell[ptr]-= 8; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; putchar(cell[ptr]); ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 4; putchar(cell[ptr]); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 2; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; } cell[ptr]+= 1; ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr-= 2; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 4; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 2; if(ptr<0) perror("Program pointer underflow"); } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 7; putchar(cell[ptr]); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 7; putchar(cell[ptr]); ptr-= 3; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { while(cell[ptr]) { cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { cell[ptr]-= 1; } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 15; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); cell[ptr]-= 6; putchar(cell[ptr]); cell[ptr]-= 8; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; putchar(cell[ptr]); ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 4; putchar(cell[ptr]); return 0; }
Convert the following code from Java to C, ensuring the logic remains intact.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
int meaning_of_life();
Rewrite this program in C while keeping its functionality equivalent to the Java version.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
int meaning_of_life();
Produce a functionally identical C code for the snippet given in Java.
public final class ImprovedNoise { static public double noise(double x, double y, double z) { int X = (int)Math.floor(x) & 255, Y = (int)Math.floor(y) & 255, Z = (int)Math.floor(z) & 255; x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } static double lerp(double t, double a, double b) { return a + t * (b - a); } static double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } }
#include<stdlib.h> #include<stdio.h> #include<math.h> int p[512]; double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } double lerp(double t, double a, double b) { return a + t * (b - a); } double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } double noise(double x, double y, double z) { int X = (int)floor(x) & 255, Y = (int)floor(y) & 255, Z = (int)floor(z) & 255; x -= floor(x); y -= floor(y); z -= floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } void loadPermutation(char* fileName){ FILE* fp = fopen(fileName,"r"); int permutation[256],i; for(i=0;i<256;i++) fscanf(fp,"%d",&permutation[i]); fclose(fp); for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } int main(int argC,char* argV[]) { if(argC!=5) printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>"); else{ loadPermutation(argV[1]); printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL))); } return 0; }
Keep all operations the same but rewrite the snippet in C.
public final class ImprovedNoise { static public double noise(double x, double y, double z) { int X = (int)Math.floor(x) & 255, Y = (int)Math.floor(y) & 255, Z = (int)Math.floor(z) & 255; x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } static double lerp(double t, double a, double b) { return a + t * (b - a); } static double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } }
#include<stdlib.h> #include<stdio.h> #include<math.h> int p[512]; double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } double lerp(double t, double a, double b) { return a + t * (b - a); } double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } double noise(double x, double y, double z) { int X = (int)floor(x) & 255, Y = (int)floor(y) & 255, Z = (int)floor(z) & 255; x -= floor(x); y -= floor(y); z -= floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } void loadPermutation(char* fileName){ FILE* fp = fopen(fileName,"r"); int permutation[256],i; for(i=0;i<256;i++) fscanf(fp,"%d",&permutation[i]); fclose(fp); for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } int main(int argC,char* argV[]) { if(argC!=5) printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>"); else{ loadPermutation(argV[1]); printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL))); } return 0; }
Please provide an equivalent version of this Java code in C.
package rosetta; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class UnixLS { public static void main(String[] args) throws IOException { Files.list(Path.of("")).sorted().forEach(System.out::println); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> int cmpstr(const void *a, const void *b) { return strcmp(*(const char**)a, *(const char**)b); } int main(void) { DIR *basedir; char path[PATH_MAX]; struct dirent *entry; char **dirnames; int diralloc = 128; int dirsize = 0; if (!(dirnames = malloc(diralloc * sizeof(char*)))) { perror("malloc error:"); return 1; } if (!getcwd(path, PATH_MAX)) { perror("getcwd error:"); return 1; } if (!(basedir = opendir(path))) { perror("opendir error:"); return 1; } while ((entry = readdir(basedir))) { if (dirsize >= diralloc) { diralloc *= 2; if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) { perror("realloc error:"); return 1; } } dirnames[dirsize++] = strdup(entry->d_name); } qsort(dirnames, dirsize, sizeof(char*), cmpstr); int i; for (i = 0; i < dirsize; ++i) { if (dirnames[i][0] != '.') { printf("%s\n", dirnames[i]); } } for (i = 0; i < dirsize; ++i) free(dirnames[i]); free(dirnames); closedir(basedir); return 0; }
Keep all operations the same but rewrite the snippet in C.
import java.nio.charset.StandardCharsets; import java.util.Formatter; public class UTF8EncodeDecode { public static byte[] utf8encode(int codepoint) { return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8); } public static int utf8decode(byte[] bytes) { return new String(bytes, StandardCharsets.UTF_8).codePointAt(0); } public static void main(String[] args) { System.out.printf("%-7s %-43s %7s\t%s\t%7s%n", "Char", "Name", "Unicode", "UTF-8 encoded", "Decoded"); for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) { byte[] encoded = utf8encode(codepoint); Formatter formatter = new Formatter(); for (byte b : encoded) { formatter.format("%02X ", b); } String encodedHex = formatter.toString(); int decoded = utf8decode(encoded); System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n", codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded); } } }
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> typedef struct { char mask; char lead; uint32_t beg; uint32_t end; int bits_stored; }utf_t; utf_t * utf[] = { [0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 }, [1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 }, [2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 }, [3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 }, [4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 }, &(utf_t){0}, }; int codepoint_len(const uint32_t cp); int utf8_len(const char ch); char *to_utf8(const uint32_t cp); uint32_t to_cp(const char chr[4]); int codepoint_len(const uint32_t cp) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((cp >= (*u)->beg) && (cp <= (*u)->end)) { break; } ++len; } if(len > 4) exit(1); return len; } int utf8_len(const char ch) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((ch & ~(*u)->mask) == (*u)->lead) { break; } ++len; } if(len > 4) { exit(1); } return len; } char *to_utf8(const uint32_t cp) { static char ret[5]; const int bytes = codepoint_len(cp); int shift = utf[0]->bits_stored * (bytes - 1); ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead; shift -= utf[0]->bits_stored; for(int i = 1; i < bytes; ++i) { ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead; shift -= utf[0]->bits_stored; } ret[bytes] = '\0'; return ret; } uint32_t to_cp(const char chr[4]) { int bytes = utf8_len(*chr); int shift = utf[0]->bits_stored * (bytes - 1); uint32_t codep = (*chr++ & utf[bytes]->mask) << shift; for(int i = 1; i < bytes; ++i, ++chr) { shift -= utf[0]->bits_stored; codep |= ((char)*chr & utf[0]->mask) << shift; } return codep; } int main(void) { const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0}; printf("Character Unicode UTF-8 encoding (hex)\n"); printf("----------------------------------------\n"); char *utf8; uint32_t codepoint; for(in = input; *in; ++in) { utf8 = to_utf8(*in); codepoint = to_cp(utf8); printf("%s U+%-7.4x", utf8, codepoint); for(int i = 0; utf8[i] && i < 4; ++i) { printf("%hhx ", utf8[i]); } printf("\n"); } return 0; }
Translate this program into C but keep the logic exactly as in Java.
import java.awt.*; import static java.lang.Math.*; import javax.swing.*; public class XiaolinWu extends JPanel { public XiaolinWu() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); } void plot(Graphics2D g, double x, double y, double c) { g.setColor(new Color(0f, 0f, 0f, (float)c)); g.fillOval((int) x, (int) y, 2, 2); } int ipart(double x) { return (int) x; } double fpart(double x) { return x - floor(x); } double rfpart(double x) { return 1.0 - fpart(x); } void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) { boolean steep = abs(y1 - y0) > abs(x1 - x0); if (steep) drawLine(g, y0, x0, y1, x1); if (x0 > x1) drawLine(g, x1, y1, x0, y0); double dx = x1 - x0; double dy = y1 - y0; double gradient = dy / dx; double xend = round(x0); double yend = y0 + gradient * (xend - x0); double xgap = rfpart(x0 + 0.5); double xpxl1 = xend; double ypxl1 = ipart(yend); if (steep) { plot(g, ypxl1, xpxl1, rfpart(yend) * xgap); plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap); } else { plot(g, xpxl1, ypxl1, rfpart(yend) * xgap); plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap); } double intery = yend + gradient; xend = round(x1); yend = y1 + gradient * (xend - x1); xgap = fpart(x1 + 0.5); double xpxl2 = xend; double ypxl2 = ipart(yend); if (steep) { plot(g, ypxl2, xpxl2, rfpart(yend) * xgap); plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap); } else { plot(g, xpxl2, ypxl2, rfpart(yend) * xgap); plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap); } for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) { if (steep) { plot(g, ipart(intery), x, rfpart(intery)); plot(g, ipart(intery) + 1, x, fpart(intery)); } else { plot(g, x, ipart(intery), rfpart(intery)); plot(g, x, ipart(intery) + 1, fpart(intery)); } intery = intery + gradient; } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; drawLine(g, 550, 170, 50, 435); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Xiaolin Wu's line algorithm"); f.setResizable(false); f.add(new XiaolinWu(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
void draw_line_antialias( image img, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, color_component r, color_component g, color_component b );
Keep all operations the same but rewrite the snippet in C.
import java.awt.*; import static java.lang.Math.*; import javax.swing.*; public class XiaolinWu extends JPanel { public XiaolinWu() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); } void plot(Graphics2D g, double x, double y, double c) { g.setColor(new Color(0f, 0f, 0f, (float)c)); g.fillOval((int) x, (int) y, 2, 2); } int ipart(double x) { return (int) x; } double fpart(double x) { return x - floor(x); } double rfpart(double x) { return 1.0 - fpart(x); } void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) { boolean steep = abs(y1 - y0) > abs(x1 - x0); if (steep) drawLine(g, y0, x0, y1, x1); if (x0 > x1) drawLine(g, x1, y1, x0, y0); double dx = x1 - x0; double dy = y1 - y0; double gradient = dy / dx; double xend = round(x0); double yend = y0 + gradient * (xend - x0); double xgap = rfpart(x0 + 0.5); double xpxl1 = xend; double ypxl1 = ipart(yend); if (steep) { plot(g, ypxl1, xpxl1, rfpart(yend) * xgap); plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap); } else { plot(g, xpxl1, ypxl1, rfpart(yend) * xgap); plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap); } double intery = yend + gradient; xend = round(x1); yend = y1 + gradient * (xend - x1); xgap = fpart(x1 + 0.5); double xpxl2 = xend; double ypxl2 = ipart(yend); if (steep) { plot(g, ypxl2, xpxl2, rfpart(yend) * xgap); plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap); } else { plot(g, xpxl2, ypxl2, rfpart(yend) * xgap); plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap); } for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) { if (steep) { plot(g, ipart(intery), x, rfpart(intery)); plot(g, ipart(intery) + 1, x, fpart(intery)); } else { plot(g, x, ipart(intery), rfpart(intery)); plot(g, x, ipart(intery) + 1, fpart(intery)); } intery = intery + gradient; } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; drawLine(g, 550, 170, 50, 435); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Xiaolin Wu's line algorithm"); f.setResizable(false); f.add(new XiaolinWu(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
void draw_line_antialias( image img, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, color_component r, color_component g, color_component b );
Ensure the translated C code behaves exactly like the original Java snippet.
package keybord.macro.demo; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; class KeyboardMacroDemo { public static void main( String [] args ) { final JFrame frame = new JFrame(); String directions = "<html><b>Ctrl-S</b> to show frame title<br>" +"<b>Ctrl-H</b> to hide it</html>"; frame.add( new JLabel(directions)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addKeyListener( new KeyAdapter(){ public void keyReleased( KeyEvent e ) { if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){ frame.setTitle("Hello there"); }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){ frame.setTitle(""); } } }); frame.pack(); frame.setVisible(true); } }
#include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/keysym.h> int main() { Display *d; XEvent event; d = XOpenDisplay(NULL); if ( d != NULL ) { XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync); XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync); for(;;) { XNextEvent(d, &event); if ( event.type == KeyPress ) { KeySym s = XLookupKeysym(&event.xkey, 0); if ( s == XK_F7 ) { printf("something's happened\n"); } else if ( s == XK_F6 ) { break; } } } XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d)); XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d)); } return EXIT_SUCCESS; }
Rewrite this program in C while keeping its functionality equivalent to the Java version.
public class McNuggets { public static void main(String... args) { int[] SIZES = new int[] { 6, 9, 20 }; int MAX_TOTAL = 100; int numSizes = SIZES.length; int[] counts = new int[numSizes]; int maxFound = MAX_TOTAL + 1; boolean[] found = new boolean[maxFound]; int numFound = 0; int total = 0; boolean advancedState = false; do { if (!found[total]) { found[total] = true; numFound++; } advancedState = false; for (int i = 0; i < numSizes; i++) { int curSize = SIZES[i]; if ((total + curSize) > MAX_TOTAL) { total -= counts[i] * curSize; counts[i] = 0; } else { counts[i]++; total += curSize; advancedState = true; break; } } } while ((numFound < maxFound) && advancedState); if (numFound < maxFound) { for (int i = MAX_TOTAL; i >= 0; i--) { if (!found[i]) { System.out.println("Largest non-McNugget number in the search space is " + i); break; } } } else { System.out.println("All numbers in the search space are McNugget numbers"); } return; } }
#include <stdio.h> int main() { int max = 0, i = 0, sixes, nines, twenties; loopstart: while (i < 100) { for (sixes = 0; sixes*6 < i; sixes++) { if (sixes*6 == i) { i++; goto loopstart; } for (nines = 0; nines*9 < i; nines++) { if (sixes*6 + nines*9 == i) { i++; goto loopstart; } for (twenties = 0; twenties*20 < i; twenties++) { if (sixes*6 + nines*9 + twenties*20 == i) { i++; goto loopstart; } } } } max = i; i++; } printf("Maximum non-McNuggets number is %d\n", max); return 0; }
Ensure the translated C code behaves exactly like the original Java snippet.
public class MagicSquareDoublyEven { public static void main(String[] args) { int n = 8; for (int[] row : magicSquareDoublyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } static int[][] magicSquareDoublyEven(final int n) { if (n < 4 || n % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[][] result = new int[n][n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } }
#include<stdlib.h> #include<ctype.h> #include<stdio.h> int** doublyEvenMagicSquare(int n) { if (n < 4 || n % 4 != 0) return NULL; int bits = 38505; int size = n * n; int mult = n / 4,i,r,c,bitPos; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); for (r = 0, i = 0; r < n; r++) { for (c = 0; c < n; c++, i++) { bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } int numDigits(int n){ int count = 1; while(n>=10){ n /= 10; count++; } return count; } void printMagicSquare(int** square,int rows){ int i,j,baseWidth = numDigits(rows*rows) + 3; printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2); for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]); } printf("\n"); } } int main(int argC,char* argV[]) { int n; if(argC!=2||isdigit(argV[1][0])==0) printf("Usage : %s <integer specifying rows in magic square>",argV[0]); else{ n = atoi(argV[1]); printMagicSquare(doublyEvenMagicSquare(n),n); } return 0; }
Write the same code in C as shown below in Java.
public class Extreme { public static void main(String[] args) { double negInf = -1.0 / 0.0; double inf = 1.0 / 0.0; double nan = 0.0 / 0.0; double negZero = -2.0 / inf; System.out.println("Negative inf: " + negInf); System.out.println("Positive inf: " + inf); System.out.println("NaN: " + nan); System.out.println("Negative 0: " + negZero); System.out.println("inf + -inf: " + (inf + negInf)); System.out.println("0 * NaN: " + (0 * nan)); System.out.println("NaN == NaN: " + (nan == nan)); } }
#include <stdio.h> int main() { double inf = 1/0.0; double minus_inf = -1/0.0; double minus_zero = -1/ inf ; double nan = 0.0/0.0; printf("positive infinity: %f\n",inf); printf("negative infinity: %f\n",minus_inf); printf("negative zero: %f\n",minus_zero); printf("not a number: %f\n",nan); printf("+inf + 2.0 = %f\n",inf + 2.0); printf("+inf - 10.1 = %f\n",inf - 10.1); printf("+inf + -inf = %f\n",inf + minus_inf); printf("0.0 * +inf = %f\n",0.0 * inf); printf("1.0/-0.0 = %f\n",1.0/minus_zero); printf("NaN + 1.0 = %f\n",nan + 1.0); printf("NaN + NaN = %f\n",nan + nan); printf("NaN == NaN = %s\n",nan == nan ? "true" : "false"); printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false"); return 0; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
public class Extreme { public static void main(String[] args) { double negInf = -1.0 / 0.0; double inf = 1.0 / 0.0; double nan = 0.0 / 0.0; double negZero = -2.0 / inf; System.out.println("Negative inf: " + negInf); System.out.println("Positive inf: " + inf); System.out.println("NaN: " + nan); System.out.println("Negative 0: " + negZero); System.out.println("inf + -inf: " + (inf + negInf)); System.out.println("0 * NaN: " + (0 * nan)); System.out.println("NaN == NaN: " + (nan == nan)); } }
#include <stdio.h> int main() { double inf = 1/0.0; double minus_inf = -1/0.0; double minus_zero = -1/ inf ; double nan = 0.0/0.0; printf("positive infinity: %f\n",inf); printf("negative infinity: %f\n",minus_inf); printf("negative zero: %f\n",minus_zero); printf("not a number: %f\n",nan); printf("+inf + 2.0 = %f\n",inf + 2.0); printf("+inf - 10.1 = %f\n",inf - 10.1); printf("+inf + -inf = %f\n",inf + minus_inf); printf("0.0 * +inf = %f\n",0.0 * inf); printf("1.0/-0.0 = %f\n",1.0/minus_zero); printf("NaN + 1.0 = %f\n",nan + 1.0); printf("NaN + NaN = %f\n",nan + nan); printf("NaN == NaN = %s\n",nan == nan ? "true" : "false"); printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false"); return 0; }
Rewrite the snippet below in C so it works the same as the original Java code.
public class XorShiftStar { private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16); private long state; public void seed(long num) { state = num; } public int nextInt() { long x; int answer; x = state; x = x ^ (x >>> 12); x = x ^ (x << 25); x = x ^ (x >>> 27); state = x; answer = (int) ((x * MAGIC) >> 32); return answer; } public float nextFloat() { return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32); } public static void main(String[] args) { var rng = new XorShiftStar(); rng.seed(1234567); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(); int[] counts = {0, 0, 0, 0, 0}; rng.seed(987654321); for (int i = 0; i < 100_000; i++) { int j = (int) Math.floor(rng.nextFloat() * 5.0); counts[j]++; } for (int i = 0; i < counts.length; i++) { System.out.printf("%d: %d\n", i, counts[i]); } } }
#include <math.h> #include <stdint.h> #include <stdio.h> static uint64_t state; static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D; void seed(uint64_t num) { state = num; } uint32_t next_int() { uint64_t x; uint32_t answer; x = state; x = x ^ (x >> 12); x = x ^ (x << 25); x = x ^ (x >> 27); state = x; answer = ((x * STATE_MAGIC) >> 32); return answer; } float next_float() { return (float)next_int() / (1LL << 32); } int main() { int counts[5] = { 0, 0, 0, 0, 0 }; int i; seed(1234567); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("\n"); seed(987654321); for (i = 0; i < 100000; i++) { int j = (int)floor(next_float() * 5.0); counts[j]++; } for (i = 0; i < 5; i++) { printf("%d: %d\n", i, counts[i]); } return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class AsciiArtDiagramConverter { private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ID |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| QDCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ANCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| NSCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ARCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"; public static void main(String[] args) { validate(TEST); display(TEST); Map<String,List<Integer>> asciiMap = decode(TEST); displayMap(asciiMap); displayCode(asciiMap, "78477bbf5496e12e1bf169a4"); } private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) { System.out.printf("%nTest string in hex:%n%s%n%n", hex); String bin = new BigInteger(hex,16).toString(2); int length = 0; for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); length += pos.get(1) - pos.get(0) + 1; } while ( length > bin.length() ) { bin = "0" + bin; } System.out.printf("Test string in binary:%n%s%n%n", bin); System.out.printf("Name Size Bit Pattern%n"); System.out.printf("-------- ----- -----------%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); int start = pos.get(0); int end = pos.get(1); System.out.printf("%-8s %2d %s%n", code, end-start+1, bin.substring(start, end+1)); } } private static void display(String ascii) { System.out.printf("%nDiagram:%n%n"); for ( String s : TEST.split("\\r\\n") ) { System.out.println(s); } } private static void displayMap(Map<String,List<Integer>> asciiMap) { System.out.printf("%nDecode:%n%n"); System.out.printf("Name Size Start End%n"); System.out.printf("-------- ----- ----- -----%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); System.out.printf("%-8s %2d %2d %2d%n", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1)); } } private static Map<String,List<Integer>> decode(String ascii) { Map<String,List<Integer>> map = new LinkedHashMap<>(); String[] split = TEST.split("\\r\\n"); int size = split[0].indexOf("+", 1) - split[0].indexOf("+"); int length = split[0].length() - 1; for ( int i = 1 ; i < split.length ; i += 2 ) { int barIndex = 1; String test = split[i]; int next; while ( barIndex < length && (next = test.indexOf("|", barIndex)) > 0 ) { List<Integer> startEnd = new ArrayList<>(); startEnd.add((barIndex/size) + (i/2)*(length/size)); startEnd.add(((next-1)/size) + (i/2)*(length/size)); String code = test.substring(barIndex, next).replace(" ", ""); map.put(code, startEnd); barIndex = next + 1; } } return map; } private static void validate(String ascii) { String[] split = TEST.split("\\r\\n"); if ( split.length % 2 != 1 ) { throw new RuntimeException("ERROR 1: Invalid number of input lines. Line count = " + split.length); } int size = 0; for ( int i = 0 ; i < split.length ; i++ ) { String test = split[i]; if ( i % 2 == 0 ) { if ( ! test.matches("^\\+([-]+\\+)+$") ) { throw new RuntimeException("ERROR 2: Improper line format. Line = " + test); } if ( size == 0 ) { int firstPlus = test.indexOf("+"); int secondPlus = test.indexOf("+", 1); size = secondPlus - firstPlus; } if ( ((test.length()-1) % size) != 0 ) { throw new RuntimeException("ERROR 3: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { if ( test.charAt(j) != '+' ) { throw new RuntimeException("ERROR 4: Improper line format. Line = " + test); } for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) != '-' ) { throw new RuntimeException("ERROR 5: Improper line format. Line = " + test); } } } } else { if ( ! test.matches("^\\|(\\s*[A-Za-z]+\\s*\\|)+$") ) { throw new RuntimeException("ERROR 6: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) == '|' ) { throw new RuntimeException("ERROR 7: Improper line format. Line = " + test); } } } } } } }
#include <stdlib.h> #include <stdio.h> #include <string.h> enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 }; char *Lines[MAX_ROWS] = { " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ID |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " |QR| Opcode |AA|TC|RD|RA| Z | RCODE |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | QDCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ANCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | NSCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ARCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" }; typedef struct { unsigned bit3s; unsigned mask; unsigned data; char A[NAME_SZ+2]; }NAME_T; NAME_T names[MAX_NAMES]; unsigned idx_name; enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR}; unsigned header[MAX_HDR]; unsigned idx_hdr; int bit_hdr(char *pLine); int bit_names(char *pLine); void dump_names(void); void make_test_hdr(void); int main(void){ char *p1; int rv; printf("Extract meta-data from bit-encoded text form\n"); make_test_hdr(); idx_name = 0; for( int i=0; i<MAX_ROWS;i++ ){ p1 = Lines[i]; if( p1==NULL ) break; if( rv = bit_hdr(Lines[i]), rv>0) continue; if( rv = bit_names(Lines[i]),rv>0) continue; } dump_names(); } int bit_hdr(char *pLine){ char *p1 = strchr(pLine,'+'); if( p1==NULL ) return 0; int numbits=0; for( int i=0; i<strlen(p1)-1; i+=3 ){ if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0; numbits++; } return numbits; } int bit_names(char *pLine){ char *p1,*p2 = pLine, tmp[80]; unsigned sz=0, maskbitcount = 15; while(1){ p1 = strchr(p2,'|'); if( p1==NULL ) break; p1++; p2 = strchr(p1,'|'); if( p2==NULL ) break; sz = p2-p1; tmp[sz] = 0; int k=0; for(int j=0; j<sz;j++){ if( p1[j] > ' ') tmp[k++] = p1[j]; } tmp[k]= 0; sz++; NAME_T *pn = &names[idx_name++]; strcpy(&pn->A[0], &tmp[0]); pn->bit3s = sz/3; if( pn->bit3s < 16 ){ for( int i=0; i<pn->bit3s; i++){ pn->mask |= 1 << maskbitcount--; } pn->data = header[idx_hdr] & pn->mask; unsigned m2 = pn->mask; while( (m2 & 1)==0 ){ m2>>=1; pn->data >>= 1; } if( pn->mask == 0xf ) idx_hdr++; } else{ pn->data = header[idx_hdr++]; } } return sz; } void dump_names(void){ NAME_T *pn; printf("-name-bits-mask-data-\n"); for( int i=0; i<MAX_NAMES; i++ ){ pn = &names[i]; if( pn->bit3s < 1 ) break; printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data); } puts("bye.."); } void make_test_hdr(void){ header[ID] = 1024; header[QDCOUNT] = 12; header[ANCOUNT] = 34; header[NSCOUNT] = 56; header[ARCOUNT] = 78; header[BITS] = 0xB50A; }
Convert this Java snippet to C and keep its semantics consistent.
import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class AsciiArtDiagramConverter { private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ID |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| QDCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ANCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| NSCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ARCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"; public static void main(String[] args) { validate(TEST); display(TEST); Map<String,List<Integer>> asciiMap = decode(TEST); displayMap(asciiMap); displayCode(asciiMap, "78477bbf5496e12e1bf169a4"); } private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) { System.out.printf("%nTest string in hex:%n%s%n%n", hex); String bin = new BigInteger(hex,16).toString(2); int length = 0; for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); length += pos.get(1) - pos.get(0) + 1; } while ( length > bin.length() ) { bin = "0" + bin; } System.out.printf("Test string in binary:%n%s%n%n", bin); System.out.printf("Name Size Bit Pattern%n"); System.out.printf("-------- ----- -----------%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); int start = pos.get(0); int end = pos.get(1); System.out.printf("%-8s %2d %s%n", code, end-start+1, bin.substring(start, end+1)); } } private static void display(String ascii) { System.out.printf("%nDiagram:%n%n"); for ( String s : TEST.split("\\r\\n") ) { System.out.println(s); } } private static void displayMap(Map<String,List<Integer>> asciiMap) { System.out.printf("%nDecode:%n%n"); System.out.printf("Name Size Start End%n"); System.out.printf("-------- ----- ----- -----%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); System.out.printf("%-8s %2d %2d %2d%n", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1)); } } private static Map<String,List<Integer>> decode(String ascii) { Map<String,List<Integer>> map = new LinkedHashMap<>(); String[] split = TEST.split("\\r\\n"); int size = split[0].indexOf("+", 1) - split[0].indexOf("+"); int length = split[0].length() - 1; for ( int i = 1 ; i < split.length ; i += 2 ) { int barIndex = 1; String test = split[i]; int next; while ( barIndex < length && (next = test.indexOf("|", barIndex)) > 0 ) { List<Integer> startEnd = new ArrayList<>(); startEnd.add((barIndex/size) + (i/2)*(length/size)); startEnd.add(((next-1)/size) + (i/2)*(length/size)); String code = test.substring(barIndex, next).replace(" ", ""); map.put(code, startEnd); barIndex = next + 1; } } return map; } private static void validate(String ascii) { String[] split = TEST.split("\\r\\n"); if ( split.length % 2 != 1 ) { throw new RuntimeException("ERROR 1: Invalid number of input lines. Line count = " + split.length); } int size = 0; for ( int i = 0 ; i < split.length ; i++ ) { String test = split[i]; if ( i % 2 == 0 ) { if ( ! test.matches("^\\+([-]+\\+)+$") ) { throw new RuntimeException("ERROR 2: Improper line format. Line = " + test); } if ( size == 0 ) { int firstPlus = test.indexOf("+"); int secondPlus = test.indexOf("+", 1); size = secondPlus - firstPlus; } if ( ((test.length()-1) % size) != 0 ) { throw new RuntimeException("ERROR 3: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { if ( test.charAt(j) != '+' ) { throw new RuntimeException("ERROR 4: Improper line format. Line = " + test); } for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) != '-' ) { throw new RuntimeException("ERROR 5: Improper line format. Line = " + test); } } } } else { if ( ! test.matches("^\\|(\\s*[A-Za-z]+\\s*\\|)+$") ) { throw new RuntimeException("ERROR 6: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) == '|' ) { throw new RuntimeException("ERROR 7: Improper line format. Line = " + test); } } } } } } }
#include <stdlib.h> #include <stdio.h> #include <string.h> enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 }; char *Lines[MAX_ROWS] = { " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ID |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " |QR| Opcode |AA|TC|RD|RA| Z | RCODE |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | QDCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ANCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | NSCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ARCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" }; typedef struct { unsigned bit3s; unsigned mask; unsigned data; char A[NAME_SZ+2]; }NAME_T; NAME_T names[MAX_NAMES]; unsigned idx_name; enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR}; unsigned header[MAX_HDR]; unsigned idx_hdr; int bit_hdr(char *pLine); int bit_names(char *pLine); void dump_names(void); void make_test_hdr(void); int main(void){ char *p1; int rv; printf("Extract meta-data from bit-encoded text form\n"); make_test_hdr(); idx_name = 0; for( int i=0; i<MAX_ROWS;i++ ){ p1 = Lines[i]; if( p1==NULL ) break; if( rv = bit_hdr(Lines[i]), rv>0) continue; if( rv = bit_names(Lines[i]),rv>0) continue; } dump_names(); } int bit_hdr(char *pLine){ char *p1 = strchr(pLine,'+'); if( p1==NULL ) return 0; int numbits=0; for( int i=0; i<strlen(p1)-1; i+=3 ){ if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0; numbits++; } return numbits; } int bit_names(char *pLine){ char *p1,*p2 = pLine, tmp[80]; unsigned sz=0, maskbitcount = 15; while(1){ p1 = strchr(p2,'|'); if( p1==NULL ) break; p1++; p2 = strchr(p1,'|'); if( p2==NULL ) break; sz = p2-p1; tmp[sz] = 0; int k=0; for(int j=0; j<sz;j++){ if( p1[j] > ' ') tmp[k++] = p1[j]; } tmp[k]= 0; sz++; NAME_T *pn = &names[idx_name++]; strcpy(&pn->A[0], &tmp[0]); pn->bit3s = sz/3; if( pn->bit3s < 16 ){ for( int i=0; i<pn->bit3s; i++){ pn->mask |= 1 << maskbitcount--; } pn->data = header[idx_hdr] & pn->mask; unsigned m2 = pn->mask; while( (m2 & 1)==0 ){ m2>>=1; pn->data >>= 1; } if( pn->mask == 0xf ) idx_hdr++; } else{ pn->data = header[idx_hdr++]; } } return sz; } void dump_names(void){ NAME_T *pn; printf("-name-bits-mask-data-\n"); for( int i=0; i<MAX_NAMES; i++ ){ pn = &names[i]; if( pn->bit3s < 1 ) break; printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data); } puts("bye.."); } void make_test_hdr(void){ header[ID] = 1024; header[QDCOUNT] = 12; header[ANCOUNT] = 34; header[NSCOUNT] = 56; header[ARCOUNT] = 78; header[BITS] = 0xB50A; }
Write the same algorithm in C as shown in this Java implementation.
public class LevenshteinAlignment { public static String[] alignment(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); int[][] costs = new int[a.length()+1][b.length()+1]; for (int j = 0; j <= b.length(); j++) costs[0][j] = j; for (int i = 1; i <= a.length(); i++) { costs[i][0] = i; for (int j = 1; j <= b.length(); j++) { costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1); } } StringBuilder aPathRev = new StringBuilder(); StringBuilder bPathRev = new StringBuilder(); for (int i = a.length(), j = b.length(); i != 0 && j != 0; ) { if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) { aPathRev.append(a.charAt(--i)); bPathRev.append(b.charAt(--j)); } else if (costs[i][j] == 1 + costs[i-1][j]) { aPathRev.append(a.charAt(--i)); bPathRev.append('-'); } else if (costs[i][j] == 1 + costs[i][j-1]) { aPathRev.append('-'); bPathRev.append(b.charAt(--j)); } } return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()}; } public static void main(String[] args) { String[] result = alignment("rosettacode", "raisethysword"); System.out.println(result[0]); System.out.println(result[1]); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct edit_s edit_t, *edit; struct edit_s { char c1, c2; int n; edit next; }; void leven(char *a, char *b) { int i, j, la = strlen(a), lb = strlen(b); edit *tbl = malloc(sizeof(edit) * (1 + la)); tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t)); for (i = 1; i <= la; i++) tbl[i] = tbl[i-1] + (1+lb); for (i = la; i >= 0; i--) { char *aa = a + i; for (j = lb; j >= 0; j--) { char *bb = b + j; if (!*aa && !*bb) continue; edit e = &tbl[i][j]; edit repl = &tbl[i+1][j+1]; edit dela = &tbl[i+1][j]; edit delb = &tbl[i][j+1]; e->c1 = *aa; e->c2 = *bb; if (!*aa) { e->next = delb; e->n = e->next->n + 1; continue; } if (!*bb) { e->next = dela; e->n = e->next->n + 1; continue; } e->next = repl; if (*aa == *bb) { e->n = e->next->n; continue; } if (e->next->n > delb->n) { e->next = delb; e->c1 = 0; } if (e->next->n > dela->n) { e->next = dela; e->c1 = *aa; e->c2 = 0; } e->n = e->next->n + 1; } } edit p = tbl[0]; printf("%s -> %s: %d edits\n", a, b, p->n); while (p->next) { if (p->c1 == p->c2) printf("%c", p->c1); else { putchar('('); if (p->c1) putchar(p->c1); putchar(','); if (p->c2) putchar(p->c2); putchar(')'); } p = p->next; } putchar('\n'); free(tbl[0]); free(tbl); } int main(void) { leven("raisethysword", "rosettacode"); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.util.*; class SameFringe { public interface Node<T extends Comparable<? super T>> { Node<T> getLeft(); Node<T> getRight(); boolean isLeaf(); T getData(); } public static class SimpleNode<T extends Comparable<? super T>> implements Node<T> { private final T data; public SimpleNode<T> left; public SimpleNode<T> right; public SimpleNode(T data) { this(data, null, null); } public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right) { this.data = data; this.left = left; this.right = right; } public Node<T> getLeft() { return left; } public Node<T> getRight() { return right; } public boolean isLeaf() { return ((left == null) && (right == null)); } public T getData() { return data; } public SimpleNode<T> addToTree(T data) { int cmp = data.compareTo(this.data); if (cmp == 0) throw new IllegalArgumentException("Same data!"); if (cmp < 0) { if (left == null) return (left = new SimpleNode<T>(data)); return left.addToTree(data); } if (right == null) return (right = new SimpleNode<T>(data)); return right.addToTree(data); } } public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2) { Stack<Node<T>> stack1 = new Stack<Node<T>>(); Stack<Node<T>> stack2 = new Stack<Node<T>>(); stack1.push(node1); stack2.push(node2); while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null)) if (!node1.getData().equals(node2.getData())) return false; return (node1 == null) && (node2 == null); } private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack) { while (!stack.isEmpty()) { Node<T> node = stack.pop(); if (node.isLeaf()) return node; Node<T> rightNode = node.getRight(); if (rightNode != null) stack.push(rightNode); Node<T> leftNode = node.getLeft(); if (leftNode != null) stack.push(leftNode); } return null; } public static void main(String[] args) { SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50))); SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null)))); SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56))))); System.out.print("Leaves for set 1: "); simpleWalk(headNode1); System.out.println(); System.out.print("Leaves for set 2: "); simpleWalk(headNode2); System.out.println(); System.out.print("Leaves for set 3: "); simpleWalk(headNode3); System.out.println(); System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2)); System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3)); } public static void simpleWalk(Node<Integer> node) { if (node.isLeaf()) System.out.print(node.getData() + " "); else { Node<Integer> left = node.getLeft(); if (left != null) simpleWalk(left); Node<Integer> right = node.getRight(); if (right != null) simpleWalk(right); } } }
#include <stdio.h> #include <stdlib.h> #include <ucontext.h> typedef struct { ucontext_t caller, callee; char stack[8192]; void *in, *out; } co_t; co_t * co_new(void(*f)(), void *data) { co_t * c = malloc(sizeof(*c)); getcontext(&c->callee); c->in = data; c->callee.uc_stack.ss_sp = c->stack; c->callee.uc_stack.ss_size = sizeof(c->stack); c->callee.uc_link = &c->caller; makecontext(&c->callee, f, 1, (int)c); return c; } void co_del(co_t *c) { free(c); } inline void co_yield(co_t *c, void *data) { c->out = data; swapcontext(&c->callee, &c->caller); } inline void * co_collect(co_t *c) { c->out = 0; swapcontext(&c->caller, &c->callee); return c->out; } typedef struct node node; struct node { int v; node *left, *right; }; node *newnode(int v) { node *n = malloc(sizeof(node)); n->left = n->right = 0; n->v = v; return n; } void tree_insert(node **root, node *n) { while (*root) root = ((*root)->v > n->v) ? &(*root)->left : &(*root)->right; *root = n; } void tree_trav(int x) { co_t *c = (co_t *) x; void trav(node *root) { if (!root) return; trav(root->left); co_yield(c, root); trav(root->right); } trav(c->in); } int tree_eq(node *t1, node *t2) { co_t *c1 = co_new(tree_trav, t1); co_t *c2 = co_new(tree_trav, t2); node *p = 0, *q = 0; do { p = co_collect(c1); q = co_collect(c2); } while (p && q && (p->v == q->v)); co_del(c1); co_del(c2); return !p && !q; } int main() { int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 }; int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 }; int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 }; node *t1 = 0, *t2 = 0, *t3 = 0; void mktree(int *buf, node **root) { int i; for (i = 0; buf[i] >= 0; i++) tree_insert(root, newnode(buf[i])); } mktree(x, &t1); mktree(y, &t2); mktree(z, &t3); printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no"); printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no"); return 0; }
Produce a functionally identical C code for the snippet given in Java.
import java.awt.Robot public static void type(String str){ Robot robot = new Robot(); for(char ch:str.toCharArray()){ if(Character.isUpperCase(ch)){ robot.keyPress(KeyEvent.VK_SHIFT); robot.keyPress((int)ch); robot.keyRelease((int)ch); robot.keyRelease(KeyEvent.VK_SHIFT); }else{ char upCh = Character.toUpperCase(ch); robot.keyPress((int)upCh); robot.keyRelease((int)upCh); } } }
#include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/Xutil.h> int main(int argc, char *argv[]) { Display *dpy; Window win; GC gc; int scr; Atom WM_DELETE_WINDOW; XEvent ev; XEvent ev2; KeySym keysym; int loop; dpy = XOpenDisplay(NULL); if (dpy == NULL) { fputs("Cannot open display", stderr); exit(1); } scr = XDefaultScreen(dpy); win = XCreateSimpleWindow(dpy, XRootWindow(dpy, scr), 10, 10, 300, 200, 1, XBlackPixel(dpy, scr), XWhitePixel(dpy, scr)); XStoreName(dpy, win, argv[0]); XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask); XMapWindow(dpy, win); XFlush(dpy); gc = XDefaultGC(dpy, scr); WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True); XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1); loop = 1; while (loop) { XNextEvent(dpy, &ev); switch (ev.type) { case Expose: { char msg1[] = "Clic in the window to generate"; char msg2[] = "a key press event"; XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1); XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1); } break; case ButtonPress: puts("ButtonPress event received"); ev2.type = KeyPress; ev2.xkey.state = ShiftMask; ev2.xkey.keycode = 24 + (rand() % 33); ev2.xkey.same_screen = True; XSendEvent(dpy, win, True, KeyPressMask, &ev2); break; case ClientMessage: if (ev.xclient.data.l[0] == WM_DELETE_WINDOW) loop = 0; break; case KeyPress: puts("KeyPress event received"); printf("> keycode: %d\n", ev.xkey.keycode); keysym = XLookupKeysym(&(ev.xkey), 0); if (keysym == XK_q || keysym == XK_Escape) { loop = 0; } else { char buffer[] = " "; int nchars = XLookupString( &(ev.xkey), buffer, 2, &keysym, NULL ); if (nchars == 1) printf("> Key '%c' pressed\n", buffer[0]); } break; } } XDestroyWindow(dpy, win); XCloseDisplay(dpy); return 1; }
Generate an equivalent C version of this Java code.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Peaceful { enum Piece { Empty, Black, White, } public static class Position { public int x, y; public Position(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (obj instanceof Position) { Position pos = (Position) obj; return pos.x == x && pos.y == y; } return false; } } private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } boolean placingBlack = true; for (int i = 0; i < n; ++i) { inner: for (int j = 0; j < n; ++j) { Position pos = new Position(i, j); for (Position queen : pBlackQueens) { if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) { continue inner; } } for (Position queen : pWhiteQueens) { if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) { continue inner; } } if (placingBlack) { pBlackQueens.add(pos); placingBlack = false; } else { pWhiteQueens.add(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.remove(pBlackQueens.size() - 1); pWhiteQueens.remove(pWhiteQueens.size() - 1); placingBlack = true; } } } if (!placingBlack) { pBlackQueens.remove(pBlackQueens.size() - 1); } return false; } private static boolean isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y); } private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { Piece[] board = new Piece[n * n]; Arrays.fill(board, Piece.Empty); for (Position queen : blackQueens) { board[queen.x + n * queen.y] = Piece.Black; } for (Position queen : whiteQueens) { board[queen.x + n * queen.y] = Piece.White; } for (int i = 0; i < board.length; ++i) { if ((i != 0) && i % n == 0) { System.out.println(); } Piece b = board[i]; if (b == Piece.Black) { System.out.print("B "); } else if (b == Piece.White) { System.out.print("W "); } else { int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { System.out.print("• "); } else { System.out.print("◦ "); } } } System.out.println('\n'); } public static void main(String[] args) { List<Position> nms = List.of( new Position(2, 1), new Position(3, 1), new Position(3, 2), new Position(4, 1), new Position(4, 2), new Position(4, 3), new Position(5, 1), new Position(5, 2), new Position(5, 3), new Position(5, 4), new Position(5, 5), new Position(6, 1), new Position(6, 2), new Position(6, 3), new Position(6, 4), new Position(6, 5), new Position(6, 6), new Position(7, 1), new Position(7, 2), new Position(7, 3), new Position(7, 4), new Position(7, 5), new Position(7, 6), new Position(7, 7) ); for (Position nm : nms) { int m = nm.y; int n = nm.x; System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n); List<Position> blackQueens = new ArrayList<>(); List<Position> whiteQueens = new ArrayList<>(); if (place(m, n, blackQueens, whiteQueens)) { printBoard(n, blackQueens, whiteQueens); } else { System.out.println("No solution exists.\n"); } } } }
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> enum Piece { Empty, Black, White, }; typedef struct Position_t { int x, y; } Position; struct Node_t { Position pos; struct Node_t *next; }; void releaseNode(struct Node_t *head) { if (head == NULL) return; releaseNode(head->next); head->next = NULL; free(head); } typedef struct List_t { struct Node_t *head; struct Node_t *tail; size_t length; } List; List makeList() { return (List) { NULL, NULL, 0 }; } void releaseList(List *lst) { if (lst == NULL) return; releaseNode(lst->head); lst->head = NULL; lst->tail = NULL; } void addNode(List *lst, Position pos) { struct Node_t *newNode; if (lst == NULL) { exit(EXIT_FAILURE); } newNode = malloc(sizeof(struct Node_t)); if (newNode == NULL) { exit(EXIT_FAILURE); } newNode->next = NULL; newNode->pos = pos; if (lst->head == NULL) { lst->head = lst->tail = newNode; } else { lst->tail->next = newNode; lst->tail = newNode; } lst->length++; } void removeAt(List *lst, size_t pos) { if (lst == NULL) return; if (pos == 0) { struct Node_t *temp = lst->head; if (lst->tail == lst->head) { lst->tail = NULL; } lst->head = lst->head->next; temp->next = NULL; free(temp); lst->length--; } else { struct Node_t *temp = lst->head; struct Node_t *rem; size_t i = pos; while (i-- > 1) { temp = temp->next; } rem = temp->next; if (rem == lst->tail) { lst->tail = temp; } temp->next = rem->next; rem->next = NULL; free(rem); lst->length--; } } bool isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || abs(queen.x - pos.x) == abs(queen.y - pos.y); } bool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) { struct Node_t *queenNode; bool placingBlack = true; int i, j; if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); } if (m == 0) return true; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { Position pos = { i, j }; queenNode = pBlackQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; } queenNode = pWhiteQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; } if (placingBlack) { addNode(pBlackQueens, pos); placingBlack = false; } else { addNode(pWhiteQueens, pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } removeAt(pBlackQueens, pBlackQueens->length - 1); removeAt(pWhiteQueens, pWhiteQueens->length - 1); placingBlack = true; } inner: {} } } if (!placingBlack) { removeAt(pBlackQueens, pBlackQueens->length - 1); } return false; } void printBoard(int n, List *pBlackQueens, List *pWhiteQueens) { size_t length = n * n; struct Node_t *queenNode; char *board; size_t i, j, k; if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); } board = calloc(length, sizeof(char)); if (board == NULL) { exit(EXIT_FAILURE); } queenNode = pBlackQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = Black; queenNode = queenNode->next; } queenNode = pWhiteQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = White; queenNode = queenNode->next; } for (i = 0; i < length; i++) { if (i != 0 && i % n == 0) { printf("\n"); } switch (board[i]) { case Black: printf("B "); break; case White: printf("W "); break; default: j = i / n; k = i - j * n; if (j % 2 == k % 2) { printf(" "); } else { printf("# "); } break; } } printf("\n\n"); } void test(int n, int q) { List blackQueens = makeList(); List whiteQueens = makeList(); printf("%d black and %d white queens on a %d x %d board:\n", q, q, n, n); if (place(q, n, &blackQueens, &whiteQueens)) { printBoard(n, &blackQueens, &whiteQueens); } else { printf("No solution exists.\n\n"); } releaseList(&blackQueens); releaseList(&whiteQueens); } int main() { test(2, 1); test(3, 1); test(3, 2); test(4, 1); test(4, 2); test(4, 3); test(5, 1); test(5, 2); test(5, 3); test(5, 4); test(5, 5); test(6, 1); test(6, 2); test(6, 3); test(6, 4); test(6, 5); test(6, 6); test(7, 1); test(7, 2); test(7, 3); test(7, 4); test(7, 5); test(7, 6); test(7, 7); return EXIT_SUCCESS; }
Change the following Java code into C without altering its purpose.
import java.util.LinkedList; import java.util.List; public class MTF{ public static List<Integer> encode(String msg, String symTable){ List<Integer> output = new LinkedList<Integer>(); StringBuilder s = new StringBuilder(symTable); for(char c : msg.toCharArray()){ int idx = s.indexOf("" + c); output.add(idx); s = s.deleteCharAt(idx).insert(0, c); } return output; } public static String decode(List<Integer> idxs, String symTable){ StringBuilder output = new StringBuilder(); StringBuilder s = new StringBuilder(symTable); for(int idx : idxs){ char c = s.charAt(idx); output = output.append(c); s = s.deleteCharAt(idx).insert(0, c); } return output.toString(); } private static void test(String toEncode, String symTable){ List<Integer> encoded = encode(toEncode, symTable); System.out.println(toEncode + ": " + encoded); String decoded = decode(encoded, symTable); System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded); } public static void main(String[] args){ String symTable = "abcdefghijklmnopqrstuvwxyz"; test("broood", symTable); test("bananaaa", symTable); test("hiphophiphop", symTable); } }
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_SIZE 100 int move_to_front(char *str,char c) { char *q,*p; int shift=0; p=(char *)malloc(strlen(str)+1); strcpy(p,str); q=strchr(p,c); shift=q-p; strncpy(str+1,p,shift); str[0]=c; free(p); return shift; } void decode(int* pass,int size,char *sym) { int i,index; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=table[pass[i]]; index=move_to_front(table,c); if(pass[i]!=index) printf("there is an error"); sym[i]=c; } sym[size]='\0'; } void encode(char *sym,int size,int *pass) { int i=0; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=sym[i]; pass[i]=move_to_front(table,c); } } int check(char *sym,int size,int *pass) { int *pass2=malloc(sizeof(int)*size); char *sym2=malloc(sizeof(char)*size); int i,val=1; encode(sym,size,pass2); i=0; while(i<size && pass[i]==pass2[i])i++; if(i!=size)val=0; decode(pass,size,sym2); if(strcmp(sym,sym2)!=0)val=0; free(sym2); free(pass2); return val; } int main() { char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"}; int pass[MAX_SIZE]={0}; int i,len,j; for(i=0;i<3;i++) { len=strlen(sym[i]); encode(sym[i],len,pass); printf("%s : [",sym[i]); for(j=0;j<len;j++) printf("%d ",pass[j]); printf("]\n"); if(check(sym[i],len,pass)) printf("Correct :)\n"); else printf("Incorrect :(\n"); } return 0; }
Translate the given Java code snippet into C without altering its behavior.
import java.io.IOException; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; public class LdapSearchDemo { public static void main(String[] args) throws IOException, LdapException, CursorException { new LdapSearchDemo().demonstrateSearch(); } private void demonstrateSearch() throws IOException, LdapException, CursorException { try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) { conn.bind("uid=admin,ou=system", "********"); search(conn, "*mil*"); conn.unBind(); } } private void search(LdapConnection connection, String uid) throws LdapException, CursorException { String baseDn = "ou=users,o=mojo"; String filter = "(&(objectClass=person)(&(uid=" + uid + ")))"; SearchScope scope = SearchScope.SUBTREE; String[] attributes = {"dn", "cn", "sn", "uid"}; int ksearch = 0; EntryCursor cursor = connection.search(baseDn, filter, scope, attributes); while (cursor.next()) { ksearch++; Entry entry = cursor.get(); System.out.printf("Search entry %d = %s%n", ksearch, entry); } } }
#include <ldap.h> char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); LDAPMessage **result; ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE, "(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))", NULL, 0, result); ldap_msgfree(*result); ldap_unbind(ld);
Produce a language-to-language conversion: from Java to C, same semantics.
import java.io.IOException; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; public class LdapSearchDemo { public static void main(String[] args) throws IOException, LdapException, CursorException { new LdapSearchDemo().demonstrateSearch(); } private void demonstrateSearch() throws IOException, LdapException, CursorException { try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) { conn.bind("uid=admin,ou=system", "********"); search(conn, "*mil*"); conn.unBind(); } } private void search(LdapConnection connection, String uid) throws LdapException, CursorException { String baseDn = "ou=users,o=mojo"; String filter = "(&(objectClass=person)(&(uid=" + uid + ")))"; SearchScope scope = SearchScope.SUBTREE; String[] attributes = {"dn", "cn", "sn", "uid"}; int ksearch = 0; EntryCursor cursor = connection.search(baseDn, filter, scope, attributes); while (cursor.next()) { ksearch++; Entry entry = cursor.get(); System.out.printf("Search entry %d = %s%n", ksearch, entry); } } }
#include <ldap.h> char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); LDAPMessage **result; ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE, "(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))", NULL, 0, result); ldap_msgfree(*result); ldap_unbind(ld);
Port the provided Java code into C while preserving the original functionality.
import Jama.Matrix; public class SingularValueDecomposition { public static void main(String[] args) { double[][] matrixArray = {{3, 0}, {4, 5}}; var matrix = new Matrix(matrixArray); var svd = matrix.svd(); svd.getU().print(0, 10); svd.getS().print(0, 10); svd.getV().print(0, 10); } }
#include <stdio.h> #include <gsl/gsl_linalg.h> void gsl_matrix_print(const gsl_matrix *M) { int rows = M->size1; int cols = M->size2; for (int i = 0; i < rows; i++) { printf("|"); for (int j = 0; j < cols; j++) { printf("% 12.10f ", gsl_matrix_get(M, i, j)); } printf("\b|\n"); } printf("\n"); } int main(){ double a[] = {3, 0, 4, 5}; gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2); gsl_matrix *V = gsl_matrix_alloc(2, 2); gsl_vector *S = gsl_vector_alloc(2); gsl_vector *work = gsl_vector_alloc(2); gsl_linalg_SV_decomp(&A.matrix, V, S, work); gsl_matrix_transpose(V); double s[] = {S->data[0], 0, 0, S->data[1]}; gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2); printf("U:\n"); gsl_matrix_print(&A.matrix); printf("S:\n"); gsl_matrix_print(&SM.matrix); printf("VT:\n"); gsl_matrix_print(V); gsl_matrix_free(V); gsl_vector_free(S); gsl_vector_free(work); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.math.BigDecimal; import java.util.List; public class TestIntegerness { private static boolean isLong(double d) { return isLong(d, 0.0); } private static boolean isLong(double d, double tolerance) { return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance; } @SuppressWarnings("ResultOfMethodCallIgnored") private static boolean isBigInteger(BigDecimal bd) { try { bd.toBigIntegerExact(); return true; } catch (ArithmeticException ex) { return false; } } private static class Rational { long num; long denom; Rational(int num, int denom) { this.num = num; this.denom = denom; } boolean isLong() { return num % denom == 0; } @Override public String toString() { return String.format("%s/%s", num, denom); } } private static class Complex { double real; double imag; Complex(double real, double imag) { this.real = real; this.imag = imag; } boolean isLong() { return TestIntegerness.isLong(real) && imag == 0.0; } @Override public String toString() { if (imag >= 0.0) { return String.format("%s + %si", real, imag); } return String.format("%s - %si", real, imag); } } public static void main(String[] args) { List<Double> da = List.of(25.000000, 24.999999, 25.000100); for (Double d : da) { boolean exact = isLong(d); System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an"); } System.out.println(); double tolerance = 0.00001; System.out.printf("With a tolerance of %.5f:%n", tolerance); for (Double d : da) { boolean fuzzy = isLong(d, tolerance); System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an"); } System.out.println(); List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY); for (Double f : fa) { boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString())); System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an"); } System.out.println(); List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0)); for (Complex c : ca) { boolean exact = c.isLong(); System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an"); } System.out.println(); List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2)); for (Rational r : ra) { boolean exact = r.isLong(); System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an"); } } }
#include <stdio.h> #include <complex.h> #include <math.h> #define FMTSPEC(arg) _Generic((arg), \ float: "%f", double: "%f", \ long double: "%Lf", unsigned int: "%u", \ unsigned long: "%lu", unsigned long long: "%llu", \ int: "%d", long: "%ld", long long: "%lld", \ default: "(invalid type (%p)") #define CMPPARTS(x, y) ((long double complex)((long double)(x) + \ I * (long double)(y))) #define TEST_CMPL(i, j)\ printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \ printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false")) #define TEST_REAL(i)\ printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false")) static inline int isint(long double complex n) { return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n); } int main(void) { TEST_REAL(0); TEST_REAL(-0); TEST_REAL(-2); TEST_REAL(-2.00000000000001); TEST_REAL(5); TEST_REAL(7.3333333333333); TEST_REAL(3.141592653589); TEST_REAL(-9.223372036854776e18); TEST_REAL(5e-324); TEST_REAL(NAN); TEST_CMPL(6, 0); TEST_CMPL(0, 1); TEST_CMPL(0, 0); TEST_CMPL(3.4, 0); double complex test1 = 5 + 0*I, test2 = 3.4f, test3 = 3, test4 = 0 + 1.2*I; printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false"); printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false"); printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false"); printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false"); }
Write a version of this Java function in C with identical behavior.
import java.util.Scanner; import java.io.*; public class Program { public static void main(String[] args) { try { Process p = Runtime.getRuntime().exec("cmd /C dir"); Scanner sc = new Scanner(p.getInputStream()); while (sc.hasNext()) System.out.println(sc.nextLine()); } catch (IOException e) { System.out.println(e.getMessage()); } } }
#include <stdlib.h> int main() { system("ls"); return 0; }
Generate an equivalent C version of this Java code.
class Vector{ private double x, y, z; public Vector(double x1,double y1,double z1){ x = x1; y = y1; z = z1; } void printVector(int x,int y){ text("( " + this.x + " ) \u00ee + ( " + this.y + " ) + \u0135 ( " + this.z + ") \u006b\u0302",x,y); } public double norm() { return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z); } public Vector normalize(){ double length = this.norm(); return new Vector(this.x / length, this.y / length, this.z / length); } public double dotProduct(Vector v2) { return this.x*v2.x + this.y*v2.y + this.z*v2.z; } public Vector crossProduct(Vector v2) { return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x); } public double getAngle(Vector v2) { return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm())); } public Vector aRotate(Vector v, double a) { double ca = Math.cos(a), sa = Math.sin(a); double t = 1.0 - ca; double x = v.x, y = v.y, z = v.z; Vector[] r = { new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa), new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa), new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t) }; return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2])); } } void setup(){ Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d); double a = v1.getAngle(v2); Vector cp = v1.crossProduct(v2); Vector normCP = cp.normalize(); Vector np = v1.aRotate(normCP,a); size(1200,600); fill(#000000); textSize(30); text("v1 = ",10,100); v1.printVector(60,100); text("v2 = ",10,150); v2.printVector(60,150); text("rV = ",10,200); np.printVector(60,200); }
#include <stdio.h> #include <math.h> typedef struct { double x, y, z; } vector; typedef struct { vector i, j, k; } matrix; double norm(vector v) { return sqrt(v.x*v.x + v.y*v.y + v.z*v.z); } vector normalize(vector v){ double length = norm(v); vector n = {v.x / length, v.y / length, v.z / length}; return n; } double dotProduct(vector v1, vector v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; } vector crossProduct(vector v1, vector v2) { vector cp = {v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x}; return cp; } double getAngle(vector v1, vector v2) { return acos(dotProduct(v1, v2) / (norm(v1)*norm(v2))); } vector matrixMultiply(matrix m ,vector v) { vector mm = {dotProduct(m.i, v), dotProduct(m.j, v), dotProduct(m.k, v)}; return mm; } vector aRotate(vector p, vector v, double a) { double ca = cos(a), sa = sin(a); double t = 1.0 - ca; double x = v.x, y = v.y, z = v.z; matrix r = { {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa}, {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa}, {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t} }; return matrixMultiply(r, p); } int main() { vector v1 = {5, -6, 4}, v2 = {8, 5, -30}; double a = getAngle(v1, v2); vector cp = crossProduct(v1, v2); vector ncp = normalize(cp); vector np = aRotate(v1, ncp, a); printf("[%.13f, %.13f, %.13f]\n", np.x, np.y, np.z); return 0; }
Generate an equivalent C version of this Java code.
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import java.net.MalformedURLException; import java.net.URL; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import javax.xml.ws.Holder; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class XmlValidation { public static void main(String... args) throws MalformedURLException { URL schemaLocation = new URL("http: URL documentLocation = new URL("http: if (validate(schemaLocation, documentLocation)) { System.out.println("document is valid"); } else { System.out.println("document is invalid"); } } public static boolean minimalValidate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.validate(new StreamSource(documentLocation.toString())); return true; } catch (Exception e) { return false; } } public static boolean validate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); final Holder<Boolean> valid = new Holder<>(true); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.setErrorHandler(new ErrorHandler(){ @Override public void warning(SAXParseException exception) { System.out.println("warning: " + exception.getMessage()); } @Override public void error(SAXParseException exception) { System.out.println("error: " + exception.getMessage()); valid.value = false; } @Override public void fatalError(SAXParseException exception) throws SAXException { System.out.println("fatal error: " + exception.getMessage()); throw exception; }}); validator.validate(new StreamSource(documentLocation.toString())); return valid.value; } catch (SAXException e) { return false; } catch (Exception e) { System.err.println(e); return false; } } }
#include <libxml/xmlschemastypes.h> int main(int argC, char** argV) { if (argC <= 2) { printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]); return 0; } xmlDocPtr doc; xmlSchemaPtr schema = NULL; xmlSchemaParserCtxtPtr ctxt; char *XMLFileName = argV[1]; char *XSDFileName = argV[2]; int ret; xmlLineNumbersDefault(1); ctxt = xmlSchemaNewParserCtxt(XSDFileName); xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); schema = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); doc = xmlReadFile(XMLFileName, NULL, 0); if (doc == NULL){ fprintf(stderr, "Could not parse %s\n", XMLFileName); } else{ xmlSchemaValidCtxtPtr ctxt; ctxt = xmlSchemaNewValidCtxt(schema); xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); ret = xmlSchemaValidateDoc(ctxt, doc); if (ret == 0){ printf("%s validates\n", XMLFileName); } else if (ret > 0){ printf("%s fails to validate\n", XMLFileName); } else{ printf("%s validation generated an internal error\n", XMLFileName); } xmlSchemaFreeValidCtxt(ctxt); xmlFreeDoc(doc); } if(schema != NULL) xmlSchemaFree(schema); xmlSchemaCleanupTypes(); xmlCleanupParser(); xmlMemoryDump(); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Java version.
import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Point3D; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.shape.MeshView; import javafx.scene.shape.TriangleMesh; import javafx.scene.transform.Rotate; import javafx.stage.Stage; public class DeathStar extends Application { private static final int DIVISION = 200; float radius = 300; @Override public void start(Stage primaryStage) throws Exception { Point3D otherSphere = new Point3D(-radius, 0, -radius * 1.5); final TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere); MeshView a = new MeshView(triangleMesh); a.setTranslateY(radius); a.setTranslateX(radius); a.setRotationAxis(Rotate.Y_AXIS); Scene scene = new Scene(new Group(a)); primaryStage.setScene(scene); primaryStage.show(); } static TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) { Rotate rotate = new Rotate(180, centerOtherSphere); final int div2 = division / 2; final int nPoints = division * (div2 - 1) + 2; final int nTPoints = (division + 1) * (div2 - 1) + division * 2; final int nFaces = division * (div2 - 2) * 2 + division * 2; final float rDiv = 1.f / division; float points[] = new float[nPoints * 3]; float tPoints[] = new float[nTPoints * 2]; int faces[] = new int[nFaces * 6]; int pPos = 0, tPos = 0; for (int y = 0; y < div2 - 1; ++y) { float va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI; float sin_va = (float) Math.sin(va); float cos_va = (float) Math.cos(va); float ty = 0.5f + sin_va * 0.5f; for (int i = 0; i < division; ++i) { double a = rDiv * i * 2 * (float) Math.PI; float hSin = (float) Math.sin(a); float hCos = (float) Math.cos(a); points[pPos + 0] = hSin * cos_va * radius; points[pPos + 2] = hCos * cos_va * radius; points[pPos + 1] = sin_va * radius; final Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]); double distance = centerOtherSphere.distance(point3D); if (distance <= radius) { Point3D subtract = centerOtherSphere.subtract(point3D); Point3D transform = rotate.transform(subtract); points[pPos + 0] = (float) transform.getX(); points[pPos + 1] = (float) transform.getY(); points[pPos + 2] = (float) transform.getZ(); } tPoints[tPos + 0] = 1 - rDiv * i; tPoints[tPos + 1] = ty; pPos += 3; tPos += 2; } tPoints[tPos + 0] = 0; tPoints[tPos + 1] = ty; tPos += 2; } points[pPos + 0] = 0; points[pPos + 1] = -radius; points[pPos + 2] = 0; points[pPos + 3] = 0; points[pPos + 4] = radius; points[pPos + 5] = 0; pPos += 6; int pS = (div2 - 1) * division; float textureDelta = 1.f / 256; for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = textureDelta; tPos += 2; } for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = 1 - textureDelta; tPos += 2; } int fIndex = 0; for (int y = 0; y < div2 - 2; ++y) { for (int x = 0; x < division; ++x) { int p0 = y * division + x; int p1 = p0 + 1; int p2 = p0 + division; int p3 = p1 + division; int t0 = p0 + y; int t1 = t0 + 1; int t2 = t0 + division + 1; int t3 = t1 + division + 1; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2; faces[fIndex + 5] = t2; fIndex += 6; faces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3; faces[fIndex + 1] = t3; faces[fIndex + 2] = p2; faces[fIndex + 3] = t2; faces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 5] = t1; fIndex += 6; } } int p0 = pS; int tB = (div2 - 1) * (division + 1); for (int x = 0; x < division; ++x) { int p2 = x, p1 = x + 1, t0 = tB + x; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 == division ? 0 : p1; faces[fIndex + 3] = p1; faces[fIndex + 4] = p2; faces[fIndex + 5] = p2; fIndex += 6; } p0 = p0 + 1; tB = tB + division; int pB = (div2 - 2) * division; for (int x = 0; x < division; ++x) { int p1 = pB + x, p2 = pB + x + 1, t0 = tB + x; int t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2; faces[fIndex + 5] = t2; fIndex += 6; } TriangleMesh m = new TriangleMesh(); m.getPoints().setAll(points); m.getTexCoords().setAll(tPoints); m.getFaces().setAll(faces); return m; } public static void main(String[] args) { launch(args); } }
#include <stdio.h> #include <math.h> #include <unistd.h> const char *shades = ".:!*oe&#%@"; double light[3] = { -50, 0, 50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } typedef struct { double cx, cy, cz, r; } sphere_t; sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 }; int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2) { double zsq; x -= sph->cx; y -= sph->cy; zsq = sph->r * sph->r - (x * x + y * y); if (zsq < 0) return 0; zsq = sqrt(zsq); *z1 = sph->cz - zsq; *z2 = sph->cz + zsq; return 1; } void draw_sphere(double k, double ambient) { int i, j, intensity, hit_result; double b; double vec[3], x, y, zb1, zb2, zs1, zs2; for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) { y = i + .5; for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) { x = (j - pos.cx) / 2. + .5 + pos.cx; if (!hit_sphere(&pos, x, y, &zb1, &zb2)) hit_result = 0; else if (!hit_sphere(&neg, x, y, &zs1, &zs2)) hit_result = 1; else if (zs1 > zb1) hit_result = 1; else if (zs2 > zb2) hit_result = 0; else if (zs2 > zb1) hit_result = 2; else hit_result = 1; switch(hit_result) { case 0: putchar('+'); continue; case 1: vec[0] = x - pos.cx; vec[1] = y - pos.cy; vec[2] = zb1 - pos.cz; break; default: vec[0] = neg.cx - x; vec[1] = neg.cy - y; vec[2] = neg.cz - zs2; } normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } putchar('\n'); } } int main() { double ang = 0; while (1) { printf("\033[H"); light[1] = cos(ang * 2); light[2] = cos(ang); light[0] = sin(ang); normalize(light); ang += .05; draw_sphere(2, .3); usleep(100000); } return 0; }
Change the following Java code into C without altering its purpose.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LuckyNumbers { private static int MAX = 200000; private static List<Integer> luckyEven = luckyNumbers(MAX, true); private static List<Integer> luckyOdd = luckyNumbers(MAX, false); public static void main(String[] args) { if ( args.length == 1 || ( args.length == 2 && args[1].compareTo("lucky") == 0 ) ) { int n = Integer.parseInt(args[0]); System.out.printf("LuckyNumber(%d) = %d%n", n, luckyOdd.get(n-1)); } else if ( args.length == 2 && args[1].compareTo("evenLucky") == 0 ) { int n = Integer.parseInt(args[0]); System.out.printf("EvenLuckyNumber(%d) = %d%n", n, luckyEven.get(n-1)); } else if ( args.length == 2 || args.length == 3 ) { int j = Integer.parseInt(args[0]); int k = Integer.parseInt(args[1]); if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo("lucky") == 0 ) ) { System.out.printf("LuckyNumber(%d) through LuckyNumber(%d) = %s%n", j, k, luckyOdd.subList(j-1, k)); } else if ( args.length == 3 && k > 0 && args[2].compareTo("evenLucky") == 0 ) { System.out.printf("EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n", j, k, luckyEven.subList(j-1, k)); } else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo("lucky") == 0 ) ) { int n = Collections.binarySearch(luckyOdd, j); int m = Collections.binarySearch(luckyOdd, -k); System.out.printf("Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1)); } else if ( args.length == 3 && k < 0 && args[2].compareTo("evenLucky") == 0 ) { int n = Collections.binarySearch(luckyEven, j); int m = Collections.binarySearch(luckyEven, -k); System.out.printf("Even Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1)); } } } private static List<Integer> luckyNumbers(int max, boolean even) { List<Integer> luckyList = new ArrayList<>(); for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) { luckyList.add(i); } int start = 1; boolean removed = true; while ( removed ) { removed = false; int increment = luckyList.get(start); List<Integer> remove = new ArrayList<>(); for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) { remove.add(0, i); removed = true; } for ( int i : remove ) { luckyList.remove(i); } start++; } return luckyList; } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #define LUCKY_SIZE 60000 int luckyOdd[LUCKY_SIZE]; int luckyEven[LUCKY_SIZE]; void compactLucky(int luckyArray[]) { int i, j, k; for (i = 0; i < LUCKY_SIZE; i++) { if (luckyArray[i] == 0) { j = i; break; } } for (j = i + 1; j < LUCKY_SIZE; j++) { if (luckyArray[j] > 0) { luckyArray[i++] = luckyArray[j]; } } for (; i < LUCKY_SIZE; i++) { luckyArray[i] = 0; } } void initialize() { int i, j; for (i = 0; i < LUCKY_SIZE; i++) { luckyEven[i] = 2 * i + 2; luckyOdd[i] = 2 * i + 1; } for (i = 1; i < LUCKY_SIZE; i++) { if (luckyOdd[i] > 0) { for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) { luckyOdd[j] = 0; } compactLucky(luckyOdd); } } for (i = 1; i < LUCKY_SIZE; i++) { if (luckyEven[i] > 0) { for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) { luckyEven[j] = 0; } compactLucky(luckyEven); } } } void printBetween(size_t j, size_t k, bool even) { int i; if (even) { if (luckyEven[j] == 0 || luckyEven[k] == 0) { fprintf(stderr, "At least one argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even numbers between %d and %d are:", j, k); for (i = 0; luckyEven[i] != 0; i++) { if (luckyEven[i] > k) { break; } if (luckyEven[i] > j) { printf(" %d", luckyEven[i]); } } } else { if (luckyOdd[j] == 0 || luckyOdd[k] == 0) { fprintf(stderr, "At least one argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky numbers between %d and %d are:", j, k); for (i = 0; luckyOdd[i] != 0; i++) { if (luckyOdd[i] > k) { break; } if (luckyOdd[i] > j) { printf(" %d", luckyOdd[i]); } } } printf("\n"); } void printRange(size_t j, size_t k, bool even) { int i; if (even) { if (luckyEven[k] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even numbers %d to %d are:", j, k); for (i = j - 1; i < k; i++) { printf(" %d", luckyEven[i]); } } else { if (luckyOdd[k] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky numbers %d to %d are:", j, k); for (i = j - 1; i < k; i++) { printf(" %d", luckyOdd[i]); } } printf("\n"); } void printSingle(size_t j, bool even) { if (even) { if (luckyEven[j] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even number %d=%d\n", j, luckyEven[j - 1]); } else { if (luckyOdd[j] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky number %d=%d\n", j, luckyOdd[j - 1]); } } void help() { printf("./lucky j [k] [--lucky|--evenLucky]\n"); printf("\n"); printf(" argument(s) | what is displayed\n"); printf("==============================================\n"); printf("-j=m | mth lucky number\n"); printf("-j=m --lucky | mth lucky number\n"); printf("-j=m --evenLucky | mth even lucky number\n"); printf("-j=m -k=n | mth through nth (inclusive) lucky numbers\n"); printf("-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n"); printf("-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n"); printf("-j=m -k=-n | all lucky numbers in the range [m, n]\n"); printf("-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n"); printf("-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n"); } void process(int argc, char *argv[]) { bool evenLucky = false; int j = 0; int k = 0; bool good = false; int i; for (i = 1; i < argc; ++i) { if ('-' == argv[i][0]) { if ('-' == argv[i][1]) { if (0 == strcmp("--lucky", argv[i])) { evenLucky = false; } else if (0 == strcmp("--evenLucky", argv[i])) { evenLucky = true; } else { fprintf(stderr, "Unknown long argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } else { if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) { good = true; j = atoi(&argv[i][3]); } else if ('k' == argv[i][1] && '=' == argv[i][2]) { k = atoi(&argv[i][3]); } else { fprintf(stderr, "Unknown short argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } } else { fprintf(stderr, "Unknown argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } if (!good) { help(); exit(EXIT_FAILURE); } if (k > 0) { printRange(j, k, evenLucky); } else if (k < 0) { printBetween(j, -k, evenLucky); } else { printSingle(j, evenLucky); } } void test() { printRange(1, 20, false); printRange(1, 20, true); printBetween(6000, 6100, false); printBetween(6000, 6100, true); printSingle(10000, false); printSingle(10000, true); } int main(int argc, char *argv[]) { initialize(); if (argc < 2) { help(); return 1; } process(argc, argv); return 0; }
Generate an equivalent C version of this Java code.
public protected private static public void function(int x){ int y; { int z; } }
int a; static int p; extern float v; int code(int arg) { int myp; static int myc; } static void code2(void) { v = v * 1.02; }
Ensure the translated C code behaves exactly like the original Java snippet.
import java.io.*; import java.text.*; import java.util.*; public class SimpleDatabase { final static String filename = "simdb.csv"; public static void main(String[] args) { if (args.length < 1 || args.length > 3) { printUsage(); return; } switch (args[0].toLowerCase()) { case "add": addItem(args); break; case "latest": printLatest(args); break; case "all": printAll(); break; default: printUsage(); break; } } private static class Item implements Comparable<Item>{ final String name; final String date; final String category; Item(String n, String d, String c) { name = n; date = d; category = c; } @Override public int compareTo(Item item){ return date.compareTo(item.date); } @Override public String toString() { return String.format("%s,%s,%s%n", name, date, category); } } private static void addItem(String[] input) { if (input.length < 2) { printUsage(); return; } List<Item> db = load(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf.format(new Date()); String cat = (input.length == 3) ? input[2] : "none"; db.add(new Item(input[1], date, cat)); store(db); } private static void printLatest(String[] a) { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); if (a.length == 2) { for (Item item : db) if (item.category.equals(a[1])) System.out.println(item); } else { System.out.println(db.get(0)); } } private static void printAll() { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); for (Item item : db) System.out.println(item); } private static List<Item> load() { List<Item> db = new ArrayList<>(); try (Scanner sc = new Scanner(new File(filename))) { while (sc.hasNext()) { String[] item = sc.nextLine().split(","); db.add(new Item(item[0], item[1], item[2])); } } catch (IOException e) { System.out.println(e); } return db; } private static void store(List<Item> db) { try (FileWriter fw = new FileWriter(filename)) { for (Item item : db) fw.write(item.toString()); } catch (IOException e) { System.out.println(e); } } private static void printUsage() { System.out.println("Usage:"); System.out.println(" simdb cmd [categoryName]"); System.out.println(" add add item, followed by optional category"); System.out.println(" latest print last added item(s), followed by " + "optional category"); System.out.println(" all print all"); System.out.println(" For instance: add \"some item name\" " + "\"some category name\""); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define _XOPEN_SOURCE #define __USE_XOPEN #include <time.h> #define DB "database.csv" #define TRY(a) if (!(a)) {perror(#a);exit(1);} #define TRY2(a) if((a)<0) {perror(#a);exit(1);} #define FREE(a) if(a) {free(a);a=NULL;} #define sort_by(foo) \ static int by_##foo (const void*p1, const void*p2) { \ return strcmp ((*(const pdb_t*)p1)->foo, (*(const pdb_t*)p2)->foo); } typedef struct db { char title[26]; char first_name[26]; char last_name[26]; time_t date; char publ[100]; struct db *next; } db_t,*pdb_t; typedef int (sort)(const void*, const void*); enum {CREATE,PRINT,TITLE,DATE,AUTH,READLINE,READ,SORT,DESTROY}; static pdb_t dao (int cmd, FILE *f, pdb_t db, sort sortby); static char *time2str (time_t *time); static time_t str2time (char *date); sort_by(last_name); sort_by(title); static int by_date(pdb_t *p1, pdb_t *p2); int main (int argc, char **argv) { char buf[100]; const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; db_t db; db.next=NULL; pdb_t dblist; int i; FILE *f; TRY (f=fopen(DB,"a+")); if (argc<2) { usage: printf ("Usage: %s [commands]\n" "-c Create new entry.\n" "-p Print the latest entry.\n" "-t Print all entries sorted by title.\n" "-d Print all entries sorted by date.\n" "-a Print all entries sorted by author.\n",argv[0]); fclose (f); return 0; } for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++); switch (i) { case CREATE: printf("-c Create a new entry.\n"); printf("Title  :");if((scanf(" %25[^\n]",db.title ))<0)break; printf("Author Firstname:");if((scanf(" %25[^\n]",db.first_name))<0)break; printf("Author Lastname :");if((scanf(" %25[^\n]",db.last_name ))<0)break; printf("Date 10-12-2000 :");if((scanf(" %10[^\n]",buf ))<0)break; printf("Publication  :");if((scanf(" %99[^\n]",db.publ ))<0)break; db.date=str2time (buf); dao (CREATE,f,&db,NULL); break; case PRINT: printf ("-p Print the latest entry.\n"); while (!feof(f)) dao (READLINE,f,&db,NULL); dao (PRINT,f,&db,NULL); break; case TITLE: printf ("-t Print all entries sorted by title.\n"); dblist = dao (READ,f,&db,NULL); dblist = dao (SORT,f,dblist,by_title); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; case DATE: printf ("-d Print all entries sorted by date.\n"); dblist = dao (READ,f,&db,NULL); dblist = dao (SORT,f,dblist,(int (*)(const void *,const void *)) by_date); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; case AUTH: printf ("-a Print all entries sorted by author.\n"); dblist = dao (READ,f,&db,NULL); dblist = dao (SORT,f,dblist,by_last_name); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; default: { printf ("Unknown command: %s.\n",strlen(argv[1])<10?argv[1]:""); goto usage; } } fclose (f); return 0; } static pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) { pdb_t *pdb=NULL,rec=NULL,hd=NULL; int i=0,ret; char buf[100]; switch (cmd) { case CREATE: fprintf (f,"\"%s\",",in_db->title); fprintf (f,"\"%s\",",in_db->first_name); fprintf (f,"\"%s\",",in_db->last_name); fprintf (f,"\"%s\",",time2str(&in_db->date)); fprintf (f,"\"%s\" \n",in_db->publ); break; case PRINT: for (;in_db;i++) { printf ("Title  : %s\n", in_db->title); printf ("Author  : %s %s\n", in_db->first_name, in_db->last_name); printf ("Date  : %s\n", time2str(&in_db->date)); printf ("Publication : %s\n\n", in_db->publ); if (!((i+1)%3)) { printf ("Press Enter to continue.\n"); ret = scanf ("%*[^\n]"); if (ret<0) return rec; else getchar(); } in_db=in_db->next; } break; case READLINE: if((fscanf(f," \"%[^\"]\",",in_db->title ))<0)break; if((fscanf(f," \"%[^\"]\",",in_db->first_name))<0)break; if((fscanf(f," \"%[^\"]\",",in_db->last_name ))<0)break; if((fscanf(f," \"%[^\"]\",",buf ))<0)break; if((fscanf(f," \"%[^\"]\" ",in_db->publ ))<0)break; in_db->date=str2time (buf); break; case READ: while (!feof(f)) { dao (READLINE,f,in_db,NULL); TRY (rec=malloc(sizeof(db_t))); *rec=*in_db; rec->next=hd; hd=rec;i++; } if (i<2) { puts ("Empty database. Please create some entries."); fclose (f); exit (0); } break; case SORT: rec=in_db; for (;in_db;i++) in_db=in_db->next; TRY (pdb=malloc(i*sizeof(pdb_t))); in_db=rec; for (i=0;in_db;i++) { pdb[i]=in_db; in_db=in_db->next; } qsort (pdb,i,sizeof in_db,sortby); pdb[i-1]->next=NULL; for (i=i-1;i;i--) { pdb[i-1]->next=pdb[i]; } rec=pdb[0]; FREE (pdb); pdb=NULL; break; case DESTROY: { while ((rec=in_db)) { in_db=in_db->next; FREE (rec); } } } return rec; } static char *time2str (time_t *time) { static char buf[255]; struct tm *ptm; ptm=localtime (time); strftime(buf, 255, "%m-%d-%Y", ptm); return buf; } static time_t str2time (char *date) { struct tm tm; memset (&tm, 0, sizeof(struct tm)); strptime(date, "%m-%d-%Y", &tm); return mktime(&tm); } static int by_date (pdb_t *p1, pdb_t *p2) { if ((*p1)->date < (*p2)->date) { return -1; } else return ((*p1)->date > (*p2)->date); }
Produce a functionally identical C code for the snippet given in Java.
public class CirclesTotalArea { private static double distSq(double x1, double y1, double x2, double y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) { double r2 = circ[2] * circ[2]; return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2; } private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) { if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] && rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; } double r2 = circ[2] + Math.max(rect[2], rect[3]); r2 = r2 * r2; return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2; } private static boolean[] surelyOutside; private static double totalArea(double[] rect, double[][] circs, int d) { int surelyOutsideCount = 0; for(int i = 0; i < circs.length; i++) { if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; } if(rectangleSurelyOutsideCircle(rect, circs[i])) { surelyOutside[i] = true; surelyOutsideCount++; } else { surelyOutside[i] = false; } } if(surelyOutsideCount == circs.length) { return 0; } if(d < 1) { return rect[2] * rect[3] / 3; } if(surelyOutsideCount > 0) { double[][] newCircs = new double[circs.length - surelyOutsideCount][3]; int loc = 0; for(int i = 0; i < circs.length; i++) { if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; } } circs = newCircs; } double w = rect[2] / 2; double h = rect[3] / 2; double[][] pieces = { { rect[0], rect[1], w, h }, { rect[0] + w, rect[1], w, h }, { rect[0], rect[1] - h, w, h }, { rect[0] + w, rect[1] - h, w, h } }; double total = 0; for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); } return total; } public static double totalArea(double[][] circs, int d) { double maxx = Double.NEGATIVE_INFINITY; double minx = Double.POSITIVE_INFINITY; double maxy = Double.NEGATIVE_INFINITY; double miny = Double.POSITIVE_INFINITY; for(double[] circ: circs) { if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; } if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; } if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; } if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; } } double[] rect = { minx, maxy, maxx - minx, maxy - miny }; surelyOutside = new boolean[circs.length]; return totalArea(rect, circs, d); } public static void main(String[] args) { double[][] circs = { { 1.6417233788, 1.6121789534, 0.0848270516 }, {-1.4944608174, 1.2077959613, 1.1039549836 }, { 0.6110294452, -0.6907087527, 0.9089162485 }, { 0.3844862411, 0.2923344616, 0.2375743054 }, {-0.2495892950, -0.3832854473, 1.0845181219 }, {1.7813504266, 1.6178237031, 0.8162655711 }, {-0.1985249206, -0.8343333301, 0.0538864941 }, {-1.7011985145, -0.1263820964, 0.4776976918 }, {-0.4319462812, 1.4104420482, 0.7886291537 }, {0.2178372997, -0.9499557344, 0.0357871187 }, {-0.6294854565, -1.3078893852, 0.7653357688 }, {1.7952608455, 0.6281269104, 0.2727652452 }, {1.4168575317, 1.0683357171, 1.1016025378 }, {1.4637371396, 0.9463877418, 1.1846214562 }, {-0.5263668798, 1.7315156631, 1.4428514068 }, {-1.2197352481, 0.9144146579, 1.0727263474 }, {-0.1389358881, 0.1092805780, 0.7350208828 }, {1.5293954595, 0.0030278255, 1.2472867347 }, {-0.5258728625, 1.3782633069, 1.3495508831 }, {-0.1403562064, 0.2437382535, 1.3804956588 }, {0.8055826339, -0.0482092025, 0.3327165165 }, {-0.6311979224, 0.7184578971, 0.2491045282 }, {1.4685857879, -0.8347049536, 1.3670667538 }, {-0.6855727502, 1.6465021616, 1.0593087096 }, {0.0152957411, 0.0638919221, 0.9771215985 } }; double ans = totalArea(circs, 24); System.out.println("Approx. area is " + ans); System.out.println("Error is " + Math.abs(21.56503660 - ans)); } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdbool.h> typedef double Fp; typedef struct { Fp x, y, r; } Circle; Circle circles[] = { { 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}; const size_t n_circles = sizeof(circles) / sizeof(Circle); static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } static inline Fp sq(const Fp a) { return a * a; } static inline double uniform(const double a, const double b) { const double r01 = rand() / (double)RAND_MAX; return a + (b - a) * r01; } static inline bool is_inside_circles(const Fp x, const Fp y) { for (size_t i = 0; i < n_circles; i++) if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) return true; return false; } int main() { Fp x_min = INFINITY, x_max = -INFINITY; Fp y_min = x_min, y_max = x_max; for (size_t i = 0; i < n_circles; i++) { Circle *c = &circles[i]; x_min = min(x_min, c->x - c->r); x_max = max(x_max, c->x + c->r); y_min = min(y_min, c->y - c->r); y_max = max(y_max, c->y + c->r); c->r *= c->r; } const Fp bbox_area = (x_max - x_min) * (y_max - y_min); srand(time(0)); size_t to_try = 1U << 16; size_t n_tries = 0; size_t n_hits = 0; while (true) { n_hits += is_inside_circles(uniform(x_min, x_max), uniform(y_min, y_max)); n_tries++; if (n_tries == to_try) { const Fp area = bbox_area * n_hits / n_tries; const Fp r = (Fp)n_hits / n_tries; const Fp s = area * sqrt(r * (1 - r) / n_tries); printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries); if (s * 3 <= 1e-3) break; to_try *= 2; } } return 0; }
Write the same code in C as shown below in Java.
public class CirclesTotalArea { private static double distSq(double x1, double y1, double x2, double y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) { double r2 = circ[2] * circ[2]; return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2; } private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) { if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] && rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; } double r2 = circ[2] + Math.max(rect[2], rect[3]); r2 = r2 * r2; return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2; } private static boolean[] surelyOutside; private static double totalArea(double[] rect, double[][] circs, int d) { int surelyOutsideCount = 0; for(int i = 0; i < circs.length; i++) { if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; } if(rectangleSurelyOutsideCircle(rect, circs[i])) { surelyOutside[i] = true; surelyOutsideCount++; } else { surelyOutside[i] = false; } } if(surelyOutsideCount == circs.length) { return 0; } if(d < 1) { return rect[2] * rect[3] / 3; } if(surelyOutsideCount > 0) { double[][] newCircs = new double[circs.length - surelyOutsideCount][3]; int loc = 0; for(int i = 0; i < circs.length; i++) { if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; } } circs = newCircs; } double w = rect[2] / 2; double h = rect[3] / 2; double[][] pieces = { { rect[0], rect[1], w, h }, { rect[0] + w, rect[1], w, h }, { rect[0], rect[1] - h, w, h }, { rect[0] + w, rect[1] - h, w, h } }; double total = 0; for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); } return total; } public static double totalArea(double[][] circs, int d) { double maxx = Double.NEGATIVE_INFINITY; double minx = Double.POSITIVE_INFINITY; double maxy = Double.NEGATIVE_INFINITY; double miny = Double.POSITIVE_INFINITY; for(double[] circ: circs) { if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; } if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; } if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; } if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; } } double[] rect = { minx, maxy, maxx - minx, maxy - miny }; surelyOutside = new boolean[circs.length]; return totalArea(rect, circs, d); } public static void main(String[] args) { double[][] circs = { { 1.6417233788, 1.6121789534, 0.0848270516 }, {-1.4944608174, 1.2077959613, 1.1039549836 }, { 0.6110294452, -0.6907087527, 0.9089162485 }, { 0.3844862411, 0.2923344616, 0.2375743054 }, {-0.2495892950, -0.3832854473, 1.0845181219 }, {1.7813504266, 1.6178237031, 0.8162655711 }, {-0.1985249206, -0.8343333301, 0.0538864941 }, {-1.7011985145, -0.1263820964, 0.4776976918 }, {-0.4319462812, 1.4104420482, 0.7886291537 }, {0.2178372997, -0.9499557344, 0.0357871187 }, {-0.6294854565, -1.3078893852, 0.7653357688 }, {1.7952608455, 0.6281269104, 0.2727652452 }, {1.4168575317, 1.0683357171, 1.1016025378 }, {1.4637371396, 0.9463877418, 1.1846214562 }, {-0.5263668798, 1.7315156631, 1.4428514068 }, {-1.2197352481, 0.9144146579, 1.0727263474 }, {-0.1389358881, 0.1092805780, 0.7350208828 }, {1.5293954595, 0.0030278255, 1.2472867347 }, {-0.5258728625, 1.3782633069, 1.3495508831 }, {-0.1403562064, 0.2437382535, 1.3804956588 }, {0.8055826339, -0.0482092025, 0.3327165165 }, {-0.6311979224, 0.7184578971, 0.2491045282 }, {1.4685857879, -0.8347049536, 1.3670667538 }, {-0.6855727502, 1.6465021616, 1.0593087096 }, {0.0152957411, 0.0638919221, 0.9771215985 } }; double ans = totalArea(circs, 24); System.out.println("Approx. area is " + ans); System.out.println("Error is " + Math.abs(21.56503660 - ans)); } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdbool.h> typedef double Fp; typedef struct { Fp x, y, r; } Circle; Circle circles[] = { { 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}; const size_t n_circles = sizeof(circles) / sizeof(Circle); static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } static inline Fp sq(const Fp a) { return a * a; } static inline double uniform(const double a, const double b) { const double r01 = rand() / (double)RAND_MAX; return a + (b - a) * r01; } static inline bool is_inside_circles(const Fp x, const Fp y) { for (size_t i = 0; i < n_circles; i++) if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) return true; return false; } int main() { Fp x_min = INFINITY, x_max = -INFINITY; Fp y_min = x_min, y_max = x_max; for (size_t i = 0; i < n_circles; i++) { Circle *c = &circles[i]; x_min = min(x_min, c->x - c->r); x_max = max(x_max, c->x + c->r); y_min = min(y_min, c->y - c->r); y_max = max(y_max, c->y + c->r); c->r *= c->r; } const Fp bbox_area = (x_max - x_min) * (y_max - y_min); srand(time(0)); size_t to_try = 1U << 16; size_t n_tries = 0; size_t n_hits = 0; while (true) { n_hits += is_inside_circles(uniform(x_min, x_max), uniform(y_min, y_max)); n_tries++; if (n_tries == to_try) { const Fp area = bbox_area * n_hits / n_tries; const Fp r = (Fp)n_hits / n_tries; const Fp s = area * sqrt(r * (1 - r) / n_tries); printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries); if (s * 3 <= 1e-3) break; to_try *= 2; } } return 0; }
Change the following Java code into C without altering its purpose.
import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.*; public class HoughTransform { public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast) { int width = inputData.width; int height = inputData.height; int maxRadius = (int)Math.ceil(Math.hypot(width, height)); int halfRAxisSize = rAxisSize >>> 1; ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize); double[] sinTable = new double[thetaAxisSize]; double[] cosTable = new double[thetaAxisSize]; for (int theta = thetaAxisSize - 1; theta >= 0; theta--) { double thetaRadians = theta * Math.PI / thetaAxisSize; sinTable[theta] = Math.sin(thetaRadians); cosTable[theta] = Math.cos(thetaRadians); } for (int y = height - 1; y >= 0; y--) { for (int x = width - 1; x >= 0; x--) { if (inputData.contrast(x, y, minContrast)) { for (int theta = thetaAxisSize - 1; theta >= 0; theta--) { double r = cosTable[theta] * x + sinTable[theta] * y; int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize; outputData.accumulate(theta, rScaled, 1); } } } } return outputData; } public static class ArrayData { public final int[] dataArray; public final int width; public final int height; public ArrayData(int width, int height) { this(new int[width * height], width, height); } public ArrayData(int[] dataArray, int width, int height) { this.dataArray = dataArray; this.width = width; this.height = height; } public int get(int x, int y) { return dataArray[y * width + x]; } public void set(int x, int y, int value) { dataArray[y * width + x] = value; } public void accumulate(int x, int y, int delta) { set(x, y, get(x, y) + delta); } public boolean contrast(int x, int y, int minContrast) { int centerValue = get(x, y); for (int i = 8; i >= 0; i--) { if (i == 4) continue; int newx = x + (i % 3) - 1; int newy = y + (i / 3) - 1; if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height)) continue; if (Math.abs(get(newx, newy) - centerValue) >= minContrast) return true; } return false; } public int getMax() { int max = dataArray[0]; for (int i = width * height - 1; i > 0; i--) if (dataArray[i] > max) max = dataArray[i]; return max; } } public static ArrayData getArrayDataFromImage(String filename) throws IOException { BufferedImage inputImage = ImageIO.read(new File(filename)); int width = inputImage.getWidth(); int height = inputImage.getHeight(); int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width); ArrayData arrayData = new ArrayData(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgbValue = rgbData[y * width + x]; rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11); arrayData.set(x, height - 1 - y, rgbValue); } } return arrayData; } public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException { int max = arrayData.getMax(); BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < arrayData.height; y++) { for (int x = 0; x < arrayData.width; x++) { int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255); outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000); } } ImageIO.write(outputImage, "PNG", new File(filename)); return; } public static void main(String[] args) throws IOException { ArrayData inputData = getArrayDataFromImage(args[0]); int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]); ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast); writeOutputImage(args[1], outputData); return; } }
#include "SL_Generated.h" #include "CImg.h" using namespace cimg_library; int main( int argc, char** argv ) { string fileName = "Pentagon.bmp"; if(argc > 1) fileName = argv[1]; int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]); int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]); int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]); int threads = 0; if(argc > 5) threads = atoi(argv[5]); char titleBuffer[200]; SLTimer t; CImg<int> image(fileName.c_str()); int imageDimensions[] = {image.height(), image.width(), 0}; Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions); Sequence< Sequence<int> > result; sl_init(threads); t.start(); sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result); t.stop(); CImg<int> resultImage(result[1].size(), result.size()); for(int y = 0; y < result.size(); y++) for(int x = 0; x < result[y+1].size(); x++) resultImage(x,result.size() - 1 - y) = result[y+1][x+1]; sprintf(titleBuffer, "SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\0", image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime()); resultImage.display(titleBuffer); sl_done(); return 0; }
Write the same algorithm in C as shown in this Java implementation.
import static java.lang.Math.pow; import java.util.Arrays; import static java.util.Arrays.stream; import org.apache.commons.math3.special.Gamma; public class Test { static double x2Dist(double[] data) { double avg = stream(data).sum() / data.length; double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2)); return sqs / avg; } static double x2Prob(double dof, double distance) { return Gamma.regularizedGammaQ(dof / 2, distance / 2); } static boolean x2IsUniform(double[] data, double significance) { return x2Prob(data.length - 1.0, x2Dist(data)) > significance; } public static void main(String[] a) { double[][] dataSets = {{199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}}; System.out.printf(" %4s %12s %12s %8s %s%n", "dof", "distance", "probability", "Uniform?", "dataset"); for (double[] ds : dataSets) { int dof = ds.length - 1; double dist = x2Dist(ds); double prob = x2Prob(dof, dist); System.out.printf("%4d %12.3f %12.8f %5s %6s%n", dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO", Arrays.toString(ds)); } } }
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif typedef double (* Ifctn)( double t); double Simpson3_8( Ifctn f, double a, double b, int N) { int j; double l1; double h = (b-a)/N; double h1 = h/3.0; double sum = f(a) + f(b); for (j=3*N-1; j>0; j--) { l1 = (j%3)? 3.0 : 2.0; sum += l1*f(a+h1*j) ; } return h*sum/8.0; } #define A 12 double Gamma_Spouge( double z ) { int k; static double cspace[A]; static double *coefs = NULL; double accum; double a = A; if (!coefs) { double k1_factrl = 1.0; coefs = cspace; coefs[0] = sqrt(2.0*M_PI); for(k=1; k<A; k++) { coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl; k1_factrl *= -k; } } accum = coefs[0]; for (k=1; k<A; k++) { accum += coefs[k]/(z+k); } accum *= exp(-(z+a)) * pow(z+a, z+0.5); return accum/z; } double aa1; double f0( double t) { return pow(t, aa1)*exp(-t); } double GammaIncomplete_Q( double a, double x) { double y, h = 1.5e-2; y = aa1 = a-1; while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4; if (y>x) y=x; return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); }
Convert this Java snippet to C and keep its semantics consistent.
import org.apache.commons.math3.distribution.TDistribution; public class WelchTTest { public static double[] meanvar(double[] a) { double m = 0.0, v = 0.0; int n = a.length; for (double x: a) { m += x; } m /= n; for (double x: a) { v += (x - m) * (x - m); } v /= (n - 1); return new double[] {m, v}; } public static double[] welch_ttest(double[] x, double[] y) { double mx, my, vx, vy, t, df, p; double[] res; int nx = x.length, ny = y.length; res = meanvar(x); mx = res[0]; vx = res[1]; res = meanvar(y); my = res[0]; vy = res[1]; t = (mx-my)/Math.sqrt(vx/nx+vy/ny); df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1))); TDistribution dist = new TDistribution(df); p = 2.0*dist.cumulativeProbability(-Math.abs(t)); return new double[] {t, df, p}; } public static void main(String[] args) { double x[] = {3.0, 4.0, 1.0, 2.1}; double y[] = {490.2, 340.0, 433.9}; double res[] = welch_ttest(x, y); System.out.println("t = " + res[0]); System.out.println("df = " + res[1]); System.out.println("p = " + res[2]); } }
#include <stdio.h> #include <math.h> #include <stdlib.h> double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) { if (ARRAY1_SIZE <= 1) { return 1.0; } else if (ARRAY2_SIZE <= 1) { return 1.0; } double fmean1 = 0.0, fmean2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { if (isfinite(ARRAY1[x]) == 0) { puts("Got a non-finite number in 1st array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean1 += ARRAY1[x]; } fmean1 /= ARRAY1_SIZE; for (size_t x = 0; x < ARRAY2_SIZE; x++) { if (isfinite(ARRAY2[x]) == 0) { puts("Got a non-finite number in 2nd array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean2 += ARRAY2[x]; } fmean2 /= ARRAY2_SIZE; if (fmean1 == fmean2) { return 1.0; } double unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { unbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1); } for (size_t x = 0; x < ARRAY2_SIZE; x++) { unbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2); } unbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1); unbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1); const double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE); const double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0) / ( (unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+ (unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1)) ); const double a = DEGREES_OF_FREEDOM/2; double value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM); if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } const double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5); const double acu = 0.1E-14; double ai; double cx; int indx; int ns; double pp; double psq; double qq; double rx; double temp; double term; double xx; if ( (a <= 0.0)) { } if ( value < 0.0 || 1.0 < value ) { return value; } if ( value == 0.0 || value == 1.0 ) { return value; } psq = a + 0.5; cx = 1.0 - value; if ( a < psq * value ) { xx = cx; cx = value; pp = 0.5; qq = a; indx = 1; } else { xx = value; pp = a; qq = 0.5; indx = 0; } term = 1.0; ai = 1.0; value = 1.0; ns = ( int ) ( qq + cx * psq ); rx = xx / cx; temp = qq - ai; if ( ns == 0 ) { rx = xx; } for ( ; ; ) { term = term * temp * rx / ( pp + ai ); value = value + term;; temp = fabs ( term ); if ( temp <= acu && temp <= acu * value ) { value = value * exp ( pp * log ( xx ) + ( qq - 1.0 ) * log ( cx ) - beta ) / pp; if ( indx ) { value = 1.0 - value; } break; } ai = ai + 1.0; ns = ns - 1; if ( 0 <= ns ) { temp = qq - ai; if ( ns == 0 ) { rx = xx; } } else { temp = psq; psq = psq + 1.0; } } return value; } int main(void) { const double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4}; const double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4}; const double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8}; const double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8}; const double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0}; const double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2}; const double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99}; const double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98}; const double x[] = {3.0,4.0,1.0,2.1}; const double y[] = {490.2,340.0,433.9}; const double v1[] = {0.010268,0.000167,0.000167}; const double v2[] = {0.159258,0.136278,0.122389}; const double s1[] = {1.0/15,10.0/62.0}; const double s2[] = {1.0/10,2/50.0}; const double z1[] = {9/23.0,21/45.0,0/38.0}; const double z2[] = {0/44.0,42/94.0,0/22.0}; const double CORRECT_ANSWERS[] = {0.021378001462867, 0.148841696605327, 0.0359722710297968, 0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794}; double pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2)); double error = fabs(pvalue - CORRECT_ANSWERS[0]); printf("Test sets 1 p-value = %g\n", pvalue); pvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4)); error += fabs(pvalue - CORRECT_ANSWERS[1]); printf("Test sets 2 p-value = %g\n",pvalue); pvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6)); error += fabs(pvalue - CORRECT_ANSWERS[2]); printf("Test sets 3 p-value = %g\n", pvalue); pvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8)); printf("Test sets 4 p-value = %g\n", pvalue); error += fabs(pvalue - CORRECT_ANSWERS[3]); pvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y)); error += fabs(pvalue - CORRECT_ANSWERS[4]); printf("Test sets 5 p-value = %g\n", pvalue); pvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2)); error += fabs(pvalue - CORRECT_ANSWERS[5]); printf("Test sets 6 p-value = %g\n", pvalue); pvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2)); error += fabs(pvalue - CORRECT_ANSWERS[6]); printf("Test sets 7 p-value = %g\n", pvalue); pvalue = Pvalue(z1, 3, z2, 3); error += fabs(pvalue - CORRECT_ANSWERS[7]); printf("Test sets z p-value = %g\n", pvalue); printf("the cumulative error is %g\n", error); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Java version.
import org.apache.commons.math3.distribution.TDistribution; public class WelchTTest { public static double[] meanvar(double[] a) { double m = 0.0, v = 0.0; int n = a.length; for (double x: a) { m += x; } m /= n; for (double x: a) { v += (x - m) * (x - m); } v /= (n - 1); return new double[] {m, v}; } public static double[] welch_ttest(double[] x, double[] y) { double mx, my, vx, vy, t, df, p; double[] res; int nx = x.length, ny = y.length; res = meanvar(x); mx = res[0]; vx = res[1]; res = meanvar(y); my = res[0]; vy = res[1]; t = (mx-my)/Math.sqrt(vx/nx+vy/ny); df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1))); TDistribution dist = new TDistribution(df); p = 2.0*dist.cumulativeProbability(-Math.abs(t)); return new double[] {t, df, p}; } public static void main(String[] args) { double x[] = {3.0, 4.0, 1.0, 2.1}; double y[] = {490.2, 340.0, 433.9}; double res[] = welch_ttest(x, y); System.out.println("t = " + res[0]); System.out.println("df = " + res[1]); System.out.println("p = " + res[2]); } }
#include <stdio.h> #include <math.h> #include <stdlib.h> double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) { if (ARRAY1_SIZE <= 1) { return 1.0; } else if (ARRAY2_SIZE <= 1) { return 1.0; } double fmean1 = 0.0, fmean2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { if (isfinite(ARRAY1[x]) == 0) { puts("Got a non-finite number in 1st array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean1 += ARRAY1[x]; } fmean1 /= ARRAY1_SIZE; for (size_t x = 0; x < ARRAY2_SIZE; x++) { if (isfinite(ARRAY2[x]) == 0) { puts("Got a non-finite number in 2nd array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean2 += ARRAY2[x]; } fmean2 /= ARRAY2_SIZE; if (fmean1 == fmean2) { return 1.0; } double unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { unbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1); } for (size_t x = 0; x < ARRAY2_SIZE; x++) { unbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2); } unbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1); unbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1); const double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE); const double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0) / ( (unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+ (unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1)) ); const double a = DEGREES_OF_FREEDOM/2; double value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM); if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } const double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5); const double acu = 0.1E-14; double ai; double cx; int indx; int ns; double pp; double psq; double qq; double rx; double temp; double term; double xx; if ( (a <= 0.0)) { } if ( value < 0.0 || 1.0 < value ) { return value; } if ( value == 0.0 || value == 1.0 ) { return value; } psq = a + 0.5; cx = 1.0 - value; if ( a < psq * value ) { xx = cx; cx = value; pp = 0.5; qq = a; indx = 1; } else { xx = value; pp = a; qq = 0.5; indx = 0; } term = 1.0; ai = 1.0; value = 1.0; ns = ( int ) ( qq + cx * psq ); rx = xx / cx; temp = qq - ai; if ( ns == 0 ) { rx = xx; } for ( ; ; ) { term = term * temp * rx / ( pp + ai ); value = value + term;; temp = fabs ( term ); if ( temp <= acu && temp <= acu * value ) { value = value * exp ( pp * log ( xx ) + ( qq - 1.0 ) * log ( cx ) - beta ) / pp; if ( indx ) { value = 1.0 - value; } break; } ai = ai + 1.0; ns = ns - 1; if ( 0 <= ns ) { temp = qq - ai; if ( ns == 0 ) { rx = xx; } } else { temp = psq; psq = psq + 1.0; } } return value; } int main(void) { const double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4}; const double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4}; const double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8}; const double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8}; const double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0}; const double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2}; const double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99}; const double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98}; const double x[] = {3.0,4.0,1.0,2.1}; const double y[] = {490.2,340.0,433.9}; const double v1[] = {0.010268,0.000167,0.000167}; const double v2[] = {0.159258,0.136278,0.122389}; const double s1[] = {1.0/15,10.0/62.0}; const double s2[] = {1.0/10,2/50.0}; const double z1[] = {9/23.0,21/45.0,0/38.0}; const double z2[] = {0/44.0,42/94.0,0/22.0}; const double CORRECT_ANSWERS[] = {0.021378001462867, 0.148841696605327, 0.0359722710297968, 0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794}; double pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2)); double error = fabs(pvalue - CORRECT_ANSWERS[0]); printf("Test sets 1 p-value = %g\n", pvalue); pvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4)); error += fabs(pvalue - CORRECT_ANSWERS[1]); printf("Test sets 2 p-value = %g\n",pvalue); pvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6)); error += fabs(pvalue - CORRECT_ANSWERS[2]); printf("Test sets 3 p-value = %g\n", pvalue); pvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8)); printf("Test sets 4 p-value = %g\n", pvalue); error += fabs(pvalue - CORRECT_ANSWERS[3]); pvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y)); error += fabs(pvalue - CORRECT_ANSWERS[4]); printf("Test sets 5 p-value = %g\n", pvalue); pvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2)); error += fabs(pvalue - CORRECT_ANSWERS[5]); printf("Test sets 6 p-value = %g\n", pvalue); pvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2)); error += fabs(pvalue - CORRECT_ANSWERS[6]); printf("Test sets 7 p-value = %g\n", pvalue); pvalue = Pvalue(z1, 3, z2, 3); error += fabs(pvalue - CORRECT_ANSWERS[7]); printf("Test sets z p-value = %g\n", pvalue); printf("the cumulative error is %g\n", error); return 0; }
Generate a C translation of this Java snippet without changing its computational steps.
import java.util.*; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; public class TopologicalSort2 { public static void main(String[] args) { String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1," + "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1"; Graph g = new Graph(s, new int[][]{ {0, 10}, {0, 2}, {0, 3}, {1, 10}, {1, 3}, {1, 4}, {2, 17}, {2, 5}, {2, 9}, {3, 6}, {3, 7}, {3, 8}, {3, 9}, {10, 11}, {10, 12}, {10, 13}, {11, 14}, {11, 15}, {13, 16}, {13, 17},}); System.out.println("Top levels: " + g.toplevels()); String[] files = {"top1", "top2", "ip1"}; for (String f : files) System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f)); } } class Graph { List<String> vertices; boolean[][] adjacency; int numVertices; public Graph(String s, int[][] edges) { vertices = asList(s.split(",")); numVertices = vertices.size(); adjacency = new boolean[numVertices][numVertices]; for (int[] edge : edges) adjacency[edge[0]][edge[1]] = true; } List<String> toplevels() { List<String> result = new ArrayList<>(); outer: for (int c = 0; c < numVertices; c++) { for (int r = 0; r < numVertices; r++) { if (adjacency[r][c]) continue outer; } result.add(vertices.get(c)); } return result; } List<String> compileOrder(String item) { LinkedList<String> result = new LinkedList<>(); LinkedList<Integer> queue = new LinkedList<>(); queue.add(vertices.indexOf(item)); while (!queue.isEmpty()) { int r = queue.poll(); for (int c = 0; c < numVertices; c++) { if (adjacency[r][c] && !queue.contains(c)) { queue.add(c); } } result.addFirst(vertices.get(r)); } return result.stream().distinct().collect(toList()); } }
char input[] = "top1 des1 ip1 ip2\n" "top2 des1 ip2 ip3\n" "ip1 extra1 ip1a ipcommon\n" "ip2 ip2a ip2b ip2c ipcommon\n" "des1 des1a des1b des1c\n" "des1a des1a1 des1a2\n" "des1c des1c1 extra1\n"; ... int find_name(item base, int len, const char *name) { int i; for (i = 0; i < len; i++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.util.*; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; public class TopologicalSort2 { public static void main(String[] args) { String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1," + "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1"; Graph g = new Graph(s, new int[][]{ {0, 10}, {0, 2}, {0, 3}, {1, 10}, {1, 3}, {1, 4}, {2, 17}, {2, 5}, {2, 9}, {3, 6}, {3, 7}, {3, 8}, {3, 9}, {10, 11}, {10, 12}, {10, 13}, {11, 14}, {11, 15}, {13, 16}, {13, 17},}); System.out.println("Top levels: " + g.toplevels()); String[] files = {"top1", "top2", "ip1"}; for (String f : files) System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f)); } } class Graph { List<String> vertices; boolean[][] adjacency; int numVertices; public Graph(String s, int[][] edges) { vertices = asList(s.split(",")); numVertices = vertices.size(); adjacency = new boolean[numVertices][numVertices]; for (int[] edge : edges) adjacency[edge[0]][edge[1]] = true; } List<String> toplevels() { List<String> result = new ArrayList<>(); outer: for (int c = 0; c < numVertices; c++) { for (int r = 0; r < numVertices; r++) { if (adjacency[r][c]) continue outer; } result.add(vertices.get(c)); } return result; } List<String> compileOrder(String item) { LinkedList<String> result = new LinkedList<>(); LinkedList<Integer> queue = new LinkedList<>(); queue.add(vertices.indexOf(item)); while (!queue.isEmpty()) { int r = queue.poll(); for (int c = 0; c < numVertices; c++) { if (adjacency[r][c] && !queue.contains(c)) { queue.add(c); } } result.addFirst(vertices.get(r)); } return result.stream().distinct().collect(toList()); } }
char input[] = "top1 des1 ip1 ip2\n" "top2 des1 ip2 ip3\n" "ip1 extra1 ip1a ipcommon\n" "ip2 ip2a ip2b ip2c ipcommon\n" "des1 des1a des1b des1c\n" "des1a des1a1 des1a2\n" "des1c des1c1 extra1\n"; ... int find_name(item base, int len, const char *name) { int i; for (i = 0; i < len; i++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
public class BraceExpansion { public static void main(String[] args) { for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) { System.out.println(); expand(s); } } public static void expand(String s) { expandR("", s, ""); } private static void expandR(String pre, String s, String suf) { int i1 = -1, i2 = 0; String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " "); StringBuilder sb = null; outer: while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) { i2 = i1 + 1; sb = new StringBuilder(s); for (int depth = 1; i2 < s.length() && depth > 0; i2++) { char c = noEscape.charAt(i2); depth = (c == '{') ? ++depth : depth; depth = (c == '}') ? --depth : depth; if (c == ',' && depth == 1) { sb.setCharAt(i2, '\u0000'); } else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1) break outer; } } if (i1 == -1) { if (suf.length() > 0) expandR(pre + s, suf, ""); else System.out.printf("%s%s%s%n", pre, s, suf); } else { for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1)) expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf); } } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 128 typedef unsigned char character; typedef character *string; typedef struct node_t node; struct node_t { enum tag_t { NODE_LEAF, NODE_TREE, NODE_SEQ, } tag; union { string str; node *root; } data; node *next; }; node *allocate_node(enum tag_t tag) { node *n = malloc(sizeof(node)); if (n == NULL) { fprintf(stderr, "Failed to allocate node for tag: %d\n", tag); exit(1); } n->tag = tag; n->next = NULL; return n; } node *make_leaf(string str) { node *n = allocate_node(NODE_LEAF); n->data.str = str; return n; } node *make_tree() { node *n = allocate_node(NODE_TREE); n->data.root = NULL; return n; } node *make_seq() { node *n = allocate_node(NODE_SEQ); n->data.root = NULL; return n; } void deallocate_node(node *n) { if (n == NULL) { return; } deallocate_node(n->next); n->next = NULL; if (n->tag == NODE_LEAF) { free(n->data.str); n->data.str = NULL; } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) { deallocate_node(n->data.root); n->data.root = NULL; } else { fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag); exit(1); } free(n); } void append(node *root, node *elem) { if (root == NULL) { fprintf(stderr, "Cannot append to uninitialized node."); exit(1); } if (elem == NULL) { return; } if (root->tag == NODE_SEQ || root->tag == NODE_TREE) { if (root->data.root == NULL) { root->data.root = elem; } else { node *it = root->data.root; while (it->next != NULL) { it = it->next; } it->next = elem; } } else { fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag); exit(1); } } size_t count(node *n) { if (n == NULL) { return 0; } if (n->tag == NODE_LEAF) { return 1; } if (n->tag == NODE_TREE) { size_t sum = 0; node *it = n->data.root; while (it != NULL) { sum += count(it); it = it->next; } return sum; } if (n->tag == NODE_SEQ) { size_t prod = 1; node *it = n->data.root; while (it != NULL) { prod *= count(it); it = it->next; } return prod; } fprintf(stderr, "Cannot count node with tag: %d\n", n->tag); exit(1); } void expand(node *n, size_t pos) { if (n == NULL) { return; } if (n->tag == NODE_LEAF) { printf(n->data.str); } else if (n->tag == NODE_TREE) { node *it = n->data.root; while (true) { size_t cnt = count(it); if (pos < cnt) { expand(it, pos); break; } pos -= cnt; it = it->next; } } else if (n->tag == NODE_SEQ) { size_t prod = pos; node *it = n->data.root; while (it != NULL) { size_t cnt = count(it); size_t rem = prod % cnt; expand(it, rem); it = it->next; } } else { fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag); exit(1); } } string allocate_string(string src) { size_t len = strlen(src); string out = calloc(len + 1, sizeof(character)); if (out == NULL) { fprintf(stderr, "Failed to allocate a copy of the string."); exit(1); } strcpy(out, src); return out; } node *parse_seq(string input, size_t *pos); node *parse_tree(string input, size_t *pos) { node *root = make_tree(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; size_t depth = 0; bool asSeq = false; bool allow = false; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = '\\'; buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { buffer[bufpos++] = c; buffer[bufpos] = 0; asSeq = true; depth++; } else if (c == '}') { if (depth-- > 0) { buffer[bufpos++] = c; buffer[bufpos] = 0; } else { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); } else { append(root, make_leaf(allocate_string(buffer))); } break; } } else if (c == ',') { if (depth == 0) { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); bufpos = 0; buffer[bufpos] = 0; asSeq = false; } else { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } return root; } node *parse_seq(string input, size_t *pos) { node *root = make_seq(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { node *tree = parse_tree(input, pos); if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } append(root, tree); } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } return root; } void test(string input) { size_t pos = 0; node *n = parse_seq(input, &pos); size_t cnt = count(n); size_t i; printf("Pattern: %s\n", input); for (i = 0; i < cnt; i++) { expand(n, i); printf("\n"); } printf("\n"); deallocate_node(n); } int main() { test("~/{Downloads,Pictures}/*.{jpg,gif,png}"); test("It{{em,alic}iz,erat}e{d,}, please."); test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!"); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
foo(); Int x = bar();
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
Rewrite the snippet below in C so it works the same as the original Java code.
foo(); Int x = bar();
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
Maintain the same structure and functionality when rewriting this code in C.
foo(); Int x = bar();
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
Write a version of this Java function in C with identical behavior.
import static java.util.stream.IntStream.rangeClosed; public class Test { final static int nMax = 12; static char[] superperm; static int pos; static int[] count = new int[nMax]; static int factSum(int n) { return rangeClosed(1, n) .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum(); } static boolean r(int n) { if (n == 0) return false; char c = superperm[pos - n]; if (--count[n] == 0) { count[n] = n; if (!r(n - 1)) return false; } superperm[pos++] = c; return true; } static void superPerm(int n) { String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; pos = n; superperm = new char[factSum(n)]; for (int i = 0; i < n + 1; i++) count[i] = i; for (int i = 1; i < n + 1; i++) superperm[i - 1] = chars.charAt(i); while (r(n)) { } } public static void main(String[] args) { for (int n = 0; n < nMax; n++) { superPerm(n); System.out.printf("superPerm(%2d) len = %d", n, superperm.length); System.out.println(); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 12 char *super = 0; int pos, cnt[MAX]; int fact_sum(int n) { int s, x, f; for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f); return s; } int r(int n) { if (!n) return 0; char c = super[pos - n]; if (!--cnt[n]) { cnt[n] = n; if (!r(n-1)) return 0; } super[pos++] = c; return 1; } void superperm(int n) { int i, len; pos = n; len = fact_sum(n); super = realloc(super, len + 1); super[len] = '\0'; for (i = 0; i <= n; i++) cnt[i] = i; for (i = 1; i <= n; i++) super[i - 1] = i + '0'; while (r(n)); } int main(void) { int n; for (n = 0; n < MAX; n++) { printf("superperm(%2d) ", n); superperm(n); printf("len = %d", (int)strlen(super)); putchar('\n'); } return 0; }
Rewrite the snippet below in C so it works the same as the original Java code.
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class Interact extends JFrame{ final JTextField numberField; final JButton incButton, randButton; public Interact(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); numberField = new JTextField(); incButton = new JButton("Increment"); randButton = new JButton("Random"); numberField.setText("0"); numberField.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { if(!Character.isDigit(e.getKeyChar())){ e.consume(); } } @Override public void keyReleased(KeyEvent e){} @Override public void keyPressed(KeyEvent e){} }); incButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String text = numberField.getText(); if(text.isEmpty()){ numberField.setText("1"); }else{ numberField.setText((Long.valueOf(text) + 1) + ""); } } }); randButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if(JOptionPane.showConfirmDialog(null, "Are you sure?") == JOptionPane.YES_OPTION){ numberField.setText(Long.toString((long)(Math.random() * Long.MAX_VALUE))); } } }); setLayout(new GridLayout(2, 1)); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, 2)); buttonPanel.add(incButton); buttonPanel.add(randButton); add(numberField); add(buttonPanel); pack(); } public static void main(String[] args){ new Interact().setVisible(true); } }
#include <windows.h> #include "resource.h" BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) { switch( msg ) { case WM_INITDIALOG: srand( GetTickCount() ); SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE ); break; case WM_COMMAND: switch( LOWORD(wPar) ) { case IDC_INCREMENT: { UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE ); SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE ); } break; case IDC_RANDOM: { int reply = MessageBox( hwnd, "Do you really want to\nget a random number?", "Random input confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE ); } break; case IDC_QUIT: SendMessage( hwnd, WM_CLOSE, 0, 0 ); break; default: ; } break; case WM_CLOSE: { int reply = MessageBox( hwnd, "Do you really want to quit?", "Quit confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) EndDialog( hwnd, 0 ); } break; default: ; } return 0; } int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) { return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc ); }
Change the programming language of this snippet from Java to C without modifying what it does.
import java.util.Arrays; import java.util.Random; public class OneOfNLines { static Random rand; public static int oneOfN(int n) { int choice = 0; for(int i = 1; i < n; i++) { if(rand.nextInt(i+1) == 0) choice = i; } return choice; } public static void main(String[] args) { int n = 10; int trials = 1000000; int[] bins = new int[n]; rand = new Random(); for(int i = 0; i < trials; i++) bins[oneOfN(n)]++; System.out.println(Arrays.toString(bins)); } }
#include <stdio.h> #include <stdlib.h> inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf("%d%c", r[i], i == 9 ? '\n':' '); return 0; }
Rewrite the snippet below in C so it works the same as the original Java code.
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; public class SelfReferentialSequence { static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000); public static void main(String[] args) { Seeds res = IntStream.range(0, 1000_000) .parallel() .mapToObj(n -> summarize(n, false)) .collect(Seeds::new, Seeds::accept, Seeds::combine); System.out.println("Seeds:"); res.seeds.forEach(e -> System.out.println(Arrays.toString(e))); System.out.println("\nSequence:"); summarize(res.seeds.get(0)[0], true); } static int[] summarize(int seed, boolean display) { String n = String.valueOf(seed); String k = Arrays.toString(n.chars().sorted().toArray()); if (!display && cache.get(k) != null) return new int[]{seed, cache.get(k)}; Set<String> seen = new HashSet<>(); StringBuilder sb = new StringBuilder(); int[] freq = new int[10]; while (!seen.contains(n)) { seen.add(n); int len = n.length(); for (int i = 0; i < len; i++) freq[n.charAt(i) - '0']++; sb.setLength(0); for (int i = 9; i >= 0; i--) { if (freq[i] != 0) { sb.append(freq[i]).append(i); freq[i] = 0; } } if (display) System.out.println(n); n = sb.toString(); } cache.put(k, seen.size()); return new int[]{seed, seen.size()}; } static class Seeds { int largest = Integer.MIN_VALUE; List<int[]> seeds = new ArrayList<>(); void accept(int[] s) { int size = s[1]; if (size >= largest) { if (size > largest) { largest = size; seeds.clear(); } seeds.add(s); } } void combine(Seeds acc) { acc.seeds.forEach(this::accept); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct rec_t rec_t; struct rec_t { int depth; rec_t * p[10]; }; rec_t root = {0, {0}}; #define USE_POOL_ALLOC #ifdef USE_POOL_ALLOC rec_t *tail = 0, *head = 0; #define POOL_SIZE (1 << 20) inline rec_t *new_rec() { if (head == tail) { head = calloc(sizeof(rec_t), POOL_SIZE); tail = head + POOL_SIZE; } return head++; } #else #define new_rec() calloc(sizeof(rec_t), 1) #endif rec_t *find_rec(char *s) { int i; rec_t *r = &root; while (*s) { i = *s++ - '0'; if (!r->p[i]) r->p[i] = new_rec(); r = r->p[i]; } return r; } char number[100][4]; void init() { int i; for (i = 0; i < 100; i++) sprintf(number[i], "%d", i); } void count(char *buf) { int i, c[10] = {0}; char *s; for (s = buf; *s; c[*s++ - '0']++); for (i = 9; i >= 0; i--) { if (!c[i]) continue; s = number[c[i]]; *buf++ = s[0]; if ((*buf = s[1])) buf++; *buf++ = i + '0'; } *buf = '\0'; } int depth(char *in, int d) { rec_t *r = find_rec(in); if (r->depth > 0) return r->depth; d++; if (!r->depth) r->depth = -d; else r->depth += d; count(in); d = depth(in, d); if (r->depth <= 0) r->depth = d + 1; return r->depth; } int main(void) { char a[100]; int i, d, best_len = 0, n_best = 0; int best_ints[32]; rec_t *r; init(); for (i = 0; i < 1000000; i++) { sprintf(a, "%d", i); d = depth(a, 0); if (d < best_len) continue; if (d > best_len) { n_best = 0; best_len = d; } if (d == best_len) best_ints[n_best++] = i; } printf("longest length: %d\n", best_len); for (i = 0; i < n_best; i++) { printf("%d\n", best_ints[i]); sprintf(a, "%d", best_ints[i]); for (d = 0; d <= best_len; d++) { r = find_rec(a); printf("%3d: %s\n", r->depth, a); count(a); } putchar('\n'); } return 0; }
Write the same algorithm in C as shown in this Java implementation.
import java.util.HashMap; import java.util.Map; public class SpellingOfOrdinalNumbers { public static void main(String[] args) { for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) { System.out.printf("%d = %s%n", test, toOrdinal(test)); } } private static Map<String,String> ordinalMap = new HashMap<>(); static { ordinalMap.put("one", "first"); ordinalMap.put("two", "second"); ordinalMap.put("three", "third"); ordinalMap.put("five", "fifth"); ordinalMap.put("eight", "eighth"); ordinalMap.put("nine", "ninth"); ordinalMap.put("twelve", "twelfth"); } private static String toOrdinal(long n) { String spelling = numToString(n); String[] split = spelling.split(" "); String last = split[split.length - 1]; String replace = ""; if ( last.contains("-") ) { String[] lastSplit = last.split("-"); String lastWithDash = lastSplit[1]; String lastReplace = ""; if ( ordinalMap.containsKey(lastWithDash) ) { lastReplace = ordinalMap.get(lastWithDash); } else if ( lastWithDash.endsWith("y") ) { lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth"; } else { lastReplace = lastWithDash + "th"; } replace = lastSplit[0] + "-" + lastReplace; } else { if ( ordinalMap.containsKey(last) ) { replace = ordinalMap.get(last); } else if ( last.endsWith("y") ) { replace = last.substring(0, last.length() - 1) + "ieth"; } else { replace = last + "th"; } } split[split.length - 1] = replace; return String.join(" ", split); } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String numToString(long n) { return numToStringHelper(n); } private static final String numToStringHelper(long n) { if ( n < 0 ) { return "negative " + numToStringHelper(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : ""); } }
#include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <glib.h> typedef uint64_t integer; typedef struct number_names_tag { const char* cardinal; const char* ordinal; } number_names; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } void append_number_name(GString* gstr, integer n, bool ordinal) { if (n < 20) g_string_append(gstr, get_small_name(&small[n], ordinal)); else if (n < 100) { if (n % 10 == 0) { g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal)); } else { g_string_append(gstr, get_small_name(&tens[n/10 - 2], false)); g_string_append_c(gstr, '-'); g_string_append(gstr, get_small_name(&small[n % 10], ordinal)); } } else { const named_number* num = get_named_number(n); integer p = num->number; append_number_name(gstr, n/p, false); g_string_append_c(gstr, ' '); if (n % p == 0) { g_string_append(gstr, get_big_name(num, ordinal)); } else { g_string_append(gstr, get_big_name(num, false)); g_string_append_c(gstr, ' '); append_number_name(gstr, n % p, ordinal); } } } GString* number_name(integer n, bool ordinal) { GString* result = g_string_sized_new(8); append_number_name(result, n, ordinal); return result; } void test_ordinal(integer n) { GString* name = number_name(n, true); printf("%llu: %s\n", n, name->str); g_string_free(name, TRUE); } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
public class SelfDescribingNumbers{ public static boolean isSelfDescribing(int a){ String s = Integer.toString(a); for(int i = 0; i < s.length(); i++){ String s0 = s.charAt(i) + ""; int b = Integer.parseInt(s0); int count = 0; for(int j = 0; j < s.length(); j++){ int temp = Integer.parseInt(s.charAt(j) + ""); if(temp == i){ count++; } if (count > b) return false; } if(count != b) return false; } return true; } public static void main(String[] args){ for(int i = 0; i < 100000000; i++){ if(isSelfDescribing(i)){ System.out.println(i); } } } }
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; } int main() { int i; for (i = 1; i < 100000000; i++) if (self_desc(i)) printf("%d\n", i); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
public class AdditionChains { private static class Pair { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } } private static int[] prepend(int n, int[] seq) { int[] result = new int[seq.length + 1]; result[0] = n; System.arraycopy(seq, 0, result, 1, seq.length); return result; } private static Pair check_seq(int pos, int[] seq, int n, int min_len) { if (pos > min_len || seq[0] > n) return new Pair(min_len, 0); else if (seq[0] == n) return new Pair(pos, 1); else if (pos < min_len) return try_perm(0, pos, seq, n, min_len); else return new Pair(min_len, 0); } private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) { if (i > pos) return new Pair(min_len, 0); Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len); Pair res2 = try_perm(i + 1, pos, seq, n, res1.f); if (res2.f < res1.f) return res2; else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s); else throw new RuntimeException("Try_perm exception"); } private static Pair init_try_perm(int x) { return try_perm(0, 0, new int[]{1}, x, 12); } private static void find_brauer(int num) { Pair res = init_try_perm(num); System.out.println(); System.out.println("N = " + num); System.out.println("Minimum length of chains: L(n)= " + res.f); System.out.println("Number of minimum length Brauer chains: " + res.s); } public static void main(String[] args) { int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; for (int i : nums) { find_brauer(i); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 typedef int bool; typedef struct { int x, y; } pair; int* example = NULL; int exampleLen = 0; void reverse(int s[], int len) { int i, j, t; for (i = 0, j = len - 1; i < j; ++i, --j) { t = s[i]; s[i] = s[j]; s[j] = t; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen); pair checkSeq(int pos, int seq[], int n, int len, int minLen) { pair p; if (pos > minLen || seq[0] > n) { p.x = minLen; p.y = 0; return p; } else if (seq[0] == n) { example = malloc(len * sizeof(int)); memcpy(example, seq, len * sizeof(int)); exampleLen = len; p.x = pos; p.y = 1; return p; } else if (pos < minLen) { return tryPerm(0, pos, seq, n, len, minLen); } else { p.x = minLen; p.y = 0; return p; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) { int *seq2; pair p, res1, res2; size_t size = sizeof(int); if (i > pos) { p.x = minLen; p.y = 0; return p; } seq2 = malloc((len + 1) * size); memcpy(seq2 + 1, seq, len * size); seq2[0] = seq[0] + seq[i]; res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen); res2 = tryPerm(i + 1, pos, seq, n, len, res1.x); free(seq2); if (res2.x < res1.x) return res2; else if (res2.x == res1.x) { p.x = res2.x; p.y = res1.y + res2.y; return p; } else { printf("Error in tryPerm\n"); p.x = 0; p.y = 0; return p; } } pair initTryPerm(int x, int minLen) { int seq[1] = {1}; return tryPerm(0, 0, seq, x, 1, minLen); } void printArray(int a[], int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]\n"); } bool isBrauer(int a[], int len) { int i, j; bool ok; for (i = 2; i < len; ++i) { ok = FALSE; for (j = i - 1; j >= 0; j--) { if (a[i-1] + a[j] == a[i]) { ok = TRUE; break; } } if (!ok) return FALSE; } return TRUE; } bool isAdditionChain(int a[], int len) { int i, j, k; bool ok, exit; for (i = 2; i < len; ++i) { if (a[i] > a[i - 1] * 2) return FALSE; ok = FALSE; exit = FALSE; for (j = i - 1; j >= 0; --j) { for (k = j; k >= 0; --k) { if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; } } if (exit) break; } if (!ok) return FALSE; } if (example == NULL && !isBrauer(a, len)) { example = malloc(len * sizeof(int)); memcpy(example, a, len * sizeof(int)); exampleLen = len; } return TRUE; } void nextChains(int index, int len, int seq[], int *pcount) { for (;;) { int i; if (index < len - 1) { nextChains(index + 1, len, seq, pcount); } if (seq[index] + len - 1 - index >= seq[len - 1]) return; seq[index]++; for (i = index + 1; i < len - 1; ++i) { seq[i] = seq[i-1] + 1; } if (isAdditionChain(seq, len)) (*pcount)++; } } int findNonBrauer(int num, int len, int brauer) { int i, count = 0; int *seq = malloc(len * sizeof(int)); seq[0] = 1; seq[len - 1] = num; for (i = 1; i < len - 1; ++i) { seq[i] = seq[i - 1] + 1; } if (isAdditionChain(seq, len)) count = 1; nextChains(2, len, seq, &count); free(seq); return count - brauer; } void findBrauer(int num, int minLen, int nbLimit) { pair p = initTryPerm(num, minLen); int actualMin = p.x, brauer = p.y, nonBrauer; printf("\nN = %d\n", num); printf("Minimum length of chains : L(%d) = %d\n", num, actualMin); printf("Number of minimum length Brauer chains : %d\n", brauer); if (brauer > 0) { printf("Brauer example : "); reverse(example, exampleLen); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } if (num <= nbLimit) { nonBrauer = findNonBrauer(num, actualMin + 1, brauer); printf("Number of minimum length non-Brauer chains : %d\n", nonBrauer); if (nonBrauer > 0) { printf("Non-Brauer example : "); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } } else { printf("Non-Brauer analysis suppressed\n"); } } int main() { int i; int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; printf("Searching for Brauer chains up to a minimum length of 12:\n"); for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
public class NumericSeparatorSyntax { public static void main(String[] args) { runTask("Underscore allowed as seperator", 1_000); runTask("Multiple consecutive underscores allowed:", 1__0_0_0); runTask("Many multiple consecutive underscores allowed:", 1________________________00); runTask("Underscores allowed in multiple positions", 1__4__4); runTask("Underscores allowed in negative number", -1__4__4); runTask("Underscores allowed in floating point number", 1__4__4e-5); runTask("Underscores allowed in floating point exponent", 1__4__440000e-1_2); } private static void runTask(String description, long n) { runTask(description, n, "%d"); } private static void runTask(String description, double n) { runTask(description, n, "%3.7f"); } private static void runTask(String description, Number n, String format) { System.out.printf("%s: " + format + "%n", description, n); } }
#include <locale.h> #include <stdio.h> int main() { unsigned long long int trillion = 1000000000000; setlocale(LC_NUMERIC,""); printf("Locale : %s, One Trillion : %'llu\n", setlocale(LC_CTYPE,NULL),trillion); return 0; }
Generate a C translation of this Java snippet without changing its computational steps.
import java.util.function.Consumer; import java.util.stream.IntStream; public class Repeat { public static void main(String[] args) { repeat(3, (x) -> System.out.println("Example " + x)); } static void repeat (int n, Consumer<Integer> fun) { IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); } }
#include <stdio.h> void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); } void example() { printf("Example\n"); } int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
Ensure the translated C code behaves exactly like the original Java snippet.
public class Sparkline { String bars="▁▂▃▄▅▆▇█"; public static void main(String[] args) { Sparkline now=new Sparkline(); float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; now.display1D(arr); System.out.println(now.getSparkline(arr)); float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; now.display1D(arr1); System.out.println(now.getSparkline(arr1)); } public void display1D(float[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public String getSparkline(float[] arr) { float min=Integer.MAX_VALUE; float max=Integer.MIN_VALUE; for(int i=0;i<arr.length;i++) { if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; } float range=max-min; int num=bars.length()-1; String line=""; for(int i=0;i<arr.length;i++) { line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num))); } return line; } }
#include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h> int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<argC;i++){ len = strlen(argV[i]); if(argV[i][len-1]==','){ str = (char*)malloc(len*sizeof(char)); strncpy(str,argV[i],len-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min); setlocale(LC_ALL, ""); for(i=1;i<argC;i++){ printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str_to_nodes = new HashMap<>(); static class Node { public NodeType nt; public Node left, right; public String value; Node() { this.nt = null; this.left = null; this.right = null; this.value = null; } Node(NodeType node_type, Node left, Node right, String value) { this.nt = node_type; this.left = left; this.right = right; this.value = value; } public static Node make_node(NodeType nodetype, Node left, Node right) { return new Node(nodetype, left, right, ""); } public static Node make_node(NodeType nodetype, Node left) { return new Node(nodetype, left, null, ""); } public static Node make_leaf(NodeType nodetype, String value) { return new Node(nodetype, null, null, value); } } static enum NodeType { nd_None(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"), nd_Sequence("Sequence"), nd_If("If"), nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"), nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"), nd_Mod("Mod"), nd_Add("Add"), nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"), nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or"); private final String name; NodeType(String name) { this.name = name; } @Override public String toString() { return this.name; } } static String str(String s) { String result = ""; int i = 0; s = s.replace("\"", ""); while (i < s.length()) { if (s.charAt(i) == '\\' && i + 1 < s.length()) { if (s.charAt(i + 1) == 'n') { result += '\n'; i += 2; } else if (s.charAt(i) == '\\') { result += '\\'; i += 2; } } else { result += s.charAt(i); i++; } } return result; } static boolean itob(int i) { return i != 0; } static int btoi(boolean b) { return b ? 1 : 0; } static int fetch_var(String name) { int result; if (globals.containsKey(name)) { result = globals.get(name); } else { globals.put(name, 0); result = 0; } return result; } static Integer interpret(Node n) throws Exception { if (n == null) { return 0; } switch (n.nt) { case nd_Integer: return Integer.parseInt(n.value); case nd_Ident: return fetch_var(n.value); case nd_String: return 1; case nd_Assign: globals.put(n.left.value, interpret(n.right)); return 0; case nd_Add: return interpret(n.left) + interpret(n.right); case nd_Sub: return interpret(n.left) - interpret(n.right); case nd_Mul: return interpret(n.left) * interpret(n.right); case nd_Div: return interpret(n.left) / interpret(n.right); case nd_Mod: return interpret(n.left) % interpret(n.right); case nd_Lss: return btoi(interpret(n.left) < interpret(n.right)); case nd_Leq: return btoi(interpret(n.left) <= interpret(n.right)); case nd_Gtr: return btoi(interpret(n.left) > interpret(n.right)); case nd_Geq: return btoi(interpret(n.left) >= interpret(n.right)); case nd_Eql: return btoi(interpret(n.left) == interpret(n.right)); case nd_Neq: return btoi(interpret(n.left) != interpret(n.right)); case nd_And: return btoi(itob(interpret(n.left)) && itob(interpret(n.right))); case nd_Or: return btoi(itob(interpret(n.left)) || itob(interpret(n.right))); case nd_Not: if (interpret(n.left) == 0) { return 1; } else { return 0; } case nd_Negate: return -interpret(n.left); case nd_If: if (interpret(n.left) != 0) { interpret(n.right.left); } else { interpret(n.right.right); } return 0; case nd_While: while (interpret(n.left) != 0) { interpret(n.right); } return 0; case nd_Prtc: System.out.printf("%c", interpret(n.left)); return 0; case nd_Prti: System.out.printf("%d", interpret(n.left)); return 0; case nd_Prts: System.out.print(str(n.left.value)); return 0; case nd_Sequence: interpret(n.left); interpret(n.right); return 0; default: throw new Exception("Error: '" + n.nt + "' found, expecting operator"); } } static Node load_ast() throws Exception { String command, value; String line; Node left, right; while (s.hasNext()) { line = s.nextLine(); value = null; if (line.length() > 16) { command = line.substring(0, 15).trim(); value = line.substring(15).trim(); } else { command = line.trim(); } if (command.equals(";")) { return null; } if (!str_to_nodes.containsKey(command)) { throw new Exception("Command not found: '" + command + "'"); } if (value != null) { return Node.make_leaf(str_to_nodes.get(command), value); } left = load_ast(); right = load_ast(); return Node.make_node(str_to_nodes.get(command), left, right); } return null; } public static void main(String[] args) { Node n; str_to_nodes.put(";", NodeType.nd_None); str_to_nodes.put("Sequence", NodeType.nd_Sequence); str_to_nodes.put("Identifier", NodeType.nd_Ident); str_to_nodes.put("String", NodeType.nd_String); str_to_nodes.put("Integer", NodeType.nd_Integer); str_to_nodes.put("If", NodeType.nd_If); str_to_nodes.put("While", NodeType.nd_While); str_to_nodes.put("Prtc", NodeType.nd_Prtc); str_to_nodes.put("Prts", NodeType.nd_Prts); str_to_nodes.put("Prti", NodeType.nd_Prti); str_to_nodes.put("Assign", NodeType.nd_Assign); str_to_nodes.put("Negate", NodeType.nd_Negate); str_to_nodes.put("Not", NodeType.nd_Not); str_to_nodes.put("Multiply", NodeType.nd_Mul); str_to_nodes.put("Divide", NodeType.nd_Div); str_to_nodes.put("Mod", NodeType.nd_Mod); str_to_nodes.put("Add", NodeType.nd_Add); str_to_nodes.put("Subtract", NodeType.nd_Sub); str_to_nodes.put("Less", NodeType.nd_Lss); str_to_nodes.put("LessEqual", NodeType.nd_Leq); str_to_nodes.put("Greater", NodeType.nd_Gtr); str_to_nodes.put("GreaterEqual", NodeType.nd_Geq); str_to_nodes.put("Equal", NodeType.nd_Eql); str_to_nodes.put("NotEqual", NodeType.nd_Neq); str_to_nodes.put("And", NodeType.nd_And); str_to_nodes.put("Or", NodeType.nd_Or); if (args.length > 0) { try { s = new Scanner(new File(args[0])); n = load_ast(); interpret(n); } catch (Exception e) { System.out.println("Ex: "+e.getMessage()); } } } }
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
Rewrite this program in C while keeping its functionality equivalent to the Java version.
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str_to_nodes = new HashMap<>(); static class Node { public NodeType nt; public Node left, right; public String value; Node() { this.nt = null; this.left = null; this.right = null; this.value = null; } Node(NodeType node_type, Node left, Node right, String value) { this.nt = node_type; this.left = left; this.right = right; this.value = value; } public static Node make_node(NodeType nodetype, Node left, Node right) { return new Node(nodetype, left, right, ""); } public static Node make_node(NodeType nodetype, Node left) { return new Node(nodetype, left, null, ""); } public static Node make_leaf(NodeType nodetype, String value) { return new Node(nodetype, null, null, value); } } static enum NodeType { nd_None(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"), nd_Sequence("Sequence"), nd_If("If"), nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"), nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"), nd_Mod("Mod"), nd_Add("Add"), nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"), nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or"); private final String name; NodeType(String name) { this.name = name; } @Override public String toString() { return this.name; } } static String str(String s) { String result = ""; int i = 0; s = s.replace("\"", ""); while (i < s.length()) { if (s.charAt(i) == '\\' && i + 1 < s.length()) { if (s.charAt(i + 1) == 'n') { result += '\n'; i += 2; } else if (s.charAt(i) == '\\') { result += '\\'; i += 2; } } else { result += s.charAt(i); i++; } } return result; } static boolean itob(int i) { return i != 0; } static int btoi(boolean b) { return b ? 1 : 0; } static int fetch_var(String name) { int result; if (globals.containsKey(name)) { result = globals.get(name); } else { globals.put(name, 0); result = 0; } return result; } static Integer interpret(Node n) throws Exception { if (n == null) { return 0; } switch (n.nt) { case nd_Integer: return Integer.parseInt(n.value); case nd_Ident: return fetch_var(n.value); case nd_String: return 1; case nd_Assign: globals.put(n.left.value, interpret(n.right)); return 0; case nd_Add: return interpret(n.left) + interpret(n.right); case nd_Sub: return interpret(n.left) - interpret(n.right); case nd_Mul: return interpret(n.left) * interpret(n.right); case nd_Div: return interpret(n.left) / interpret(n.right); case nd_Mod: return interpret(n.left) % interpret(n.right); case nd_Lss: return btoi(interpret(n.left) < interpret(n.right)); case nd_Leq: return btoi(interpret(n.left) <= interpret(n.right)); case nd_Gtr: return btoi(interpret(n.left) > interpret(n.right)); case nd_Geq: return btoi(interpret(n.left) >= interpret(n.right)); case nd_Eql: return btoi(interpret(n.left) == interpret(n.right)); case nd_Neq: return btoi(interpret(n.left) != interpret(n.right)); case nd_And: return btoi(itob(interpret(n.left)) && itob(interpret(n.right))); case nd_Or: return btoi(itob(interpret(n.left)) || itob(interpret(n.right))); case nd_Not: if (interpret(n.left) == 0) { return 1; } else { return 0; } case nd_Negate: return -interpret(n.left); case nd_If: if (interpret(n.left) != 0) { interpret(n.right.left); } else { interpret(n.right.right); } return 0; case nd_While: while (interpret(n.left) != 0) { interpret(n.right); } return 0; case nd_Prtc: System.out.printf("%c", interpret(n.left)); return 0; case nd_Prti: System.out.printf("%d", interpret(n.left)); return 0; case nd_Prts: System.out.print(str(n.left.value)); return 0; case nd_Sequence: interpret(n.left); interpret(n.right); return 0; default: throw new Exception("Error: '" + n.nt + "' found, expecting operator"); } } static Node load_ast() throws Exception { String command, value; String line; Node left, right; while (s.hasNext()) { line = s.nextLine(); value = null; if (line.length() > 16) { command = line.substring(0, 15).trim(); value = line.substring(15).trim(); } else { command = line.trim(); } if (command.equals(";")) { return null; } if (!str_to_nodes.containsKey(command)) { throw new Exception("Command not found: '" + command + "'"); } if (value != null) { return Node.make_leaf(str_to_nodes.get(command), value); } left = load_ast(); right = load_ast(); return Node.make_node(str_to_nodes.get(command), left, right); } return null; } public static void main(String[] args) { Node n; str_to_nodes.put(";", NodeType.nd_None); str_to_nodes.put("Sequence", NodeType.nd_Sequence); str_to_nodes.put("Identifier", NodeType.nd_Ident); str_to_nodes.put("String", NodeType.nd_String); str_to_nodes.put("Integer", NodeType.nd_Integer); str_to_nodes.put("If", NodeType.nd_If); str_to_nodes.put("While", NodeType.nd_While); str_to_nodes.put("Prtc", NodeType.nd_Prtc); str_to_nodes.put("Prts", NodeType.nd_Prts); str_to_nodes.put("Prti", NodeType.nd_Prti); str_to_nodes.put("Assign", NodeType.nd_Assign); str_to_nodes.put("Negate", NodeType.nd_Negate); str_to_nodes.put("Not", NodeType.nd_Not); str_to_nodes.put("Multiply", NodeType.nd_Mul); str_to_nodes.put("Divide", NodeType.nd_Div); str_to_nodes.put("Mod", NodeType.nd_Mod); str_to_nodes.put("Add", NodeType.nd_Add); str_to_nodes.put("Subtract", NodeType.nd_Sub); str_to_nodes.put("Less", NodeType.nd_Lss); str_to_nodes.put("LessEqual", NodeType.nd_Leq); str_to_nodes.put("Greater", NodeType.nd_Gtr); str_to_nodes.put("GreaterEqual", NodeType.nd_Geq); str_to_nodes.put("Equal", NodeType.nd_Eql); str_to_nodes.put("NotEqual", NodeType.nd_Neq); str_to_nodes.put("And", NodeType.nd_And); str_to_nodes.put("Or", NodeType.nd_Or); if (args.length > 0) { try { s = new Scanner(new File(args[0])); n = load_ast(); interpret(n); } catch (Exception e) { System.out.println("Ex: "+e.getMessage()); } } } }
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
Generate a C translation of this Java snippet without changing its computational steps.
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str_to_nodes = new HashMap<>(); static class Node { public NodeType nt; public Node left, right; public String value; Node() { this.nt = null; this.left = null; this.right = null; this.value = null; } Node(NodeType node_type, Node left, Node right, String value) { this.nt = node_type; this.left = left; this.right = right; this.value = value; } public static Node make_node(NodeType nodetype, Node left, Node right) { return new Node(nodetype, left, right, ""); } public static Node make_node(NodeType nodetype, Node left) { return new Node(nodetype, left, null, ""); } public static Node make_leaf(NodeType nodetype, String value) { return new Node(nodetype, null, null, value); } } static enum NodeType { nd_None(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"), nd_Sequence("Sequence"), nd_If("If"), nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"), nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"), nd_Mod("Mod"), nd_Add("Add"), nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"), nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or"); private final String name; NodeType(String name) { this.name = name; } @Override public String toString() { return this.name; } } static String str(String s) { String result = ""; int i = 0; s = s.replace("\"", ""); while (i < s.length()) { if (s.charAt(i) == '\\' && i + 1 < s.length()) { if (s.charAt(i + 1) == 'n') { result += '\n'; i += 2; } else if (s.charAt(i) == '\\') { result += '\\'; i += 2; } } else { result += s.charAt(i); i++; } } return result; } static boolean itob(int i) { return i != 0; } static int btoi(boolean b) { return b ? 1 : 0; } static int fetch_var(String name) { int result; if (globals.containsKey(name)) { result = globals.get(name); } else { globals.put(name, 0); result = 0; } return result; } static Integer interpret(Node n) throws Exception { if (n == null) { return 0; } switch (n.nt) { case nd_Integer: return Integer.parseInt(n.value); case nd_Ident: return fetch_var(n.value); case nd_String: return 1; case nd_Assign: globals.put(n.left.value, interpret(n.right)); return 0; case nd_Add: return interpret(n.left) + interpret(n.right); case nd_Sub: return interpret(n.left) - interpret(n.right); case nd_Mul: return interpret(n.left) * interpret(n.right); case nd_Div: return interpret(n.left) / interpret(n.right); case nd_Mod: return interpret(n.left) % interpret(n.right); case nd_Lss: return btoi(interpret(n.left) < interpret(n.right)); case nd_Leq: return btoi(interpret(n.left) <= interpret(n.right)); case nd_Gtr: return btoi(interpret(n.left) > interpret(n.right)); case nd_Geq: return btoi(interpret(n.left) >= interpret(n.right)); case nd_Eql: return btoi(interpret(n.left) == interpret(n.right)); case nd_Neq: return btoi(interpret(n.left) != interpret(n.right)); case nd_And: return btoi(itob(interpret(n.left)) && itob(interpret(n.right))); case nd_Or: return btoi(itob(interpret(n.left)) || itob(interpret(n.right))); case nd_Not: if (interpret(n.left) == 0) { return 1; } else { return 0; } case nd_Negate: return -interpret(n.left); case nd_If: if (interpret(n.left) != 0) { interpret(n.right.left); } else { interpret(n.right.right); } return 0; case nd_While: while (interpret(n.left) != 0) { interpret(n.right); } return 0; case nd_Prtc: System.out.printf("%c", interpret(n.left)); return 0; case nd_Prti: System.out.printf("%d", interpret(n.left)); return 0; case nd_Prts: System.out.print(str(n.left.value)); return 0; case nd_Sequence: interpret(n.left); interpret(n.right); return 0; default: throw new Exception("Error: '" + n.nt + "' found, expecting operator"); } } static Node load_ast() throws Exception { String command, value; String line; Node left, right; while (s.hasNext()) { line = s.nextLine(); value = null; if (line.length() > 16) { command = line.substring(0, 15).trim(); value = line.substring(15).trim(); } else { command = line.trim(); } if (command.equals(";")) { return null; } if (!str_to_nodes.containsKey(command)) { throw new Exception("Command not found: '" + command + "'"); } if (value != null) { return Node.make_leaf(str_to_nodes.get(command), value); } left = load_ast(); right = load_ast(); return Node.make_node(str_to_nodes.get(command), left, right); } return null; } public static void main(String[] args) { Node n; str_to_nodes.put(";", NodeType.nd_None); str_to_nodes.put("Sequence", NodeType.nd_Sequence); str_to_nodes.put("Identifier", NodeType.nd_Ident); str_to_nodes.put("String", NodeType.nd_String); str_to_nodes.put("Integer", NodeType.nd_Integer); str_to_nodes.put("If", NodeType.nd_If); str_to_nodes.put("While", NodeType.nd_While); str_to_nodes.put("Prtc", NodeType.nd_Prtc); str_to_nodes.put("Prts", NodeType.nd_Prts); str_to_nodes.put("Prti", NodeType.nd_Prti); str_to_nodes.put("Assign", NodeType.nd_Assign); str_to_nodes.put("Negate", NodeType.nd_Negate); str_to_nodes.put("Not", NodeType.nd_Not); str_to_nodes.put("Multiply", NodeType.nd_Mul); str_to_nodes.put("Divide", NodeType.nd_Div); str_to_nodes.put("Mod", NodeType.nd_Mod); str_to_nodes.put("Add", NodeType.nd_Add); str_to_nodes.put("Subtract", NodeType.nd_Sub); str_to_nodes.put("Less", NodeType.nd_Lss); str_to_nodes.put("LessEqual", NodeType.nd_Leq); str_to_nodes.put("Greater", NodeType.nd_Gtr); str_to_nodes.put("GreaterEqual", NodeType.nd_Geq); str_to_nodes.put("Equal", NodeType.nd_Eql); str_to_nodes.put("NotEqual", NodeType.nd_Neq); str_to_nodes.put("And", NodeType.nd_And); str_to_nodes.put("Or", NodeType.nd_Or); if (args.length > 0) { try { s = new Scanner(new File(args[0])); n = load_ast(); interpret(n); } catch (Exception e) { System.out.println("Ex: "+e.getMessage()); } } } }
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");